if 문은 조건을 평가하고 그 조건이 참일 때 코드 블록을 실행
var = 2
if var >= 3: # 조건이 거짓이므로 실행 X
print('크다')
print('참일때 수행')
print('계속')
else를 사용하여 if 조건이 거짓일 때 실행할 코드 블록을 지정
var = 5
if var >= 3: # 조건이 참인지 확인
print('3보다 크다')
else: # 조건이 거짓일 때 실행
print('거짓일 경우 실행 숫자가 적다.')
print('end1')
if 문을 중첩하여 더 복잡한 조건을 처리 가능
money = 1000
age = 23
msg = ''
if money >= 200: # 첫 번째 조건
item = 'apple' # 지역 변수
if age >= 30: # 중첩 조건
msg = 'young'
print('item, msg=', item, msg) # apple, msg 값 출력
elif는 "else if"의 줄임말로, 여러 조건을 순차적으로 확인
jumsu = 95
if jumsu >= 90: # 첫 번째 조건
print('우수')
elif jumsu >= 70: # 두 번째 조건
print('보통')
else: # 모든 조건이 거짓일 때 실행
print('저조')
print('end2')
사용자로부터 값을 입력받고 싶을 때 사용
jum = int(input('정수입력?'))
if 90 <= jum <= 100: # 조건 범위 확인
grade = '우수3'
elif 70 <= jum < 90:
grade = '보통3'
else:
grade = '저조3'
print(f'결과 {jum} 등급 => {grade}') # 결과 출력
while 문은 조건이 참인 동안 코드 블록을 반복해서 실행
a = 1
while a <= 5: # 조건이 참인 동안 반복
print(a, end=',')
a += 1 # 변수 증가
print('\na:', a) # 최종 값 출력
while 문을 중첩하여 더 복잡한 반복을 처리
i = 1
while i <= 3: # 첫 번째 반복
j = 1
while j <= 4: # 중첩 반복
print(f'i = {i}, j = {j}')
j += 1
i += 1
print('while 구문 종료됨!')
for 문은 시퀀스(리스트, 튜플, range 등)를 반복
# 리스트
colors = ['red', 'green', 'blue', 'white', 'black']
for color in colors:
print(color, end=' ')
# 집합 (순서 없음)
colors = {'red', 'green', 'blue'}
for color in colors:
print(color, end=' ')
# 튜플
t = (1, 2, 3)
for num in t:
print(num, end=',')
# 딕셔너리
soft = {'java': '웹용언어', 'python': '만능언어', 'maria': 'db'}
for key, value in soft.items(): # 키와 값 동시에 반복
print(f'{key}, {value}')
for n in range(2, 10): # 2단부터 9단까지
print(f'--{n}단--')
for i in range(1, 10): # 각 단의 곱셈
print(f'{n} * {i} = {n * i}')코드를 입력하세요
i = 1
hap = 0
while i <= 100: # 1부터 100까지
if i % 3 == 0: # 3의 배수인지 확인
hap += i
print(f'i => {i}, hap => {hap}')
i += 1
print('합은', hap) # 최종 합 출력
coffee = 3
while True: # 무한 반복
money = int(input('지불할 금액입력?'))
if money == 3000: # 정확한 금액
print('커피 한잔 받으세요')
coffee -= 1
elif money > 3000: # 금액이 많은 경우
print(f'커피 한잔 받으시고 잔돈 {money - 3000}원 받으세요')
coffee -= 1
else: # 금액이 부족한 경우
print('금액이 부족합니다.')
if not coffee: # 커피가 다 떨어진 경우
print('오늘 장사 끝')
break