if - else
print("Tell me your age")
myage = int(input())
if myage < 30:
print("Welcome to the Club")
else:
print("Oh! No. You ar not accepted")
조건 판단 방법
비교연산자 | 비교상태 | 설명 |
---|---|---|
x < y | ~ 보다 작음 | x가 y보다 작은지 검사 |
x > y | ~ 보다 큼 | x가 y보다 큰지 검사 |
x == y | 같음 | x와 y가 같은지 검사( 값 비교 ) |
x is y | 같음 | x와 y가 같은지 검사( 메모리 주소 비교 ) |
x !- y | 같지 않음 | x와 y가 다른지 검사( 값 비교 ) |
x is not y | 같지 않음 | x와 y가 다른지 검사( 메모리 주소 비교 ) |
x >= y | 크거나 같음 | x가 y보다 이상인지 검사 |
x <= y | 작거나 같음 | x가 y보다 이하인지 검사 |
논리 키워드
a | 논리연산자 | b | 결과 |
---|---|---|---|
True | and | True | True |
True | and | False | False |
False | or | False | False |
True | or | False | True |
삼항 연산자
value = 12
is_even = True if value % 2 == 0 else False
print(is_even)
>>> True
elif 구문
if score >= 90: grade = 'A'
elif score >= 80: grade = 'B'
elif score >= 70: grade = 'C'
elif score >= 60: grade = 'D'
else: grade = 'F'
연습문제
year = int(input("태어난 년도를 입력하세요 : "))
age = 2022 - year + 1
school = ""
if 20 <= age and age <= 26:
print("대학생")
elif 17 <= age and age < 20:
print("고등학생")
elif 14 <= age and age < 17:
print("중학생")
elif 8 <= age and age < 14:
print("초등학생")
else:
print("학생이 아닙니다")
for
반복 실행 횟수가 명확할 때 사용
기본적인 for문
for looper in [1,2,3,4,5]:
print(f"{looper} : Hello")
for looper in range(0,5):
print(f"{looper} : Hello")
# 간격을 두고 세기
for looper in range(0,10,2):
print(f"{looper} : Hello")
# 역순으로 세기
for looper in range(10,1,-1):
print(f"{looper} : Hello")
for i in "abcdef":
print(i)
while
반복 실행 횟수가 명확하지 않을 때 수행
무한 루프에 빠지지 않게 주의!
코드가 복잡하거나 확인해야 할 것이 많으면 여러 개의 print를 사용해 debugging을 확인
기본적인 while문
i = 0
while i < 10:
print(f'{i} : Hello')
i += 1
break
for i in range(10):
if i == 5:
break
print(i)
print("EOP")
continue
for i in range(10):
if i == 5: continue
print(i)
print("EOP")
연습문제
x = int(input("몇 단의 구구단을 계산할까요? : "))
for i in range(1,10):
print(f'({x} X {i} = {dan*i}')
sentence = "I love you"
reverse_sentence = ""
for char in sentence:
reverse_sentence = char + reverse_sentence
print(reverse_sentence)
decimal = 10
result = ''
while (decimal > 0):
remainder = decimal % 2
decimal = decimal / 2
result = str(remainder) + result
print(result)
중첩 반복문