Python While 循环突破问题 [英] Python While loop breakout issues

查看:21
本文介绍了Python While 循环突破问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是关于 while 循环的标志.这有效,但不像我认为的那样.我想我没有理解某些东西,所以如果有人能够解释,那就太好了.

The question I have is about the flag I have here for the while loop. This works but not like I think it should. I assume I'm not understanding something so if someone is able to explain, that would be great.

根据我的理解,只要满足我的条件之一,它就会跳出循环.因此,如果我输入q",它应该会中断并停止循环.但是发生的情况是它一直在循环中,然后它会爆发.所以它通过最后一个提示并打印异常.

From my understanding this should break out of the loop as soon as one of my conditionals is met. So if I input 'q' it should break out and stop the loop. But what happens is it keeps going through the loop and then it breaks out. so it goes through the last prompt and prints the exception.

(Python 版本为 3.8.5)

(Python version is 3.8.5)

# Statement that tells the user what we need.
print("Enter two numbers and I will tell you the sum of the numbers.")
# Lets the user know they can press 'q' to exit the program.
print("Press 'q' at anytime to exit.")

keep_going = True

# Loop to make the program keep going until its told to stop.
while keep_going:
    # Prompt for user to input first number and store it in a variable.
    first_number = input("First number: ")
    # Create a break when entering the first number.
    if first_number == 'q':
        keep_going = False
    # Prompt for user to input second number and store it in a variable.
    second_number = input("Second number: ")
    # Create a break when entering the second number.
    if second_number == 'q':
        keep_going = False
    # Exception for non integers being input "ValueError"
    try:
        # Convert input to integers and add them. 
        # storing the answer in a variable.
        answer = int(first_number) + int(second_number)
    except ValueError:
        # Tell the user what they did wrong.
        print("Please enter a number!")
    else:    
        # Print the sum of the numbers
        print(f"
The answer is: {answer}")

使用此代码它会像我预期的那样立即爆发.

Using this code it breaks out right away like I expect it to.

while True:
    first_number = input("First number: ")
    if first_number == 'q':
        break
    second_number = input("Second number: ")
    if second_number == 'q':
        break

我只是想了解有什么区别,以及它是否应该这样工作.我觉得我错过了什么或误解了什么.

I just would like to understand what the difference is and if thats how it should work. I feel like I'm missing something or misunderstanding something.

推荐答案

while 循环的条件只在循环体的迭代之间检查,所以如果你在中间改变条件循环,当前迭代将在循环终止之前完成.如果您想立即中断循环,您需要break(无论条件如何都会自动中断循环)或continue(跳转到下一次迭代,因此如果条件不再为真,则将终止循环).

The condition of the while loop is only checked between iterations of the loop body, so if you change the condition in the middle of the loop, the current iteration will finish before the loop terminates. If you want to break a loop immediately, you need to either break (which automatically breaks the loop regardless of the condition) or continue (which jumps to the next iteration, and will therefore terminate the loop if the condition is no longer true).

当您想停止循环时,使用带有 breakwhile True: 通常比尝试通过设置和取消设置标志来控制循环要简单得多.

Using while True: with a break when you want to stop the loop is generally much more straightforward than trying to control the loop by setting and unsetting a flag.

FWIW,与其复制和粘贴代码来输入两个数字,并有两种不同的方法来跳出循环,我可能会将所有这些都放入一个函数中并使用 Exception,像这样:

FWIW, rather than copying and pasting the code to input the two numbers, and have two different ways to break out of the loop, I might put that all into a function and break the loop with an Exception, like this:

print("Enter two numbers and I will tell you the sum of the numbers.")
print("Press 'q' at anytime to exit.")


def input_number(prompt: str) -> int:
    """Ask the user to input a number, re-prompting on invalid input.
    Exception: raise EOFError if the user enters 'q'."""
    while True:
        try:
            number = input(f"{prompt} number: ")
            if number == 'q':
                raise EOFError
            return int(number)
        except ValueError:
            print("Please enter a number!")


while True:
    try:
        numbers = (input_number(n) for n in ("First", "Second"))
        print(f"The answer is: {sum(numbers)}")
    except EOFError:
        break

这样可以更轻松地扩展程序以处理两个以上的输入;尝试添加第三个"在它说第一"之后和第二"!:)

This makes it easier to extend the program to handle more than two inputs; try adding a "Third" after where it says "First" and "Second"! :)

这篇关于Python While 循环突破问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆