【问题标题】:Python: How to end a while loop while it is running if the while condition changes during the loop?Python:如果while条件在循环期间发生变化,如何在while循环运行时结束它?
【发布时间】:2016-12-11 17:31:32
【问题描述】:

我需要一些关于我正在尝试制作的基于文本的游戏的代码方面的帮助。我的游戏使用健康,代码以“while health>0:”开始,在游戏的另一点,当健康最终=0时,循环仍然继续。当health = 0时如何使循环结束,而不完成整个循环。

这是一个例子:

health=100
while health>0:
  print("You got attacked")
  health=0
  print("test")

当 health=0 时代码不应该停止,并且不打印“test”吗?当健康= 0时如何让它停止?我写的代码是根据用户的行为来扣除健康的,所以健康=0的时间可能会有所不同。我想在 health=0 时结束代码 任何帮助将不胜感激。

【问题讨论】:

  • health>0 检查只发生在每次迭代开始时,所以health=0 直到print('test') 之后才会生效
  • 是的。在我的代码中,我将继续根据用户的操作(他们的输入)扣除健康,并且我想在 health=0 时结束,这可以根据用户做出的决定而改变
  • 您应该知道用户的健康状况何时会发生变化,只需在每次用户健康状况发生变化时添加if health=0 : break 语句
  • 我想过这样做,但我认为会有更有效的方法来做到这一点。无论如何我都会这样做,这不应该是一个问题。谢谢!

标签: python while-loop pyscripter text-based


【解决方案1】:

条件仅在每次迭代开始时进行评估。 在迭代过程中不会对其进行检查(例如,只要将 health 设置为零)。

要显式退出循环,请使用break

while health>0:
  ...
  if some_condition:
    break
  ...

【讨论】:

    【解决方案2】:

    break 语句,就像在 C 中一样,跳出最小的封闭 forwhile 循环。

    【讨论】:

      【解决方案3】:

      你应该使用'break'语句退出循环

      health=100
      while health>0:
        print("You got attacked")
        # decrement the variable according to your requirement inside the loop
        health=health-1 
        if health==0:
          break
        print("test")
      

      【讨论】:

        【解决方案4】:

        更简洁的实现

        health = 100
        while True:
            if (health <= 0): break
            print ("You got attacked!")
            health = 0
            print ("Testing!")
        

        输出:

        You got attacked!
        Testing!
        

        【讨论】:

          【解决方案5】:

          在 while 循环中,只有指定某种条件才能让代码停止。在这种情况下,生命值总是大于 0,所以它会一直打印“你被攻击了”。 您需要使健康变量减小直到它变为 0 才能打印“测试”。因此;

            `   health=100
                while health>0:
                  print("You got attacked")
                  health-=5
                  if health==0:
                   print("test")
                   break`
          

          也可以这样;

              `  health=100
                if health>0:
                 print("You got attacked")
                if health==0:
                 print("test") `
          

          【讨论】:

            猜你喜欢
            • 2016-01-12
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-04-19
            • 1970-01-01
            • 2021-11-09
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多