简体   繁体   English

Python,而While循环无法正常运行

[英]Python, While Loop Not Functioning Properly

The while loop correctly stops when "no" is entered first for the "would you like to continue" question. 当首先为“您想继续”问题输入“否”时,while循环正确停止。 When "no" is entered after "yes" or after several "yes" entries, then the user must answer "no" for however many "yes" entries came before it: eg "yes", "yes", "no" will produce two "would you like to continue" questions after the first "no" answer. 当在“是”之后或在多个“是”条目之后输入“否”时,则用户必须回答“否”,因为在此之前有许多“是”条目:例如,“是”,“是”,“否”在第一个“否”答案之后产生两个“您想继续”问题。

I am just beginning to learn Python, so any suggestions would be helpful. 我刚刚开始学习Python,因此任何建议都会有所帮助。

Thank you. 谢谢。

def testing3():
    def Grade(score):
        if score >= 90:
            letter = "A"
        elif score >= 80:
            letter = "B"
        elif score >= 70:
            letter = "C"
        elif score >= 60:
            letter = "D"
        else:
            letter = "F"
        print(letter) 

    def main():
        x = input("Enter Numerical Grade: ")
        numGrade = int(x)
        Grade(numGrade)

    main()

    def main2():
        while True:
            test = input("Would you like to continue?: ")
            if test == 'Yes':
                testing3()
            else:
                print("Done")
                break

    main2()

testing3()

Your testing3 call invokes the inner main2 def, but main2 invokes the testing3 def so you are ping-ponging between the two. 您的testing3调用会调用内部的main2 def,但是main2会调用testing3 def,因此您在两者之间进行了ping-poning。

To get a sense of this you should look at your stack-frames and you should see a frame for testing3 followed by testing2 followed by testing3 etc for how ever many times you have entered yes. 为了了解这一点,您应该查看堆栈框架,并看到一个用于test3的框架,然后是testing2,然后是testing3,依次类推,以了解您输入了yes的次数。

Whether or not you meant to (I don't think you did) you created a recursive function. 无论您是否打算(我认为您没有这样做),您都创建了一个递归函数。 So the reason you are having to enter no multiple times is as you unwind up (popping frames off the stack) 因此,您不必多次输入的原因是在展开时(将帧弹出堆栈)

The proper use of the while loop should something like: while循环的正确使用应如下所示:

finish = False
while not finish:
  # do your stuff here
  finish = evaluateLoopFinish()

Here, finish is a signal flag which you must evaluate at the end of each turn. 在此,终点是一个信号标志,您必须在每个回合结束时对其进行评估。 The first time is set at False, so not False == True, hence enters the loop. 第一次设置为False,因此不设置False == True,因此进入循环。

Another tip: use only one main like this 另一个提示:只能使用一个这样的主体

def main(args):
  # do your stuff here

if __name__=="__main__":
  main()

Every Python script has a name special variable which holds the name of the module except for the script which was given to Python to be executed which receives the special value main . 每个Python脚本都有一个名称特殊变量,该变量保存模块的名称, 要执行的Python脚本收到的特殊值main 除外

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM