【问题标题】:Need help ending a while loop [closed]需要帮助结束 while 循环 [关闭]
【发布时间】:2023-02-19 20:10:24
【问题描述】:

所以我遇到了一个问题,我无法弄清楚如何结束特定的 while 循环。

one = [1, 3, 5, 7, 8, 10, 12]
thirty = [4, 6, 9, 11]

while True:
    try:
        month = int(input("Enter the number of the month: "))
    except month == "":
        print("Program ending")
        break
    except ValueError:
        print("Please enter a number")
        continue
    else:
        def days(month): 
            if month in one:
                return 31
            elif month in thirty:
                return 30
            elif month == 2:
                return 28
        
    if days(month) == None:
            print("The number has to be between 1-12")
    else:
        print("This month has", days(month) ,"days.")

因此,该程序应该告诉您指定月份有多少天,而我几乎想要实现的是循环继续并再次询问问题,直到用户留下空白输入(按回车键)。我已经在谷歌上搜索了很长一段时间,但似乎无法找到我的确切问题的解决方案。我发现你不能把某些东西的价值放在除了:如果值是在尝试:,目前代码中就是这种情况。 提前致谢 :)

【问题讨论】:

  • 您真的打算在 while 循环中定义一个函数吗?并且没有调用该函数,它什么也不做。
  • 好吧,老实说,我不知道,我真的是编程新手,除了我无法结束循环之外,一切似乎都正常。如果您有任何更好的建议,那么我愿意接受 :)

标签: python


【解决方案1】:

一些小错误

正如 Chris 所说,在 while 循环中定义一个函数是没有用的 所以定义你上面的函数 while 循环

其次,在检查它是否为 '' 之前,您不应该尝试将输入转换为 int,这样您就不会得到 ValueError

这是固定的代码

one = [1, 3, 5, 7, 8, 10, 12]
thirty = [4, 6, 9, 11]

def days(month):
    if month in one:
        return 31
    elif month in thirty:
        return 30
    elif month == 2:
        return 28


while True:
    month = input("Enter the number of the month: ")
    if month = '':
        print('program ending')
        break;
    try:
        month = int(month)
    except ValueError:
        print("Please enter a valid number")
        continue
    if days(month) == None:
        print("The number has to be between 1-12")
    else:
        print("This month has ", days(month), " days.")

【讨论】:

  • 还要看看@Lost_coder 的回答,它的可读性更高,更干净,性能更明智,即使这在这里并不重要)
【解决方案2】:

一般关于您的代码的一些 cmets。您将输入定义为整数,为什么还要尝试将整数与字符串进行比较。您可以稍后再进行字符串到 int 的转换。在循环中定义函数不是一个好习惯。

当您需要多个 if 语句时,还可以考虑使用 switch 语句或在 python 字典中。

编辑

捕获一个 ValueError

这是调整后的代码。

months = {
    1: 31, 2: 28, 3: 31,
    4: 30, 5: 31, 6: 30,
    7: 31, 8: 31, 9: 30,
    10: 31, 11: 30, 12: 31
}

while True:
    month = input("Enter the number of the month: ")
    if month == "":
        print("Program ending")
        break
    try:
        month = int(month)
    except ValueError:
        print("please enter a number")

    if month in months.keys():
        print(months[month])
    else:
        print("not a month")

【讨论】:

  • 你应该限制自己去捕捉ValueError
猜你喜欢
  • 2013-05-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-03
  • 2016-11-30
  • 1970-01-01
  • 1970-01-01
  • 2014-03-15
相关资源
最近更新 更多