如何检查 Python 中的错误以阻止它循环?

问题描述

我是 Python 初学者。这不断循环,我似乎无法找到其中的错误来纠正它。任何帮助,将不胜感激。谢谢。

sentence = "that car was really fast"
i = 1
while i > 0:
    for char in sentence:
        if char == "t":
            print("found a 't' in sentence")
        else:
            print("maybe the next character?")

解决方法

如果您只想确定字母“t”是否在句子中,可以使用 Python 的 in 运算符非常简单地完成:

if 't' in sentence:
    print("found a 't' in sentence")

如果你想遍历句子中的每个字母并根据它的内容为每个字母打印一行输出,你只需要一个 for 循环:

for char in sentence:
    if char == "t":
        print("found a 't' in sentence")
    else:
        print("maybe the next character?")

如果您想在找到“t”后立即停止此循环,方法是break

for char in sentence:
    if char == "t":
        print("found a 't' in sentence")
        break
    print("maybe the next character?")
,

您已经设置了 i = 1,但在 while 循环中,没有任何东西可以将 i 的值更改为最终变为 0 并退出循环。此外,您甚至不需要 while 循环,因为您只是遍历字符串 sentence 中的字符,所以只需执行以下操作:

sentence = "that car was really fast"

for char in sentence:
    if char == "t":
        print("found a 't' in sentence")
    else:
        print("maybe the next character?")
,

我想你想要的是如果字符是“t”,则打印“在句子中找到 t”,否则打印“也许是下一个字符?”。 您不应该在此程序中使用 while 循环,只有 for 循环才能满足您的要求。