>>> money = 2000
>>> card = True
>>> if money >= 3000 or card:
... print("택시를 타고 가라")
... else:
... print("걸어가라")
...
택시를 타고 가라
다른 프로그래밍 언어에서 쉽게 볼 수 없는 조건문
1. x in 리스트, x not in 리스트
2. x in 튜플, x not in 튜플
3. x in 문자열, x not in 문자열
>>> pocket = ['paper', 'cellphone', 'money']
>>> if 'money' in pocket:
... print("택시를 타고 가라")
... else:
... print("걸어가라")
...
택시를 타고 가라
조건문에서 아무 일도 하지 않게 설정하고 싶다면
>>> pocket = ['paper', 'money', 'cellphone']
>>> if 'money' in pocket:
... pass
... else:
... print("카드를 꺼내라")
...
아래와 같이 간단하게 작성할 수 있다
>>> if 'money' in pocket: pass
... else: print("카드를 꺼내라")
조건문이 참인 경우 if 조건문 else 조건문이 거짓인 경우
>>> if score >= 60
... message = "success"
... else:
... message = "failure"
아래와 같이 작성할 수 있다.
message = "success" if score >= 60 else "failure"
break, continue 다른 프로그래밍 언어와 사용법 동일
continue 다른 프로그래밍 언어와 동일하게 사용
1. 전형적인 for문
>>> test_list = ['one', 'two', 'three']
>>> for i in test_list:
... print(i)
one
two
three
>>> a = [(1,2), (3,4), (5,6)]
>>> for (first, last) in a:
... print(first + last)
...
3
7
11
>>> a = tange(1,11)
>>> a
range(1,11) //1,2,3,4,5,6,7,8,9,10
[표현식 for 항목 in 반복 가능 객체 if 조건]
>>> a = [1,2,3,4]
>>> result = []
>>> for num in a:
... result.append(num*3)
...
>>> print(result)
[3,6,9,12]
아래와 같이 쉽게 만들 수 있다.
>>> a = [1,2,3,4]
>>> result = [num * 3 for num in a]
>>> print(result)
[3, 6, 9, 12]