본문 바로가기

파이썬 후다닥⚡️

파이썬 문법 정리 1⚡️ 출력, 변수, 연산, 리스트

1️⃣ 출력하기

print("hello")

2️⃣ 변수

a = 10 #정수
b = 90.0 #소수
c = "hello world" #문자열
d = True #bool
e = (1, 2, 3) #튜플
f = [1, 2, 3] #리스트
g = {'name':'jiyo', 'phone':'01012345678', 'birth':'0101'} #딕셔너리

h = 0o177 #팔진수
i = 0xABC #16진수

3️⃣ 연산자

>>> 1 + 1
2

>>> 1 - 2
-1

>>> 2 * 2
4

>>> 3 / 2
1.5

>>> 3 // 2 # 나눗셈 후 소수점 이하 버림
1

>>> 7 % 3 # 나머지 연산
1

>>> 2 ** 5 #거듭제곱
32

4️⃣ 리스트

➰리스트 생성하기➰

a = list()	#빈 리스트 생성
b = [] 		#빈 리스트 생성2
c = [1, 2, 3, 4, 5]
d = [1, 'python', 'love']
e = [1, ['python', 'love'], 2] #이중리스트
f = [1, ['python', [2, 3], 'love'], 4] #삼중리스트

➰리스트 인덱싱하기➰

>>> c[1]
2
>>> c[-1]
5
>>> c[1] + c[2]
5
>>> d[0] + d[1]
TypeError
>>> d[1] + d[2]
'pythonlove'
>>> e[1][0]
'python'
>>> f[1][1][0]
2

➰리스트 슬라이싱➰

>>> c[0:2]
[1, 2]
>>> c[2:3]
[3]
>>> c[:3]
[1, 2, 3]
>>> c[2:]
[3, 4, 5]
>>> c[:]
[1, 2, 3, 4, 5]
>>> f[1][1][0:1]
[2]
# list_name[시작인덱스번호 : n번째 요소(n == 종료인덱스 + 1)]

➰리스트 연산하기➰

>>> list1 = [1, 2, 3]; list2 = [4, 5, 6]
>>> list1 + list2
[1, 2, 3, 4, 5, 6]
>>> list1 * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
>>> len(list1)
3
>>> len(list1[1]) #int형은 길이가 없다
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: object of type 'int' has no len()

# 삼중 리스트
>>> f = [1, ['python', [2, 3], 'love'], 4] 
>>> len(f)
3
>>> len(f[1])
3
>>> len(f[1][1])
2
>>> len(f[1][0]) #리스트 길이가 아니라 문자열의 길이를 셈
6

➰리스트 수정, 삭제

>>> list1 = [1, 2, 3, 4, 5]
>>> list1[-1] = 8
>>> list1
[1, 2, 3, 4, 8]
>>> del list1[4]
>>> list1
[1, 2, 3, 4]