if <조건문>:
<수행할 문장>
❗ 들여쓰기가 매우 중요함
bool 자료형을 사용해 bool 자료형으로 만들어도 됨bool 자료형
: <, >, ==, !=, >=, <=, and, or, not, &, |, int, not in
자료형의 True/False도 가능
| 값 | True/False |
|---|---|
| "python" | 참 |
| "" | 거짓 |
| [1, 2, 3] | 참 |
| [] | 거짓 |
| () | 거짓 |
| {} | 거짓 |
| 1 | 참 |
| 0 | 거짓 |
| None | 거짓 |
| 비교연산자 | 설명 |
|---|---|
| x<y | x가 y보다 작다 |
| x>y | x가 y보다 크다 |
| x==y | x와 y가 같다 |
| x!=y | x와 y가 같지 않다 |
| x>=y | x가 y보다 크거나 같다 |
| x<=y | x가 y보다 작거나 같다 |
논리연산자
|연산자|설명|기호|
|::|::|::|
|x or y|x와 y 둘 중에 하나만 참이면 참||
|x and y|x와 y 모두 참이어야 참|&|
|not x|x가 거짓이면 참|not|
포함 연산자
| 연산자 | 설명 |
|---|---|
| in | 포함하면 참 |
| not in | 포함하지 않으면 참 |
ex)
if 1 in [1, 2, 3]:
print("hi")
ex)
pocket = ['paper', 'money', 'cellphone']
if 'money' in pocket:
pass #아무 것도 출력x
else :
print("카드를 꺼내라")
#ex1)
score = 79
if score >= 60:
message = "success"
else:
message = "failure"
print(massage)
#ex2)
message = "success" if score >= 60 else "failure"
print(message)
while<조건문>:
<수행할 문장1>
<수행할 문장2>
<...>
#ex)
coffee = 10
money = 300
while money:
print("돈을 받았으니 커피를 줍니다."
coffee = coffee-1
print("남을 커피의 양은 %d개입니다.") %coffee
if not coffee:
print("커피가 다 떨어졌습니다. 판매를 중지합니다.")
break #10번 반복 후 break를 만나 while문 탈출
#ex)
a = 0
while a<10:
a = a + 1
if a % 2 == 0:
continue
print(a)
while True:
<수행할 문장1>
<수행할 문장2>
<...>
for <변수> in <리스트(또는 튜플, 문자열)>:
<수행할 문장1>
<수행할 문장2>
<...>
#ex1) 리스트
test_list = ["one", "two", "three"]
for i in test_list:
print(i) #one\n two\n three\n 출력
#ex2) 리스트 안의 튜플
a = [(1, 2), (3, 4), (5, 6)]
for (first, last) in a:
print(first+last) #3\n 7\n 11\n 출력
#ex3) 60점이 넘으면 합격, 그렇지 않으면 불합격
marks = [90, 25, 67, 45, 80]
number = 0
for mark in marks:
number = number + 1
if mark>60:
print("%d번 학생은 합격") %number
else :
print("%d번 학생은 불합격") %number
#ex)
marks = [90, 25, 67, 45, 80]
number = 0
for mark in marks:
number = number + 1
if mark<60 :
continue
print("%d번 학생 축하합니다. 합격입니다") %number
#60보다 작을 경우 continue를 만나 아래 코드 생략 후 다음 for문 실행
for i in range(x, y)는 i가 x 이상부터 y 미만만큼 반복 #ex1)
sum = 0
for i in range(1, 11):
sum = sum + 1
print(sum)
#ex2) 구구단
for i in range(2, 10):
for j in range(1, 10):
print(i*j, end = " ") #end = " "는 다음 줄로 넘어가지 않고 공백 한 칸 있는 상태로 만들음
print('')
#ex1)
result = [num*3 for num in a] #a의 값들을 *3한 값들을 리스트 result로 만들어라
#ex 2-1)
result = [num * 3 for num in a if num%2==0]
#ex 2-2)
result = []
for num in a:
if num%2==0:
result.append(num*3)
#ex 3-1)
result = [x*y for x in range(2, 10) for y in range(1, 10)]
#ex 3-2)
result = []
for x in range(2, 10):
for y in range(1, 10):
result.append(x*y)
<[출처] 조코딩, "최신 파이썬 코딩 무료 강의", https://www.youtube.com/watch?v=KL1MIuBfWe0&list=PLU9-uwewPMe2AX9o9hFgv-nRvOcBdzvP5> 을 참고하여 작성한 글입니다.