我正在创建一个简单的程序来将公制单位转换为英制单位(不包括因为它工作正常)但我无法弄清楚为什么“继续”在它应该只重新启动循环时产生追踪错误?
import sys
import time
def converter():
while True:
cont_1 = input('Do you want to do another calculation? (Yes, No) ')
if cont_1 == 'no' or 'No':
break
elif cont_1 == 'yes' or 'Yes':
continue
return
converter()
sys.exit()
当我输入“是”或“是”时,我希望程序重启。实际上,我得到一个追溯错误。
你的Traceback
是由sys.exit()
创建的,但是当你在某些IDE中运行时它可能是正常的。
但你不需要sys.exit()
。如果你删除它,那么你将没有Traceback
但还有其他问题 - 你的if
没有按预期工作,它退出while
循环然后执行sys.exit()
线
if cont_1 == 'no' or 'No':
手段
if (cont_1 == 'no') or 'No':
这总是给qazxsw poi,它退出qazxsw poi循环。
你需要
True
要么
while
或使用 if cont_1 == 'no' or cont_1 == 'No':
if cont_1 in ('no', 'No'):
最后一个版本也适用于string.lower()
和 if cont_1.lower() == 'no':
您可以使用
NO
有相同的问题,但在nO
没有代码在 elif cont_1 == 'yes' or 'Yes':
continue
,所以你不需要它
所以你只需要
continue
或者把while
放在def converter():
while True:
cont_1 = input('Do you want to do another calculation? (Yes, No) ')
if cont_1.lower() == 'no':
break
return
converter()
的地方
return
你不了解Python if语句的工作方式,现在它总是错误的。
要么像这样写:
break
或者在这种情况下可能更容易:
def converter():
while True:
cont_1 = input('Do you want to do another calculation? (Yes, No) ')
if cont_1.lower() == 'no':
return
converter()
实际上,您使用完全逻辑错误的方式来运行此代码,因此您的代码应如下所示:
if cont_1 == 'no' or cont_1 == 'No':