Python/Python Language

조건문 (if, elif, else) 작성하기

567Rabbit 2024. 4. 4. 17:14

a, b = 33, 33

 

if b > a:         #1) 참인 경우
    print("b is greater than a")

 

elif a >= b:     #2) 1번 조건이 참이 아닌경우 실행할 another조건
    print("Nop")

 

else:               #3) 거짓인 경우
    print("same same")

 

 

논리연산자 and

-두 조건이 모두 참이어야 True 입니다

if num1 > 0 and num2 > 0:
        print("두 숫자 모두 양수입니다.")
    else:
        print("하나 이상의 숫자가 양수가 아닙니다.")

 

 

논리연산자 or

-두 조건 중 하나만 참이어도 True 입니다    

if num > 10 or num < 20:
        print("입력한 숫자가 10보다 크거나 20보다 작습니다.")
    else:
        print("입력한 숫자가 10보다 작거나 20보다 큽니다.")

 

 


논리연산자 not

- 조건문의 결과를 뒤집는데 사용됩니다

 

nt1, nt2 = 33, 200

 

if not nt1 > nt2 :
    print("nt1 is Not greater than nt2")

 


Pass

- if문은 비워둘 수 없지만 필요한 경우 통과시킬 수 있습니다
nn, mm = 33, 200
if mm > nn :
    pass 

 

 

 

예제)

 

text에 무료가 있는 경우에만 인쇄를 합니다

 

txt = "the best things in life are free!"
print("free" in txt)      #true



if "무료" in text:
    print('yes')    #true의 경우 인쇄

else:

    print('no')    #false의 경우 인쇄

 

 

 

fruit = list(["사과", "포도", "홍시"])



fruits = input("좋아하는 과일은? ")  #사용자에게 값을 입력받습니다

if fruits == fruit[0] :
    print("정답입니다")
elif fruits == fruit[1] :
    print("정답입니다")
elif fruits == fruit[2] :
    print("정답입니다")    
else :
    print("오답입니다")

 

 

 

fruit = list({"봄" : "딸기", "여름" : "토마토", "가을" : "사과"}.keys())



fruits = input("제가좋아하는계절은: ")   #사용자에게 값을 입력받습니다
fruits = fruits.strip()

if fruits in fruit :
    print("정답입니다") 
else:
    print("오답입니다")

 

 

fruit = {"봄" : "딸기", "여름" : "토마토", "가을" : "사과"}.values()



fruits = input("제가좋아하는과일은: ")

if fruits in fruit :
    print("정답입니다") 
else:
    print("오답입니다")

 

 

grade=input("점수를 입력하세요: ")



print("score: "+grade)

if int(grade) >= 81 :
    print("grade is A")
elif int(grade) >= 61 :
    print("grade is B")
elif int(grade) >= 41 :
    print("grade is C")
elif int(grade) >= 21 :
    print("grade is D")
else :
    print("grade is F")