简体   繁体   English

我的 break 语句在带有 if 语句的 while 循环中不起作用?

[英]My break statement is not working in a while loop with an if statement?

Trying to figure out how I can make a class or function that will take two numbers and save them to a list, use a break statement to make the second conditional on the answer of the first (and also make sure that the same numbers can't be used), and I don't know whether I would use a repr or str statement to return the whole game every time if I wanted to make a class out of it.试图弄清楚如何创建一个接受两个数字并将它们保存到列表中的类或函数,使用 break 语句使第二个条件以第一个的答案为条件(并确保相同的数字可以' t 被使用),而且我不知道如果我想从中创建一个类,我是否会使用reprstr语句每次都返回整个游戏。

I tried for loops before while loops like(for i in fye, for e in fire), but those would either return integer not iterable and then I made the int(type) into fye = list(int(input("fye"))) and then this would return that object was not compatible with int for operators.我在 while 循环之前尝试过 for 循环,例如(for i in fye,for e in fire),但那些要么返回整数不可迭代,然后我将 int(type) 设为 fye = list(int(input("fye") )) 然后这将返回该对象与运算符的 int 不兼容。

>>> def play():
...     fye = None
...     fire = None
...     while fye == None:
...         fye = int(input("What number am I thinking of?"))
...         if fye > 5:
...             print("you got it")
...             fear.append(fye)
...             continue
...         else:
...             print("wrong")
...             break
...     while fire == None:
...         fire = int(input("what number you got now?"))
...         if fire > 15:
...             print("you made it")
...             fear.append(fire)
...         elif fire == fye:
...             print("whoops try again")
...         else:
...             print("you got burnt up")
...
>>> play()
What number am I thinking of?3
wrong
what number you got now?27
you made it
>>> fear
[7, 27]

The problem with this is that fye is immeadiately not None on the first iteration of the loop, so the break or continue don't do anything meaningful.问题在于fye在循环的第一次迭代中立即不是 None ,因此breakcontinue没有做任何有意义的事情。

...     while fye == None:
...         fye = int(input("What number am I thinking of?"))

If you want to continuously ask for input until you say break , then you would do while True如果你想不断地要求输入直到你说break ,那么你会做while True

And rather than use a global fear variable, after both while loops, you can return [fye, fire]而不是使用全局fear变量,在两个 while 循环之后,您可以return [fye, fire]

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

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