<기본 리스트 생성 방법>
# 기존 방식
numbers = [1, 2, 3, 4, 5]
squared_numbers = []
for number in numbers:
squared_numbers.append(number ** 2)
print(squared_numbers) # [1, 4, 9, 16, 25]
<리스트 컴프리핸션 사용>
# 리스트 컴프리핸션 사용
numbers = [1, 2, 3, 4, 5]
squared_numbers = [number ** 2 for number in numbers]
print(squared_numbers) # [1, 4, 9, 16, 25]
<기본 딕셔너리 생성 방법>
# 기존 방식
numbers = [1, 2, 3, 4, 5]
squared_dict = {}
for number in numbers:
squared_dict[number] = number ** 2
print(squared_dict) # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
<딕셔너리 컴프리핸션 사용>
# 딕셔너리 컴프리핸션 사용
numbers = [1, 2, 3, 4, 5]
squared_dict = {number: number ** 2 for number in numbers}
print(squared_dict) # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
<장점>
<단점>
# 리스트 컴프리핸션을 사용하지 않을 경우
names = ["Alice", "Bob", "Charlie"]
uppercase_names = []
for name in names:
uppercase_names.append(name.upper())
print(uppercase_names) # ['ALICE', 'BOB', 'CHARLIE']
# 리스트 컴프리핸션을 사용할 경우
uppercase_names = [name.upper() for name in names]
print(uppercase_names) # ['ALICE', 'BOB', 'CHARLIE']
# 딕셔너리 컴프리핸션을 사용하지 않을 경우
names = ["Alice", "Bob", "Charlie"]
name_length_dict = {}
for name in names:
name_length_dict[name] = len(name)
print(name_length_dict) # {'Alice': 5, 'Bob': 3, 'Charlie': 7}
# 딕셔너리 컴프리핸션을 사용할 경우
name_length_dict = {name: len(name) for name in names}
print(name_length_dict) # {'Alice': 5, 'Bob': 3, 'Charlie': 7}
<if 문 기본 구조>
↓
money = True
if money:
print("택시를 타고 가라")
else:
print("걸어 가라")
<비교 연산자>
비교연산자 | 설명 |
---|---|
x < y | x가 y보다 작다 |
x > y | x가 y보다 크다 |
x == y | x와 y가 같다 |
x != y | x와 y가 같지 않다 |
x >= y | x가 y보다 크거나 같다 |
x <= y | x가 y보다 작거나 같다 |
money = 2000
if money>=3000:
print("택시를 타고 가라")
else:
print("걸어가라")
< and or not >
연산자 | 설명 |
---|---|
x or y | x와 y 둘 중 하나만 참이어도 참 |
x and y | x와 y 모두 참이어야 참 |
not x | x가 거짓이면 참 |
money = 2000
card = True
if money>=3000 or card:
print("택시를 타고 가라")
else:
print("걸어가라")
< in not in >
in | not in |
---|---|
x in 리스트 | x not in 리스트 |
x in 튜플 | x not in 튜플 |
x in 문자열 | x not in 문자열 |
1 in [1, 2, 3]
1 not in [1, 2, 3]
pocket = ['paper', 'cellphone', 'money']
if 'money' in pocket:
print("택시를 타고 가라")
else:
print("걸어가라")
<다양한 조건은 elif>
pocket = ['paper', 'cellphone']
card = True
if 'money' in pocket:
print("택시를 타고가라")
elif card:
print("택시를 타고가라")
else:
print("걸어가라")
money = 5000
if money<=3000:
print("걸어가라")
elif money<=4000:
print("버스타라")
elif money<=10000:
print("택시타라")
else:
print("비행기 타라")
<if 문을 패스 하고 싶으면?>
pocket = ['paper', 'money', 'cellphone']
if 'money' in pocket:
pass
else:
print("카드를 꺼내라")
<for 문 기본 구조>
for 변수 in 리스트(또는 튜플, 문자열):
수행할_문장1
수행할_문장2
<리스트를 활용한 for문>
test_list = ['one', 'two', 'three']
for i in test_list:
print(i)
# 연습문제
marks = [90, 25, 67, 45, 80] # 학생들의 시험 점수 리스트
number = 0 # 학생에게 붙여 줄 번호
for mark in marks: # 90, 25, 67, 45, 80을 순서대로 mark에 대입
number = number +1
if mark >= 60:
print("%d번 학생은 합격입니다." % number)
else:
print("%d번 학생은 불합격입니다." % number)
<range를 활용한 for문>
a = range(10)
a
for i in range(1,10):
print(i)
for i in range(1,10,2):
print(i)
add = 0
for i in range(1, 11):
add = add + i
print(add)
< for문과 continue>
marks = [90, 25, 67, 45, 80]
number = 0
for mark in marks:
number = number +1
if mark < 60:
continue
print("%d번 학생 축하합니다. 합격입니다. " % number)
<while 문 기본 구조>
while 조건문:
수행할_문장1
수행할_문장2
수행할_문장3
treeHit = 0
while treeHit < 10:
treeHit = treeHit +1
print("나무를 %d번 찍었습니다." % treeHit)
if treeHit == 10:
print("나무 넘어갑니다.")
<while문 강제로 빠져나가기 → break>
ex) 커피 자판기
coffee = 10
money = 300
while money:
print("돈을 받았으니 커피를 줍니다.")
coffee = coffee -1
print("남은 커피의 양은 %d개입니다." % coffee)
if coffee == 0:
print("커피가 다 떨어졌습니다. 판매를 중지합니다.")
break
<while 문과 continue>
a = 0
while a < 10:
a = a + 1
if a % 2 == 0: continue
print(a)