[기본구조] 

1
2
3
4
5
6
7
8
if 조건문:
    수행할 문장1
    수행할 문장2
    ...
else:
    수행할 문장A
    수행할 문장B
    ...
cs



[사용 예]

1
2
3
4
5
6
7
8
money = True
if money:
    print("택시를 타고 가라")
else:
    print("걸어 가라")
 
# 결과 
# 택시를 타고 가라
cs



[비교 연산자]

비교연산자

설명

x < y

x가 y보다 작다

x > y

x가 y보다 크다

x == y

x와 y가 같다

x != y

x와 y가 같지 않다

x >= y

x가 y보다 크거나 같다

x <= y

x가 y보다 작거나 같다


1
2
3
4
5
6
7
8
9
money = 2000
if money >= 3000:
    print("택시를 타고 가라")
else:
    print("걸어가라")
 
 
# 결과
#  걸어가라
cs



[and, or, not]

연산자

설명

x or y

x와 y 둘중에 하나만 참이면 참이다

x and y

x와 y 모두 참이어야 참이다

not x

x가 거짓이면 참이다


1
2
3
4
5
6
7
8
9
10
money = 2000
card = True
if money >= 3000 or card:
    print("택시를 타고 가라")
else:
    print("걸어가라")
 
# 결과
# 택시를 타고 가라
 
cs


[in, not in]

in

not in

x in 리스트

x not in 리스트

x in 튜플

x not in 튜플

x in 문자열

x not in 문자열


1
2
3
4
5
6
7
8
9
10
pocket = ['paper''cellphone''money']
if 'money' in pocket:
    print("택시를 타고 가라")
else:
    print("걸어가라")
 
 
# 결과
# 택시를 타고 가라
 
cs



[pass]

조건문에서 아무 일도 하지 않게 설정

1
2
3
4
5
6
7
8
9
10
11
12
13
pocket = ['paper''money''cellphone']
if 'money' in pocket:
    pass 
else:
    print("카드를 꺼내라")
 
    
print("pass 했습니다.")
 
 
# 결과
# pass 했습니다.
 
cs


[elif]

다양한 조건 판단

1
2
3
4
5
6
7
8
9
10
11
12
13
pocket = ['paper''cellphone']
card = True
if 'money' in pocket:
     print("택시를 타고가라")
elif card: 
     print("택시를 타고가라")
else:
     print("걸어가라")
 
        
# 결과
# 택시를 타고가라
 
cs


[if문 한 줄로 작성하기]

수행할 문장이 한 줄일 때 : 뒤에 바로 수행할 문장을 적을 수 있다.

1
2
3
4
5
6
7
8
9
10
11
12
pocket = ['paper''cellphone']
 
if 'money' in pocket:
    pass 
else:
    print("카드를 꺼내라")
 
    
# 한 줄로 작성

if 'money' in pocket: pass
elseprint("카드를 꺼내라")
 
cs


[조건부 표현식]

조건문이 참인 경우 if 조건문 else 조건문이 거짓인 경우

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
score = 70
message = "success" if score >= 60 else "failure"
print(message)
 
# 아래와 같은 의미 
if score >= 60:
    message = "success"
    
else:
    message = "failure"
    
print(message)
 
# 결과
# success
# success
cs

출처- wikidocs 점프 투 파이썬 (박응용)





+ Recent posts