파이썬은 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 루프의 조건이 충족되지 않을 경우 무한 루프에 빠지는 문제를 발생시킬 수 있다.

'프로그래밍 > Python' 카테고리의 다른 글

Python Tutorial : Lists [7]  (0) 2016.04.15
Python Tutorial : Functions [6]  (0) 2016.04.15
Python Tutorial : For loops [4]  (0) 2016.04.15
Python Tutorial : Variables [3]  (0) 2016.04.15
Python Tutorial : If statements [2]  (0) 2016.04.15

+ Recent posts