[개념] Chapter04-1 : 파이썬 제어문

Date:     Updated:

카테고리:

태그:

인프런 강의 프로그래밍 시작하기 : 파이썬 입문을 듣고 정리한 내용입니다✏️.

IF 구문 실습

기본 형식

print(type(True)) # 0 이 아닌 수, "abc", [1, 2, 3..], (1, 2, 3) ...
print(type(False)) # 0, "", [], (), {} ...

예1

if True:
    print('Good') # Good

if 'a':
    print('Good') # Good

if False:
    print('Bad')

예2

if False:
    print('Bad!')
else:
    print('Good!')
# 출력 : Good!

관계 연산자( >, >=, <, <=, ==, != )

# 양 변이 같은 경우 참
print(x == y)

# 양 변이 다를 때 참
print(x != y)

# 왼쪽이 클 때 참
print(x > y)

# 왼쪽이 크거나 같을 때 참
print(x >= y)

# 오른쪽이 클 때 참
print(x < y)

# 오른쪽이 크거나 같을 때 참
print(x <= y)

예3

city = ""
if city:
    print("You are in:", city)
else:
    print("Please enter your city")
# 출력 : Please enter your city

예4

city2 = "Seoul"
if city:
    print("You are in:", city2)
else:
    print("Please enter your city")
# 출력 : You are in: Seoul

논리 연산자(and, or, not)

a = 75
b = 40
c = 10

print('and:', a > b and b > c) # a > b > c
# 출력 : and: True

print('or:', a > b or b > c) # a > b
# 출력 : or: True
# or : 앞에 것이 True면 뒤의 연산은 진행하지 않는다.

print('not:', not a > b) # not: False

print('not:', not b > c) # not: False

print(not True) # False
print(not False) # True

산술, 관계, 논리 우선순위

# 산술 > 관계 > 논리
print('e1 : ', 3+12 > 7+3) # e1 : True
print('e2 :', 5 + 10 * 3 > 7 + 3 * 20) # e2 : False
print('e3 :', 5 + 10 > 3 and 7 + 3 == 10) # e3 : True
print('e4 :', 5 + 10 > 0 and not 7 + 3 == 10) # e4 : False

score1 = 90
score2 = 'A'

# 복수의 조건이 모두 참일 경우에 실행
if score1 >= 90 and score2 == 'A':
    print('Pass') # Pass
else:
    print('Fail')

예5

id1 = 'vip'
id2 = 'admin'
grade = 'platinum'

if id1 == 'vip' or id2 == 'admin':
    print('관리자 입장') # 관리자 입장

if id2 == 'admin' and grade == 'platinum':
    print('최상위 관리자') # 최상위 관리자

다중조건문

예6

num = 90

if num >= 90:
    print('Grade : A')
elif num >= 80:
    print('Grade : B')
elif num >= 70:
    print('Grade : C')
else:
    print('Fail')

# 출력 : Grade : A

중첩 조건문

예7

grade = 'A'
total = 95

if grade == 'A':
    if total >= 90:
        print('장학금 100%')
    elif total >= 80:
        print('장학금 80%')
    else:
        print('장학금 50%')
else:
    print('장학금 없음')

# 출력 : 장학금 100%

in, not in

q = [10, 20, 30] # 리스트
w = {70, 80, 90, 100} # 집합
e = {"name": "Lee", "City" : "Seoul", "Grade" : "A"} # 딕셔너리
r = (10, 12, 14)

print(15 in q) # False
print(90 in w) # True
print(12 not in r) # False
print("name" in e) # True
print("Seoul" in e.values()) # True

맨 위로 이동하기

Python 카테고리 내 다른 글 보러가기

댓글남기기