[英]Why is there a traceback error while using continue in a "While True" loop
我正在创建一个简单的程序来将公制单位转换为英制单位(不包括在内,因为它工作正常)但是我无法弄清楚为什么“继续”在应该重新启动循环时会产生回溯错误?
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()
我希望程序在我输入“是”或“是”时重新启动。 在现实中,我收到回溯错误。
你不理解 Python if 语句的工作方式,现在它总是错误的。
要么像这样写它们:
if cont_1 == 'no' or cont_1 == 'No':
或者在这种情况下可能更容易:
if cont_1.lower() == 'no':
实际上,您正在使用一种完全逻辑错误的方式来运行此代码,因此您的代码应该是这样的:
import sys
def converter():
cont_1 = input('Do you want to do another calculation? (Yes/ No) ')
if cont_1 == 'no' or cont_1 == 'No':
sys.exit()
if cont_1 == 'yes' or cont_1 == 'Yes':
pass
while True:
converter()
您的Traceback
是由sys.exit()
创建的,但是当您在某些 IDE 中运行时它可以是正常的。
但你不需要sys.exit()
。 如果您删除它,那么您将没有Traceback
但是还有其他问题 - 您的if
没有按预期工作,它退出while
循环,然后执行sys.exit()
线
if cont_1 == 'no' or 'No':
方法
if (cont_1 == 'no') or 'No':
这个 awlays 给出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
放在break
地方
def converter():
while True:
cont_1 = input('Do you want to do another calculation? (Yes, No) ')
if cont_1.lower() == 'no':
return
converter()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.