본문 바로가기

Python

[Python] 기초 문법 정리(숫자형, 문자열, 리스트, 튜플, 딕셔너리)

반응형

이번 포스팅은 파이썬의 기초 문법에 대해 소개합니다~!!!


변수의 종류
  • 변수의 종류 : 숫자, 문자, 논리 (true,false), null
 
# 정수형
num_int = 1 
print(num_int)
print(type(num_int))
1
<class 'int'>

정수형 데이터를 num_int 변수에 담아 출력합니다.

변수 앞에 type를 붙여서 출력하면 변수의 type를 확인할 수 있습니다.

# 실수형
num_float = 0.2
print(num_float)
print(type(num_float))
0.2
<class 'float'>
# 논리 자료형
bool_true = False
print(bool_true)
print(type(bool_true))
False
<class 'bool'>
# NULL 자료형
none_x = None
print(none_x)
print(type(none_x))
None
<class 'NoneType'>

 

4가지 자료형 : Scalar 자료형
  • int. float, bool, NoneType
  • 더는 나눌 수 없는 최소단위의 자료형
    • 이 객체 하나로는 반복문 사용이 불가

1. 정수형 사칙연산

  • 결과값의 자료형 확인
  • 특이한 사칙연산자 하나 있음(나눗셈)
a = 4
b = 2

c = a / b

print (c)
print(type(c))
2.0
<class 'float'>

사칙연산 중 나눗셈만 예외적으로 int 형 에서 float 형으로 변환되는 것을 확인 할 수 있습니다.

2. 논리형 연산자

  • AND / OR / NOT(옵션)
print(True and True)
print(True and False)
print(False and True)
print(False and False)
True
False
False
False
print(True or True)
print(True or False)
print(False or True)
print(False or False)
True
True
True
False

3. 부등호 연산자

  • '>' ,  '<' ,  '>='  , '<='
print(3 >= 3)
print(4 >= 6)
True
False

 

두 개의 값 비교
  • 입력받아서 True, False가 나오도록 간단한 프로그램 작성
  • 형변환 배우기
var = input("값을 입력해주세요!")
print("----------")
print(var)
print(type(var))
값을 입력해주세요!123
----------
123
<class 'str'>
var1 = float(input("값을 입력해주세요!"))
var2 = float(input("값을 입력해주세요!"))

print(var1 + var2)
값을 입력해주세요!4.12
값을 입력해주세요!5.32
9.440000000000001
print(var1 > var2)
False
파이썬에서 많이 사용되는 함수
# Capitallize
text = 'i love YOU' # str 클래스 객체
print(type(text))
result = text.capitalize()
print(result)
<class 'str'>
I love you
text = '  python is best  '
print(text)
result = text.strip()
print(result)
 python is best  
python is best
# split
# 문장을 분리하는 메서드

text = "올 한 해는 눈이 많이 내렸다."
result = text.split(' ')
print(result)
['올', '한', '해는', '눈이', '많이', '내렸다.']
리스트 자료형
 

5. Data Structures

This chapter describes some things you’ve learned about already in more detail, and adds some new things as well. More on Lists: The list data type has some more methods. Here are all of the method...

docs.python.org

a = [100,200,300]
b = [400, 500, 600]
a.append(400)
a.append(500)
a.append(600)
a.append(b)
print(a)
[100, 200, 300, 400, 500, 600, [400, 500, 600]]
a = [100,200,300]
b = [400, 500, 600]

# 반복문 활용 (복잡)
# extend()
a.extend(b)

print(a)

 

1. 리스트 중간에 새로운 값을 추가

# insert()
a = [100,200,300]

# 100과 200사이에 150을 추가
a.insert(1, 150)
print(a)
[100, 150, 200, 300]

2. 리스트 내 특정 값 삭제

 

a = [1,2,1,2]
a.remove(1)
print(a)

a.remove(1)
print(a)
[2, 1, 2]
[2, 2]
a = [0,1,2,3,4,5,6,7,8,9]

# 1 삭제
del a[1] # -- 인덱스 번호
print(a)

# 범위로 삭제
del a[1:5]
print(a)
[0, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 6, 7, 8, 9]

3. 전체 리스트 삭제

a = [1,1,1,1,1,1]
print(a)

a.clear()
print(a)
[1, 1, 1, 1, 1, 1]
[]

4. 인덱스 번호 찾기

a = ["Gold", "Gold", "Silver", "Silver"]

# silver가 처음 등장하는 인덱스 번호 
print(a.index("Silver"))
2

5. 리스트 정렬

a = [1,6,5,2,3,4]
a.sort()
print(a)
[1, 2, 3, 4, 5, 6]
#  내림차순으로 정렬
a.sort(reverse=True)
print(a)
[6, 5, 4, 3, 2, 1]

- 정렬이 불가능한 경우

a = [1,6,5,2,3,4,"a"]
a.sort()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-23-17a5e9f73e9a> in <module>
      1 a = [1,6,5,2,3,4,"a"]
----> 2 a.sort()

TypeError: '<' not supported between instances of 'str' and 'int'

만약 리스트 내에 type이 다른 문자들이 섞여있으면 정렬이 불가능하다.

 

- 최대값, 최소값, 길이 찾기

 

a = [1,6,5,2,3,4]
print(min(a))
print(max(a))
print(len(a))
1
6
6
튜플(Tuple)

- 튜플이 리스트와 다른 점은 변형이 불가능 하다는 것이다. (추가, 삭제 불가능)

tuple1 = (0, )
tuple2 = (0,1,2)
tuple3 = 0,1,2,3

print(tuple1)
print(tuple2)
print(tuple3)

print(type(tuple1))
print(type(tuple2))
print(type(tuple3))
(0,)
(0, 1, 2)
(0, 1, 2, 3)
<class 'tuple'>
<class 'tuple'>
<class 'tuple'>

- , 가 있어야 튜플이 생성됩니다. , 가 없으면 아래 코드의 결과처럼 tuple이 생성되지 않은 것을 볼 수 있습니다.

tuple0 = (1)
print(tuple0)
print(type(tuple0))
1
<class 'int'>
a= (0,1,2, 'A')
del a[3]
print(a)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-29-8b8a5b0d74b4> in <module>
      1 a= (0,1,2, 'A')
----> 2 del a[3]
      3 print(a)

TypeError: 'tuple' object doesn't support item deletion

삭제하려고 하면 위처럼 에러가 뜹니다. 

1. 튜플 인덱싱 및 슬라이싱

 

tuple0 = (0,1,2,3,4,5,6,7,8,9)
print(tuple0[0])
print(tuple0[::3])
0
(0, 3, 6, 9)
tuple1 = 1,2
tuple2 = 3,4

print(tuple1+tuple2)
(1, 2, 3, 4)
딕셔너리(Dictionary)
  • JSON과 유사한 자료형
# {key:value}
number = {1:"one", 2:"two", 3:"three"}
print(number)
{1: 'one', 2: 'two', 3: 'three'}
country_capital = {"한국":"서울", "일본":"동경","중국":"북경"}
print(country_capital)
{'한국': '서울', '일본': '동경', '중국': '북경'}
print(number[1])
print(country_capital['한국'])
one
서울
number[4] = 'four'
print(number)

country_capital['미국'] = '뉴욕'
print(country_capital)
{1: 'one', 2: 'two', 3: 'three', 4: 'four'}
{'한국': '서울', '일본': '동경', '중국': '북경', '미국': '뉴욕'}

1. 틀린 값 수정하기

미국의 수도는 뉴욕이 아닌 워싱턴입니다.

뉴욕을 워싱턴으로 수정해보겠습니다.

country_capital['미국'] = '워싱턴'
print(country_capital)
{'한국': '서울', '일본': '동경', '중국': '북경', '미국': '워싱턴'}

2. 삭제하기

 

del country_capital['미국']
print(country_capital)
{'한국': '서울', '일본': '동경', '중국': '북경'}

3. Dictionary 메서드

  • key() : 키 값만 출력
  • values() : value값만 출력
result = country_capital.keys()
print(result)
print(type(result))
dict_keys(['한국', '일본', '중국'])
<class 'dict_keys'>
result = country_capital.values()
print(result)
print(type(result))
dict_values(['서울', '동경', '북경'])
<class 'dict_values'>

만약 type을 list로 변형해주고 싶다면, 앞에 list를 붙이면 됩니다.

result = list(country_capital.items())
print(result)
print(type(result))
[('한국', '서울'), ('일본', '동경'), ('중국', '북경')]
<class 'list'>

 

 

 

[출처] 휴먼교육센터 -  Evan 강사님

반응형