2016-10-04 43 views
1

我試圖讓一個字符串不斷重複,如果答案是錯誤的。我會如何去做這件事?我的代碼是低於哪些作品,但不重複答案。如果輸入錯誤答案,如何再次詢問字符串?

print("Hello there, what is your name?") 
MyName = input() 
print ("Nice to meet you " + MyName) 
print ("What is 2 + 2?") 

answer = input() 
if answer is '4': 
    print("Great job!") 
elif answer != '4': 
    print ("Nope! please try again.") 
while answer != '4': 
    print ("What is 2 + 2?") 
    break 
+0

@ MooingRawr問題清楚地顯示了正在使用的while循環。只有一個小錯誤阻止程序成功運行。 – tcooc

+1

作爲一個方面說明,請不要使用'is'來比較字符串是否相等,因爲它不這樣做。改用==代替。查看https://stackoverflow.com/questions/1504717/why-does-comparing-strings-in-python-using-either-or-is-sometimes-produce爲什麼。 – tcooc

回答

3

您的代碼有幾個錯誤。首先,你現在只需要回答一次。您需要將answer = input()放入while循環中。其次,你需要使用==,而不是is

print("Hello there, what is your name?") 
MyName = input() 
print ("Nice to meet you " + MyName) 
print ("What is 2 + 2?") 

answer = 0 

while answer != '4': 

    answer = input() 
    if answer == '4': 
     print("Great job!") 
    else: 
     print ("Nope! please try again.") 

有多種方式可以安排該代碼。這只是其中的一個

1

,您只需要在錯誤回答檢查爲循環條件,然後輸出「偉大的工作」消息時,循環結束(無需if):

print("Hello there, what is your name?") 
MyName = input() 
print ("Nice to meet you " + MyName) 
print ("What is 2 + 2?") 
answer = input() 
while answer != '4': 
    print ("Nope! please try again.") 
    print ("What is 2 + 2?") 
    answer = input() 

print("Great job!") 
1
print('Guess 2 + 2: ') 
answer = int(input()) 
while answer != 4: 
    print('try again') 
    answer = int(input()) 
print('congrats!') 

我認爲這是最簡單的解決方案。

0

這裏是我的兩分錢的python2:

#!/usr/bin/env python 


MyName = raw_input("Hello there, what is your name ? ") 
print("Nice to meet you " + MyName) 

answer = raw_input('What is 2 + 2 ? ') 

while answer != '4': 
    print("Nope ! Please try again") 
    answer = raw_input('What is 2 + 2 ? ') 

print("Great job !") 
+0

令人敬畏的帖子讓事情變得更加清晰!謝謝很多人 – TechnicalJay

+0

@TechnicalJay不客氣。不要忘記驗證符合您需求的答案。 ; ) – JazZ

1

現在你已經有了更多的答案比你可以處理,但這裏有另一對夫婦微妙之處,與筆記:

while True: # loop indefinitely until we hit a break... 

    answer = input('What is 2 + 2 ? ') # ...which allows this line of code to be written just once (the DRY principle of programming: Don't Repeat Yourself) 

    try: 
     answer = float(answer) # let's convert to float rather than int so that both '4' and '4.0' are valid answers 
    except:  # we hit this if the user entered some garbage that cannot be interpreted as a number... 
     pass # ...but don't worry: answer will remain as a string, so it will fail the test on the next line and be considered wrong like anything else 

    if answer == 4.0: 
     print("Correct!") 
     break # this is the only way out of the loop 

    print("Wrong! Try again...") 
相關問題