【问题标题】:Can you combine a while statement and an If statement together into one line?您可以将 while 语句和 If 语句组合成一行吗?
【发布时间】:2019-09-16 06:56:44
【问题描述】:

我正在创建一个游戏,它玩到 10 分即可获胜,如果玩家达到 7 分而其他玩家没有获得任何积分,您也可以获胜。

我在 while 语句中有一个 if 语句,想知道是否有办法将它们组合成一个通用语句。

我尝试将它们与 if 部分的额外括号组合在一起,并尝试更改和/或布尔值以查看我是否弄错了。

while (count1 <= 10 and count2 <= 10):
   if (count1 == 7 and count2 == 0) or (count2 == 7 and count1 == 0):

Happy Path:while 和 if 循环组合成一条语句,同时仍保持摘要中所述的规则。

目前:我尝试了一堆组合,但它们都进入了 else 语句或超出了 10 点限制,这告诉我 while 参数错误。

【问题讨论】:

  • 你为什么要把它们结合起来?他们正在检查不同的东西。

标签: python-3.x


【解决方案1】:

试试:

while (count1 <= 10 and count2 <= 10) or ((count1 != 7 or count2 != 0) and (count2 != 7 or count1 != 0)):

我在这里使用以下逻辑法则:

not (a or b) &lt;=&gt; not a and not b

not (a and b) &lt;=&gt; not a or not b

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-01
    • 2016-04-12
    • 2016-02-29
    • 1970-01-01
    • 1970-01-01
    • 2019-04-08
    • 2017-10-25
    • 1970-01-01
    相关资源
    最近更新 更多