2017-02-06 4 views
0
from random import randint 
guessed = randint(0,2) 
user_guess = input("What do you think the number I'm thinking of is?") 

if user_guess == guessed: 
    print("Correct!") 
else: 
    print("Incorrect!") 

나는 코드를 반복 할 방법을 찾고 있습니다. 또는 user_guess가 추측과 같을 때까지 다른 메시지를 인쇄 할 방법을 찾고 있습니다.Python에서 완료 될 때까지 작업을 반복하는 방법

사람이 잘못 추측 한 경우 그 사실을 알리고 다른 기회를 제공 할 수 있기를 바랍니다.

감사합니다. 초급 질문에 사과드립니다.

+2

[유효한 응답을 줄 때까지 입력을 요청] (http://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a- 유효 응답) –

답변

0

while 루프를 사용하십시오. 한 추측이 잘못 같은 while 루프에서

from random import randint 
correct = False 
while (not correct): 
    guessed = randint(0,2) 
    user_guess = int(input("What do you think the number I'm thinking of is?")) 
    if user_guess == guessed: 
      print("Correct!") 
      correct = True 
    else: 
      print("Incorrect!") 
+1

입력을 int 유형으로 변환해야합니다. 'user_guess = int (input ("내가 생각하는 숫자는 무엇이라고 생각하니?"))' – r0xette

+0

감사합니다. –

+0

감사합니다 R0xette 및 Andrew, 이제 완벽하게 작동합니다. –

0

그대로. 루프를 "초기 화"하려면 첫 번째 추측이 필요합니다.

# get the first user guess 

while user_guess != guessed: 
    print "Incorrect" 
    # Get next user guess 

"다음 사용자 추측"의 코드는 "첫 번째 사용자 추측"과 매우 유사합니다.

관련 문제