【问题标题】:Is there a way to let Python generate multiple if statements?有没有办法让 Python 生成多个 if 语句?
【发布时间】:2015-01-04 16:06:22
【问题描述】:

我只需要在每个 if 语句中的每个数字上加上 +30。我需要其中的 36 个,有没有办法让海龟做出更多的 if 语句或类似的东西?我真的被困住了,手动方式会很疯狂。

例如:

if 0 <= x <=30 and 0 <= y <= 30:
      turtle.drawsstuff

if 30 <= x <=60 and 0 <= y <= 60:

etc.

【问题讨论】:

  • 这取决于你的 if 语句
  • if 语句体中有什么?
  • 乌龟填满一个正方形
  • 如果你需要这个,你就是在做一些困难的事情或者完全做错了。

标签: python if-statement auto-generate


【解决方案1】:

使用 for 循环。

for n in range(0, 36 * 30, 30):
    if n <= x <= n + 30 and 0 <= y <= n + 30:
        pass #do something

【讨论】:

    【解决方案2】:
    for n in range(0, 36 * 30, 30):
        if n <= x <= (n+30) and n <= y <= (n+30):
            pass  # (do stuff)
    

    range 可以为“step”值采用可选的第三个参数。如需参考,请参阅Python's documentation on range

    【讨论】:

      猜你喜欢
      • 2021-07-30
      • 2020-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多