【问题标题】:Failed loop: asking the user if they wish to continue (Python)失败的循环:询问用户是否希望继续(Python)
【发布时间】:2018-01-20 16:46:31
【问题描述】:

我为 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()

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

【问题讨论】:

  • python2 input() 与 python3 input() 的工作方式不同。请改用raw_input()
  • 成功了!非常感谢。

标签: python loops continue


【解决方案1】:

使用raw_input()

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

【讨论】:

    【解决方案2】:

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

    answer = raw_input("your message here: ")
    

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

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

    【讨论】:

      【解决方案3】:

      如果你使用的是 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!')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-09-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-18
        相关资源
        最近更新 更多