简体   繁体   English

Python while 循环不能在两个条件下工作

[英]Python while loop not working with two conditions

Im trying to make a while loop that stops when two variables are equal to 0, but when one of them reaches 0 the loop ends, and I have no clue why.我试图做一个while循环,当两个变量等于0时停止,但是当其中一个变量达到0时循环结束,我不知道为什么。 This is what I have...这就是我所拥有的...

  movement=3
  attacks=1
  while (attacks != 0) and (movement != 0):
    do = input('what to do?')
    if do == 'move':
      movement -=1
    if do =='attack':
      attacks -=1

I could be missing something obvious, but any help is appreciated我可能会遗漏一些明显的东西,但感谢您提供任何帮助

You had two mistakes in your code.您的代码中有两个错误。 The first one was you did not close your quotes in your input.第一个是您没有在输入中关闭引号。 The second was you used an assigning operator = instead of a comparison operator = on line 7 .第二个是您在第7行使用了分配运算符=而不是比较运算符= Cleaned up code.清理代码。

movement=3
attacks=1
while (attacks != 0) and (movement != 0):
    do=input('what to do?')
    if do=='move':movement-=1
    if do=='attack':attacks-=1

The loop will continue as long as the predicate (attacks != 0) and (movement != 0) is true.只要谓词(attacks != 0) and (movement != 0)为真,循环就会继续。 Therefore the loop will stop once the predicate is false.因此,一旦谓词为假,循环将停止。 The predicate is false exactly when EITHER attacks == 0 OR movement == 0 .当 EITHER attacks == 0movement == 0时,谓词为假。 This is the negation of the predicate.这是谓词的否定。

If you want the loop to end ONLY when both are 0, then you're saying you want the loop to continue as long as (attacks != 0) or (movement != 0) as the negation of that predicate is attacks == 0 and movement == 0 .如果您希望循环仅在两者都为 0 时结束,那么您是说您希望循环继续,只要(attacks != 0) or (movement != 0)因为该谓词的否定是attacks == 0movement == 0

To find out more, see De Morgan's Laws要了解更多信息,请参阅德摩根定律

There are some syntax errors in your code, after fixing it it seems that in a while loop with 2 conditions doesn't work, here's a working version of it:您的代码中有一些语法错误,修复后似乎在具有 2 个条件的 while 循环中不起作用,这是它的工作版本:

movement = 3
attacks = 1
while True:
    if attacks == 0 and movement == 0: break
    do = input('what to do?')
    if do == 'move':
        movement-=1
    if do == 'attack':
        attacks-=1

So you create an infinite loop and inside it you check if the attacks and movement are both equal to 0 , and if they're, then break out of the loop.因此,您创建了一个无限循环,并在其中检查attacksmovement是否都等于0 ,如果它们相等,则跳出循环。

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

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