遇到一个无限循环。为什么?

时间:2018-03-27 15:05:19

标签: python python-3.x

我遇到了一个无限循环。它不断要求social_media input。我正在尝试使用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)

2 个答案:

答案 0 :(得分:3)

除了变量名称有点可怕之外,为什么外循环没有中断条件?

看起来你正确地突破了内部的一个,但你没有任何突破外部的代码(代码中的第一行)

答案 1 :(得分:3)

无限循环是由您共享的代码最顶部的第一个外部while循环引起的。你没有什么可以打破那个循环,所以它会无限地执行内部while循环,即使你用你在#ifndef FBullCowGame_hpp #define FBullCowGame_hpp #include <stdio.h> #include <string> #endif /* FBullCowGame_hpp */ class FBullCowGame { public: void Reset(); // TODO Make a reset void // Not important.., The important is this ^^ private: int CurrentTries; int MaxTries; }; 条件中插入的break语句打破它,因为你没有打破外部while循环。

作为一个解决方案,只需删除top while循环或添加代码中更改的另一个条件,例如在if not social_media:内添加一个布尔值,用于打破外部while循环:

if not social_media:

以下是有关来自TutorialsPoint的while循环的一些其他信息:

  

只要给定条件为真,Python编程语言中的while循环语句就会重复执行目标语句。

     

如果条件永远不会变为FALSE,则循环变为无限循环。使用while循环时必须小心,因为此条件可能永远不会解析为FALSE值。这导致循环永远不会结束。这样的循环称为无限循环。

我建议您阅读更多有关while循环和Python的信息。 TutorialsPointofficial Python documentation是开始使用的好地方。