22.11.28~22.11.29
범위 : 점프 투 파이썬 1장~3장
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
pocket=[‘’paper’, ’money’, ‘cellphone’]
If ‘money’ in pocket:
pass
else:
print(“카드를 꺼내라”)
pocket=[‘’paper’, ’money’, ‘cellphone’]
If ‘money’ in pocket:
pass
elif ‘paper’ in pocket:
print(“택시를 타고가라”)
else:
print(“걸어가라”)
if score >= 60:
mseeage=“success”
else:
message=“failure”
message = “success” if score >= 60 else “failure”
treeHit = 0
while treeHit < 10:
treeHit = treeHit + 1
print("나무를 %d번 찍었습니다." %treeHit)
if treeHit == 10:
print("나무 넘어갑니다.")
기본 예시
list_te=['one', 'two', 'three']
for i in list_te:
print(i)
리스트 요소가 튜플일 때는 각각의 요소가 ()
안의 변수로 대입됨
testlist=[(1, 2), (3, 4), (5, 6)]
for (first, last) in a:
print(first + last)
range함수는 숫자 리스트를 자동으로 만들어줌
a = range(10)
a : range(0,10)
range(10)은 0부터 10 미만의 숫자를 포함하는 range 객체임. 끝 숫자가 포함되지 않는 것이 포인트
a = 0
for i in range(1,11):
a = a + i
print(a)
일반적인 for문
a = [1, 2, 3, 4]
result = []
for num in a:
result.append(num * 3)
print(result)
리스트 컴프리헨션을 사용한 for문
a = [1, 2, 3, 4]
result = [num * 3 for num in a]
print(result)
리스트 컴프리헨션 안에는 if조건도 사용할 수 있음
a = [1, 2, 3, 4]
result = [num * 3 for num in a if num % 2 == 0]
print(result)
[표현식 for 항목 in 반복가능객체 if 조건문]
이 기본 형식인데 if 조건문은 생략 가능함