gpt4 book ai didi

python - 遇到无限循环。为什么?

转载 作者:行者123 更新时间:2023-11-28 20:59:29 25 4
gpt4 key购买 nike

我遇到了一个无限循环。它不断要求 social_media 输入。我试图用 if not 结束循环,当我用“enter”输入一个空白输入时,但它忽略了它。怎么会?

while True:
if confirm_social_media == 'n':
victims.append(victim_data)
continue
while True:
social_media = input("\nType of social media: "
"\n'i' = Instagram"
"\n's' = Snapchat"
"\n't' = Twitter"
"\n'y' = Youtube"
"\n'f' = Facebook"
"\n'o' = Other"
"\nOr blank for next")
if not social_media:
break

if social_media == 'i':
iinput = input("Instagram " + str(inumbr) + ": ")
if family_members == 'm':
mother_instagram.append(iinput)
elif family_members == 'f':
father_instagram.append(iinput)
elif family_members == 'o':
other_instagram.append(iinput)

最佳答案

无限循环是由您共享代码最顶部的第一个外部 while 循环引起的。你没有什么可以打破那个循环,所以它会无限地执行内部 while 循环,即使你用你在 if not social_media: 条件中插入的 break 语句打破它,因为你没有打破外部 while 循环。

作为解决方案,只需删除顶部的 while 循环或添加另一个在代码中更改的条件,例如在您的 if not social_media: 中添加一个 bool 值,该 bool 值将用于中断您的外部while 循环:

continue_loop = True
while continue_loop :
if confirm_social_media == 'n':
victims.append(victim_data)
continue
while True:
social_media = input("\nType of social media: "
"\n'i' = Instagram"
"\n's' = Snapchat"
"\n't' = Twitter"
"\n'y' = Youtube"
"\n'f' = Facebook"
"\n'o' = Other"
"\nOr blank for next")
if not social_media:
continue_loop = False
break

if social_media == 'i':
iinput = input("Instagram " + str(inumbr) + ": ")
if family_members == 'm':
mother_instagram.append(iinput)
elif family_members == 'f':
father_instagram.append(iinput)
elif family_members == 'o':
other_instagram.append(iinput)

这里是关于 TutorialsPoint 中 while 循环的一些附加信息:

A while loop statement in Python programming language repeatedly executes a target statement as long as a given condition is true.

A loop becomes infinite loop if a condition never becomes FALSE. You must use caution when using while loops because of the possibility that this condition never resolves to a FALSE value. This results in a loop that never ends. Such a loop is called an infinite loop.

我建议您阅读更多有关 while 循环和 Python 的一般知识。 TutorialsPointofficial Python documentation是开始的好地方。

关于python - 遇到无限循环。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49516439/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com