如果输入错误答案,如何再次询问字符串?

时间:2016-10-04 14:46:46

标签: python

如果答案错误,我正试图让字符串继续重复。我该怎么做呢?我的代码如下所示,但不重复答案。

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

5 个答案:

答案 0 :(得分: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 :(得分: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!")

答案 2 :(得分:1)

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

我认为这是最简单的解决方案。

答案 3 :(得分: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...")

答案 4 :(得分: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 !")