PythonWhile循环突破问题
所以我对 Python 和一般编程很陌生。我的问题是关于我在这里的 while 循环标志。这有效,但不像我认为的那样。我想我不理解某些东西,所以如果有人能够解释,那就太好了。
根据我的理解,只要满足我的一个条件,就应该立即跳出循环。因此,如果我输入“q”,它应该会中断并停止循环。但发生的情况是它不断循环,然后爆发。所以它通过最后一个提示并打印异常。
(Python 版本为 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"nThe answer is: {answer}")
使用此代码它会像我期望的那样立即爆发。
while True:
first_number = input("First number: ")
if first_number == 'q':
break
second_number = input("Second number: ")
if second_number == 'q':
break
我只是想了解有什么区别,如果那应该是如何工作的。我觉得我错过了什么或误解了什么。我试过查这个,但还没有找到答案。
提前致谢!
回答
while
循环的条件只在循环体的迭代之间检查,因此如果在循环中间更改条件,当前迭代将在循环终止之前完成。如果您想立即中断循环,则需要break
(无论条件如何都会自动中断循环)或continue
(跳转到下一次迭代,因此如果条件不再为真,将终止循环)。
当您想要停止循环时使用while True:
abreak
通常比尝试通过设置和取消设置标志来控制循环要简单得多。
FWIW,而不是复制和粘贴代码来输入两个数字,并有两种不同的方式来跳出循环,我可能会将所有这些都放入一个函数中并用 来打破循环Exception
,如下所示:
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
这使得扩展程序以处理两个以上的输入变得更容易;尝试在“第一”和“第二”之后添加“第三”!:)
回答
一旦你运行程序并输入“q”,Yes 确实keep_going
会被设置为,False
但这并不意味着它已经打破了循环,它只会使keep_going
等于,False
因此在NEXT ITERATION将停止循环。这是为什么?因为它会是这样while keep_going:
->while False:
所以因为它True
不再执行程序了。
现在根据你提到的目标。您可以通过这种方式添加break
.
if first_number == 'q':
keep_going = False
break
# 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
break
我还想建议采用这种方式,它只是在代码上发生的事情方面更具体,但这当然取决于您。
first_number = input("First number: ")
# Create a break when entering the first number.
if first_number == 'q':
keep_going = False
break
# Prompt for user to input second number and store it in a variable.
# Create a break when entering the second number.
else:
second_number = input("Second number: ")
if second_number =='q':
keep_going = False
break