Python中phaseout设为2时触发NameError或返回空元组的问题求助
Python处理phaseout=2时的NameError及值异常问题
我运行Python代码时遇到了NameError问题:当phaseout变量设为2时,要么程序提示phasedays未定义,要么初始化phasedays为空元组后返回空值。但phaseout设为1时程序运行完全正常。
问题代码片段
character = input("What character are you saving for? ") phaseout = int(input("What phase is " + character + " coming out in? (1 or 2): ")) currentphase = int(input("Current phase (1 or 2): ")) daysleftinphase = int(input("Days left in current phase: ")) # phase calculations # does NOT include the 20 days for the phase the desired character is out phasedays = ('') if currentphase == 1: if phaseout == 1: phasedays = 20 + daysleftinphase elif currentphase == 1: if phaseout == 2: phasedays = 40 + daysleftinphase elif currentphase == 2: if phaseout == 1: phasedays = daysleftinphase elif currentphase == 2: if phaseout == 2: phasedays = 20 + daysleftinphase print("\nDays you'll have when it comes to phases:", phasedays)
错误信息(未初始化phasedays时)
Traceback (most recent call last): File "main.py", line 22, in <module> print("\nDays you'll have when it comes to phases:", phasedays) NameError: name 'phasedays' is not defined
问题原因
你的条件判断逻辑存在语法错误:第一个if currentphase == 1已经覆盖了所有currentphase为1的情况,后续的elif currentphase == 1永远不会被执行。当currentphase=1且phaseout=2时,代码不会进入任何赋值分支——如果没初始化phasedays就触发NameError,初始化了就保留初始的空元组。
修正后的代码
character = input("你要攒哪个角色?") phaseout = int(input(f"{character}会在哪个卡池阶段上线?(1或2): ")) currentphase = int(input("当前卡池阶段(1或2): ")) daysleftinphase = int(input("当前阶段剩余天数: ")) # 阶段计算(不包含目标角色上线阶段的20天) phasedays = 0 if currentphase == 1: if phaseout == 1: phasedays = 20 + daysleftinphase elif phaseout == 2: phasedays = 40 + daysleftinphase elif currentphase == 2: if phaseout == 1: phasedays = daysleftinphase elif phaseout == 2: phasedays = 20 + daysleftinphase print(f"\n你能攒到的阶段天数: {phasedays}")
优化说明
- 修复条件分支逻辑:将
currentphase的判断作为外层,内部用elif处理phaseout的不同情况,确保所有场景都能被覆盖。 - 初始值设为
0:更符合数值计算的逻辑,避免空元组带来的类型混淆。 - 使用f-string简化字符串拼接:让输入输出代码更简洁易读。
内容的提问来源于stack exchange,提问作者user20444221
相关产品推荐
相关产品推荐

