微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决如何检查 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 循环才能满足您的要求。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。