2016-10-04 20 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...") 
相关问题