【问题标题】:Python increment value by 100 while truePython 在 true 时将值增加 100
【发布时间】:2020-06-25 01:20:32
【问题描述】:
 if 150 <= center_x <= 180:
            x = 200
            x += 100
            MESSAGE = str(x)

我正在运行此语句。虽然是真的,但我希望 x 增加 100,从而输出:300、400、500、600 700 等

由于某种原因,我的输出是 300、300、300、300 等。

我该如何解决这个问题? (提前致谢):)

【问题讨论】:

  • 您每次都将 x 重置为 200。将该行移到语句之外的其他位置。
  • 您需要将x = 200 保留在外面。每次都重置

标签: python increment


【解决方案1】:

我认为这段代码在 while True 循环中。如果是这样,那么问题是您在每次迭代时将 x 设置为 200,然后将其递增 100,每次迭代时将其设为 300。您应该在循环之外将起始值赋予 x

【讨论】:

  • 你是个天才
【解决方案2】:
#First you need to define your center_x. You may get this value from some other
#function in your script. I will use 160 as a valid example
center_x  = 160

#You need to define initial value of x outside of the loop so it does not "reset"
x = 200
if 150 <= center_x <= 180:
    while x <= 600: #Here you set the limit of where you want to stop adding. I used 600 as example
        x += 100
        print(x) #There is no need to set a MESSAGE variable, you can directly print the x variable

【讨论】:

    【解决方案3】:

    尝试将其更改为:

    x = 200
    if 150 <= center_x <= 180:
        x += 100
        MESSAGE = str(x)
    

    【讨论】:

      猜你喜欢
      • 2019-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-24
      相关资源
      最近更新 更多