提示用户是或否重启程序

时间:2016-02-01 21:58:16

标签: python

我希望这个程序询问用户是否要继续,如果他们说是,那么它会重新运行程序,如果他们说不,那么它就会结束程序。我被困住了,无法弄明白。

name = raw_input("Whats your name?: ")
age = raw_input("How old are you?: ")
if age.isdigit() and int(age) > 15:
    print "Congradulations you can drive!"
elif age.isdigit() and int(age) < 16:
    print "Sorry you can not drive yet :("
else:
    print "Enter a valid number"
print ("it's been very nice getting to know you " + name)
print ("")

2 个答案:

答案 0 :(得分:1)

尝试将所有代码放入while循环中:

While True:
    .... code...
    run_again = raw_input("Run again? ")
    if run_again == 'no':
        break

另一种方法可能是将代码放入函数中,如果用户说要再次运行,则再次调用该函数。

查看this question了解更多信息。

答案 1 :(得分:0)

我曾经创建了一个功能:

def yorn(question = "[y/n]", strict = True):
    """yorn([question][, strict]) -> user input

    Asks the question specified and if the user input is 'yes' or 'y',
    returns 'yes'.  If the user input is 'no' or 'n', it returns no.  If
    strict is False, many other answers will be acceptable."""
    question = question.strip(" ")
    x = raw_input("%s " % question)
    x = x.lower()
    if (x == "yes") or (x == "y") or ((not strict) and ((x == "yep") or (x == "yeah") or (x == "of course") or (x == "sure") or (x == "definitely") or (x == "certainly") or (x == "uh huh") or (x == "okay") or (x == "ok"))): 
        return True 
    elif (x == "no") or (x == "n") or (not strict and x in ["nope", "uh uh", "no way", "definitely not", "certainly not", "nah", "of course not"]):
        return False
    else:
        return yorn(strict = strict)

要使用它,请使您的程序如下:

again = True
while again:
    name = raw_input("Whats your name?: ")
    age = raw_input("How old are you?: ")
    if age.isdigit() and int(age) > 15:
        print "Congradulations you can drive!"
    elif age.isdigit() and int(age) < 16:
        print "Sorry you can not drive yet :("
    else:
        print "Enter a valid number"
    print ("it's been very nice getting to know you " + name)
    print ("")
    again = yorn("Would you like to try again? ", strict=False)