Python - 如果用户提供无效响应,则循环回raw_input?

时间:2015-10-02 21:07:55

标签: python raw-input

我有一些使用raw_input()的Python代码。如果用户提供无效响应,我想自动返回raw_input。我该怎么做?

第一个代码:

name = raw_input("Enter Name: ")

如果用户在没有给出姓名的情况下按Enter键(可以是任何内容),我将如何返回raw_input?

第二个代码:

def start():
        answer = raw_input("Go outside (y,n)? ").lower()
        if answer == "y":
                print "I agree! We've only been here for a few days. Let's do some more exploring!"
        elif answer == "yes":
                print "I agree! We've only been here for a few days. Let's do some more exploring!"
        elif answer == "no":
                print ""
                raw_input("I think we should do some more exploring; we've only been on this planet for a few days... (Press 'Enter')")
        elif answer == "n":
                raw_input("I think we should do some more exploring; we've only been on this planet for a few days... (Press 'Enter')")
                print ""
        else:
                print "Press 'y' for yes and 'n' for no"

start()

如果'其他'我试图回到raw_input。发生或者如果用户用" n"或"不" ...

1 个答案:

答案 0 :(得分:1)

尝试while循环?

name = ''
while not name:
    name = raw_input("Go outside (y,n)? ").rstrip().lower()