【问题标题】:Python While true, Try/Except, returning valuePython While true, Try/Except, 返回值
【发布时间】:2018-11-06 15:03:13
【问题描述】:

当我在创建一个变量并放置一段时间后尝试返回一个值 True、try/except 命令时,该变量不会返回该值。我正在尝试将这个“开始”全球化,以便可以使用它。

def start_time():
    while True:
        try:
            starting = int(input("Please enter a starting hour(HH): "))
            if starting < 0:
                print("There are no negative hours!")
            elif starting > 24:
                print("There are only 24 hours in a day!")
            else:
                break
        except ValueError:
            print("Please enter in a correct format (HH)")
    return starting
def end_time():
    while True:
        try:
            ending = int(input("Please enter an ending hour (HH): "))
            if ending < starting:
                print("You can only plan a day!")
            elif ending < 0:
                print("There are only 24 hours in a day!")
            elif ending > 24:
                print("There are only 24 hours in a day!")
            else:
                break
        except ValueError:
            print("Please enter in a correct format (HH)")
    return ending

#obtain starting and ending time
start_time()
end_time()

#confirm starting and ending time

谢谢

【问题讨论】:

  • 当输入正确时,你永远不会跳出 while 循环。将pass 替换为break(或者只是提前返回)。

标签: python while-loop return global try-except


【解决方案1】:

是的,需要一项修改来实现您的既定目标:

替换:

start_time()

starting = start_time()

当一个函数被调用时,它返回一个没有明确放置该值的位置的值,python 会丢弃该值。

【讨论】:

  • 另外一件事:您需要在 if 语句的 else 分支上将 pass 更改为 break,或者更有效地将 return 语句放在那里,否则您将永远无法摆脱无限循环!
【解决方案2】:

不是将starting 设为全局,而是将starting 值返回给调用者。如果可能,需要避免使用全局。阅读为什么这是一个糟糕的设计here。为了更好地实现,您的调用者应修改为:

starting = start_time()

现在开始时间在starting获取。

同样,

ending = end_time()

结束时间在ending中获取。

还有pass 不会跳出无限的while 循环。它什么都不做,但在语法上需要语句但程序不需要操作时使用。使用break 代替pass。它退出最里面的循环。

了解breakhere的用法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-26
    • 2011-01-22
    • 1970-01-01
    • 2020-11-10
    • 1970-01-01
    • 2015-11-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多