프로그래밍/Python

Python Tutorial : While loop [5]

Kimtuna 2016. 4. 15. 09:38

파이썬은 while 키워드로 반복 코드 작성이 가능하다.

다음은 5 라는 숫자를 예측하는 게임

x = 0
while x != 5:
   x = int(input("Guess a number:"))
   
   if x != 5:
      print("Incorrect choice")

print("Correct")


게임 방식을 확장하여 입력한 숫자에 대한 힌트를 추가

x = 0
while x != 5:
   x = int(input("Guess a number:"))
   
   if x != 5:
      print("Incorrect choice")
   if x > 5:
      print("Please enter a smaller number")
   if x < 5:
      print("Please enter a larger number")

print("Correct")


주의 할 점은 while 루프의 조건이 충족되지 않을 경우 무한 루프에 빠지는 문제를 발생시킬 수 있다.