为什么在“While True”循环中使用continue时会出现回溯错误

问题描述 投票:-4回答:3

我正在创建一个简单的程序来将公制单位转换为英制单位(不包括因为它工作正常)但我无法弄清楚为什么“继续”在它应该只重新启动循环时产生追踪错误?

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 python-3.x
3个回答
0
投票

你的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

1
投票

你不了解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()

1
投票

实际上,您使用完全逻辑错误的方式来运行此代码,因此您的代码应如下所示:

if cont_1 == 'no' or cont_1 == 'No':
© www.soinside.com 2019 - 2024. All rights reserved.