늦은 프로그래밍 이야기
조건문, 반복문 본문
조건문
if 문
- 조건을 만족했을 때 특정 코드 실행
money = 5000
if money > 3800: # 불 자료형 비교연산
print('택시 타자') # if 구문에 포함되므로 들여쓰기로 구분.
else
- 조건을 만족하지 않을 때 다른 코드 실행
money = 2000
if money > 3800:
print('택시 타자')
else:
print('걸어 가자') # False 이므로 else문 실행
elif
- 여러가지 조건 판단 시 사용
money = 3000
if money > 3800: # 첫번째 조건 판단
print('택시 타자')
elif money > 1200: # 두번째 조건 판단
print('버스 타자')
else: # 모두 만족하지 않으면 실행
print('걸어 가자')
삼항연산자
- if문 삼항연산자
# 일반적인 if문
money = 2000
if money > 3800:
print('택시')
else:
print('도보')
# 삼항연산자
money = 2000
result = '택시' if money > 3800 else '도보'
print(result)
* (True일 때의 값) if (조건) else (False일 때의 값) 으로 작성.
반복문
for 문
for문
- 리스트 자료의 요소들을 하나씩 반복 출력
- for 변수 in 리스트
fruits = ['사과', '배', '감', '귤']
for fruit in fruits:
print(fruit)
리스트 + 딕셔너리에서의 for 문
people = [
{'name': 'bob', 'age': 20},
{'name': 'carry', 'age': 38},
{'name': 'john', 'age': 7},
{'name': 'smith', 'age': 17},
{'name': 'ben', 'age': 27},
{'name': 'bobby', 'age': 57},
{'name': 'red', 'age': 32},
{'name': 'queen', 'age': 25}
]
for person in people:
name = person['name'] # 변수명['키값']
age = person['age']
print(name, age) # name과 age의 밸류값만 출력.
for문 + if문
for person in people:
name = person['name']
age = person['age']
if age > 20:
print(name, age) # 조건을 충족한 데이터의 name, age 밸류값 출력
- 리스트에서 짝수 요소만 출력
num_list = [1, 2, 3, 6, 3, 2, 4, 5, 6, 2, 4]
for num in num_list:
if num % 2 == 0:
print(num) # 짝수 요소만 출력된다.
for문 + 대입연산
- 리스트 안에 있는 숫자 더하기
result = 0
for num in num_list:
result += num # 반복될 때마다 num을 result에 대입
print(result) # 모든 숫자 더해져 출력
- 리스트에서 짝수가 몇개인지 출력
num_list = [1, 2, 3, 6, 3, 2, 4, 5, 6, 2, 4]
count = 0
for num in num_list:
if num % 2 == 0:
count += 1 # count를 0부터 조건을 충족하는 데이터가 반복될 때마다 1씩 대입
print(count) # 짝수의 총수량이 출력
enumerate, break
- enumerate : for i, 변수 in enumerate(리스트)
for i, person in enumerate(people):
name = person['name']
age = person['age']
print(i, name, age) # 반복 횟수마다 0부터 넘버링
if i > 3:
break # 조건 충족 시 출력 멈춤.
for문 한줄에 쓰기
- 기존 리스트에 2를 곱한 새로운 리스트 만들기
a_list = [1, 3, 2, 5, 1, 2]
b_list = []
for a in a_list:
b_list.append(a*2)
print(b_list) # [2, 6, 4, 10, 2, 4]
- for문을 한줄로 b_list 값에 입력
a_list = [1, 3, 2, 5, 1, 2]
b_list = [a*2 for a in a_list]
print(b_list) # 위와 동일하게 출력
'내일배움캠프 > Python' 카테고리의 다른 글
| 숫자 각 자리수를 리스트 요소로 변환 (0) | 2022.11.16 |
|---|---|
| 반복문으로 2차원 리스트의 요소 출력하기 (0) | 2022.11.16 |
| 함수 (0) | 2022.11.08 |
| 자료형 (1) | 2022.11.08 |
Comments