简体   繁体   English

为什么我的带有 if 语句的 while 循环不起作用?

[英]Why is my while loop with if statements not working?

answer = "8"

print("What is 5 + 3 = ? ")
answer = input()

while (answer != "8"):
  if (answer == "8"):
    print("Correct answer!")
  else:
    print("Incorrect answer!")

Whenever I write the correct answer in the input, the print statement doesn't appear, whereas if I write the incorrect answer, it sends me an infinite amount of my else statement.每当我在输入中写出正确答案时,print 语句就不会出现,而如果我写出错误答案,它会向我发送无限量的 else 语句。 How can I fix this?我怎样才能解决这个问题?

You should move the input method inside the loop - you want the user to be able to input a new number in case the answer is wrong您应该在循环内移动输入法 - 您希望用户能够输入新数字,以防答案错误

Working code:工作代码:

print("What is 5 + 3 = ? ")
while True:
    answer = input()
    if (answer == "8"):
        print("Correct answer!")
        break
    else:
        print("Incorrect answer!") 

The while loop is executing once for every time that answer != "8".每次回答 != "8" 时,while 循环都会执行一次。 So if you enter 8, it never executes because 8 always equals 8, and if you enter something else, then it executes an infinite number of times because something that does not equal 8 never equals 8. The solution here is to get rid of the while line.所以如果你输入 8,它永远不会执行,因为 8 总是等于 8,如果你输入其他东西,那么它会执行无限次,因为不等于 8 的东西永远不等于 8。这里的解决方案是摆脱同时线。

thats because the wile don't execute if the answer is "8".那是因为如果答案是“8”,则 wile 不会执行。 You should Know as weel that every while loop should have a break statement .您应该知道每个 while 循环都应该有一个 break 语句。 if you want this code to just print if the result is correct or no you can just delete the while statement如果您希望此代码仅打印结果是否正确,您可以删除 while 语句

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

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