if 조건문:
수행할 문장1
수행할 문장2
...
else:
수행할 문장A
수행할 문장B
...
>>> money = True
>>> if money:
print('택시탑승')
택시탑승
->money가 True임으로 무조건 실행됨
x < y : x가 y보다 작다
x > y : x가 y보다 크다
x == y : x와 y가 같다
x != y : x와 y가 같지 않다
x >= y : x가 y보다 크거나 같다
x <= y : x가 y보다 작거나 같다
위 연산자들은 bool값을 반환하기 때문에 if 조건문에 사용가능
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
x in 리스트 x not in 리스트
x in 튜플 x not in 튜플
x in 문자열 x not in 문자열
>>> 1 in [1, 2, 3]
True
>>> 1 not in [1, 2, 3]
False
>>> 'a' in ('a', 'b', 'c')
True
>>> 'j' not in 'python'
True
다음과 같이 사용 가능
>>> pocket = ['paper', 'cellphone', 'money']
>>> if 'money' in pocket:
... print("택시를 타고 가라")
... else:
... print("걸어가라")
...
택시를 타고 가라
>>>
>>> pocket = ['paper', 'money', 'cellphone']
>>> if 'money' in pocket:
... pass
... else:
... print("카드를 꺼내라")
...
if <조건문>:
<수행할 문장1>
<수행할 문장2>
...
elif <조건문>:
<수행할 문장1>
<수행할 문장2>
...
elif <조건문>:
<수행할 문장1>
<수행할 문장2>
...
...
else:
<수행할 문장1>
<수행할 문장2>
...
>>> pocket = ['paper', 'money', 'cellphone']
>>> if 'money' in pocket: pass
... else: print("카드를 꺼내라")
...
변수 = 조건문이 참인 경우의 값 if 조건문 else 거짓일 경우 값if score >= 60:
message = "success"
else:
message = "failure"
위 코드를 아래와 같이 변경 가능
message = "success" if score >= 60 else "failure"
while <조건문>:
<수행할 문장1>
<수행할 문장2>
<수행할 문장3>
...
coffee = 10
while True:
money = int(input("돈을 넣어 주세요: "))
if money == 300:
print("커피를 줍니다.")
coffee = coffee -1
elif money > 300:
print("거스름돈 %d를 주고 커피를 줍니다." % (money -300))
coffee = coffee -1
else:
print("돈을 다시 돌려주고 커피를 주지 않습니다.")
print("남은 커피의 양은 %d개 입니다." % coffee)
if coffee == 0:
print("커피가 다 떨어졌습니다. 판매를 중지 합니다.")
break
while True:는 무한 루프임.break를 통해 빠져나올 수 있음>>> a = 0
>>> while a < 10:
... a = a + 1
... if a % 2 == 0: continue
... print(a)
...
1
3
5
7
9
for 변수 in 리스트(또는 튜플, 문자열):
수행할 문장1
수행할 문장2
...
>>> a = [(1,2), (3,4), (5,6)]
>>> for (first, last) in a:
... print(first + last)
...
3
7
11
>>> add = 0
>>> for i in range(1, 11):
... add = add + i
...
>>> print(add)
55
[표현식 for 항목 in 반복가능객체 if 조건문]>>> a = [1,2,3,4]
>>> result = [num * 3 for num in a]
>>> print(result)
[3, 6, 9, 12]
>>> result = [num * 3 for num in a if num % 2 == 0]
>>> print(result)
[6, 12]