打印 1-100 的数字,跳过可被 3 和 5 整除的数字

新手上路,请多包涵

我想打印 1-100 的数字,跳过可被 3 和 5 整除的数字,当我使用 code-1 时,我没有得到正确的输出,我得到的是 1-100 的完整计数

#CODE1
i=1
a=1
while i<=100:
    if (a%3==0 and a%5==0) :
           a=a+1
    else:
        print(a)
        a=a+1
    i=i+1

但是当我使用 CODE-2 时,我得到了想要的结果

#CODE2
i=1
a=1
while i<=100:
    if ((a%3 and a%5)==0) :
        a=a+1
    else:
        print(a)
        a=a+1
    i=i+1

注意代码的第四行,为什么第一行代码错了?

原文由 user10647398 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 975
2 个回答

考虑一下:

 a = 10

(a%3 == 0) and (a%5 == 0)  # False
(a%3 and a%5) == 0         # True

第一次尝试给出 False 错误,因为它需要同时满足 两个 条件;你需要 or 代替。如果你仔细看,一些数字(例如 15 )被排除在外,与同时具有 35 作为因素的数字一致

The second attempt is correct because if a is not divisible by either 3 or 5, the expression evaluates to False , and 0 == False gives True 。更惯用的是写:

 not (a%3 and a%5)

原文由 jpp 发布,翻译遵循 CC BY-SA 4.0 许可协议

检查这也是它的工作! 100%

 def result(N):
           for num in range(N):
          if num % 3 == 0 and num % 5 == 0:
             print(str(num) + " ", end="")
          else:
             pass
    if __name__ == "__main__":
       N = 100

       result(N)

原文由 Asmatullah Haroon 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题