失败的循环:询问用户是否希望继续(Python)

时间:2018-01-20 16:46:31

标签: python loops continue

我为Python 3开发了这个代码,以便询问用户是否希望继续:

def dnv(): 
    b = input('Would you like to try again? Type 1 for "yes" and 0 for "no": ')
    if b == '1':
        return run()
    if b == '0':
        return print('See you later!')

run()是任何程序的主要功能。但是现在我正在学习Python 2的课程,并且我试图将它改编成我从那里获得的算法,但没有成功。目标是确定两个日期之间的天数。我相信相关部分是:

def inputs():
    year1 = input('Type the first year: ')
    month1 = input('Type the first month: ')
    day1 = input('Type the first day: ')
    year2 = input('Type the second year: ')
    month2 = input('Type the second month: ')
    day2 = input('Type the second day: ')
    print daysBetweenDates(year1, month1, day1, year2, month2, day2)

def dnv():
    answer = input('Would you like to try again? Type "y" for yes and "n" for no: ')
    if answer == 'y':
        return inputs()
    else:
        print('See you later!')

每次输入y或n时,我都会得NameError: name 'y' is not defined(类似于'n')。我还尝试将if answer == 'y'修改为:

if answer.lower().startswith('y'):
    return inputs()

再次没有成功。我错过了什么?谢谢!

3 个答案:

答案 0 :(得分:2)

使用raw_input()

answer = input('Would you like to try again? Type "y" for yes and "n" for no: ')

答案 1 :(得分:2)

如果您使用的是python 2,则需要将输入更改为:

answer = raw_input("your message here: ")

你不需要返回一个你可以调用它的函数。

if answer.lower().startswith('y'):
    inputs()

答案 2 :(得分:2)

如果您使用的是python 3,我推荐这个:

b = input('Would you like to try again? Type 1 for "yes" and 0 for "no": ')
   if b == '1':
       return run()
   if b == '0':
       return print('See you later!')