상세 컨텐츠

본문 제목

[Python] while 문, if elif else 문

Python

by TUZA 2024. 1. 15. 16:21

본문

#조건문

 

파이썬에서 조건문 사용 시 'if' 를 사용한다.

#조건문
"""if condition:
	print("write the code to run")"""

if 10 > 5:
	print("True!")

a = 10
if a == 10:
	print("Good Job!")

 

if True 면 그에 해당하는 내용물이 나올 것이고, 반대로 False면 if문은 종료된다.

if문은 여러 가지 방식으로 활용할 수 있는데 elif와 else를 사용하면 보다 세세하게 조건을 따질 수 있다.

winner = 10

if winner > 10:
	print("winner is greater than 10")
elif winner < 10:
	print("winner is less than 10")
else:
	print("Winner is 10")

 

만약 winner가 10보다 크다면 "winner is greater than 10"이 출력될 것이고,

그렇지 않다면(else)가 출력된다.

 

여기서 elif를 넣어서 10보다 작은 경우도 따질 수 있다.

만약 winner가 10보다 작다면 "winner is less than 10" 이 출력될 것이다.

그러면 이 경우엔 winner가 10이여야만 "winner is 10" 이 출력된다.

 

#input활용하기

input을 활용해서 사용자의 입력값을 받아올 수 있다.

다음과 같이 작성해보자.

#input을 통해서 프로그램에 질문할 수 있음.
age = input("How old are you?")

print(f"user answer = {age}")


age = input("How old are you? ")
print(type(age)) #str
=> age=int(input("How old are you?"))

 

input으로 받아오는 값의 type은 모두 str이다.

그래서 현 상황에 받는 타입으로 데이터형식을 변형시켜줘야한다.

지금의 경우 integer가 필요한 상황이니

int(input())으로 받아오는 값을 int로 변경시켜준다.

 

#or 과 and

수학을 공부하다보면 흔히 볼 수 있는 조건식이 or과 and이다.

프로그래밍에서도 동일하게 적용한다. 다음 표를 참고해서 or과 and를 적용하자.

#조건문 사용 시 True 와 False 출력값

True or True = True
True or False = True
False or True = True
False or False = False

True and True == True
False and True == False
True and False == False
False and False == False

 

#while 

while의 경우 True 상태면 무한대로 반복을 한다.

그래서 특정 조건에 부합하다면 False로 바꿔주는 작업이 필요하다.

 

while 을 활용해서 다음과 같은 게임을 만들었다.

from random import randint
print("Welcome to Python Casino")

you_life = 5 # 사용자는 5개의 목숨을 가진다.
pc_choice = randint(1,100)# random 모듈에서 randint 함수를 가져온다.
playing = True #while을 on 상태로 만든다.
while playing:
	print(f"you_life: {you_life}") # 사용자에게 목숨을 표시해준다.
	if you_life !=0: # 목숨이 0이 아니라면 게임 진행. 
		user_choice = int(input("Choose number(1-100): "))	
		if user_choice == pc_choice:
			print("You Win!")
			playing = False # 정답을 맞추면 playing값을 false로 변경하여 게임 종료시킴.
		elif user_choice > pc_choice:
			you_life-=1 #틀릴 때 마다 목숨이 1개씩 줄어든다.
			print(f"Lower! Computer chose {pc_choice}")
		elif user_choice < pc_choice:
			you_life-=1 #틀릴 때 마다 목숨이 1개씩 줄어든다.
			print(f"Higher! Computer chose {pc_choice}")
	else:
		print("You Lose!")# 목숨이 0이면 게임 종료.
		playing = False

 

 

 

반응형

'Python' 카테고리의 다른 글

[Python] 딕셔너리(dictionary)  (0) 2024.01.16
[Python] data structure ( 데이터 구조 )  (2) 2024.01.16
[Python] return  (1) 2024.01.15
[Python] 파이썬 계산기 연습  (0) 2024.01.15
[Python] default Parameter (디폴트 파라미터)  (1) 2024.01.15

관련글 더보기