Python中While True+Try/Except返回值失效及全局变量问题求助
问题分析与解决方案
嘿,我来帮你梳理下当前代码的问题,以及对应的解决办法:
你现在遇到的核心问题有两个:
- 调用
start_time()时没有接住它返回的starting值,导致这个值没法被后续代码使用 end_time()里直接引用starting,但这个变量是start_time()的局部变量,作用域只在start_time函数内部,所以end_time根本访问不到它
至于你想把starting全局化的需求,确实能解决问题,但其实有更优雅的方案,我给你两种选择:
方案一:传递参数(推荐,避免全局变量)
全局变量会让代码耦合度变高,后续维护和调试都容易出问题,所以更推荐的方式是把start_time()返回的值存下来,再传递给end_time()作为参数。这样每个函数的职责更清晰,依赖关系也一目了然。
修改后的完整代码:
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(starting): # 新增参数,接收起始时间 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 no negative hours!") # 修正原代码的提示语错误 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 # 先获取起始时间并保存 starting_hour = start_time() # 将起始时间传入end_time函数,获取结束时间 ending_hour = end_time(starting_hour) # 现在可以正常确认时间了 print(f"Starting hour: {starting_hour}, Ending hour: {ending_hour}")
方案二:使用全局变量(不推荐,但满足你的需求)
如果你一定要把starting变成全局变量,需要在函数内部用global关键字声明,告诉Python你要使用的是全局作用域的变量,而不是创建一个新的局部变量。
修改后的代码:
# 先在全局作用域定义starting变量 starting = 0 def start_time(): global starting # 声明使用全局变量 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(): global starting # 同样声明使用全局变量 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 no negative hours!") # 修正提示语错误 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 # 调用函数 start_time() ending_hour = end_time() # 确认时间 print(f"Starting hour: {starting}, Ending hour: {ending_hour}")
⚠️ 注意:全局变量虽然能快速解决问题,但当代码规模变大时,很容易因为不小心修改全局变量导致难以排查的bug,所以除非必要,尽量不要用这种方式。
内容的提问来源于stack exchange,提问作者royce.lee
相关产品推荐
相关产品推荐

