【问题标题】:While True and condition statementsWhile True 和条件语句
【发布时间】:2021-11-07 17:47:44
【问题描述】:

我正在努力得到答案m = [0, 2, 0, 4, 0]:

m = []
while True:
    for x in range(1, 6):
        if x == 2:
            m.append(x)
            continue
        else:
            m.append(0)
            continue
        if x == 4:
            m.append(x)
            continue
        else:
            m.append(0)
            continue
    break

print(m)

答案来了m = [0, 2, 0, 0, 0]

【问题讨论】:

  • 你可能会考虑使用类似Python Tutor 的东西来可视化这个程序的执行。
  • while 循环的意义何在?
  • 这里需要elif。 if x == 2:/elif x == 4:/else:。您的代码永远不会超过第一个 if 语句。
  • 是的,他们不应该这样做。他还可以完全删除第一个else: 子句来解决问题,但正确答案是if/elif/else 没有continues。
  • IF x == 2 做某事并继续 ELSE 做其他事情并继续 - 后面的 if x==4 永远不会执行,因为您的代码“继续”回到 while 循环。如果你修复到 if/elif/else 就不需要继续了

标签: python list loops


【解决方案1】:

主要问题是您需要使用elif。您也不需要 while 循环。

m = []
for x in range(1, 6):
    if x == 2:
        m.append(x)
    elif x == 4:
        m.append(x)
    else:
        m.append(0)

print(m)

但这看起来你需要做的只是检查该值是否可以被 2 整除:

m = []
for x in range(1, 6):
    if x % 2 == 0:
        m.append(x)
    else:
        m.append(0)

print(m)

使用列表理解:

print([x if x % 2 == 0 else 0 for x in range(1, 6)])

【讨论】:

    【解决方案2】:

    continue 语句干扰了您的条件。您应该在没有 else 的情况下使用它们,或者只使用 if/elif/else:

    if x == 2:
       m.append(x)
       continue
    if x == 4:
       m.append(x)
       continue
    m.append(0)
    

    或

    if x == 2:
       m.append(x)
    elif x == 4:
       m.append(x)
    else:
       m.append(0)
    

    并且,假设您在 x 为 2 时和 x 为 4 时做同样的事情,您可以使用 or 关系来最大程度地减少代码重复:

    if x == 2 or x == 4:
       m.append(x)
    else:
       m.append(0)
    

    【讨论】:

      猜你喜欢
      • 2015-02-15
      • 2021-06-02
      • 2013-12-17
      • 2011-10-23
      • 2016-02-29
      • 2016-05-16
      • 2020-05-01
      • 2014-07-27
      • 2016-02-20
      相关资源
      最近更新 更多