【问题标题】:How can I check if number is multiple of 3 or contains the digit 5?如何检查数字是 3 的倍数还是包含数字 5?
【发布时间】:2021-11-19 16:21:11
【问题描述】:
digit = 5
for i in range(1, 101):
    if i % 3 == 0:
        print ("MultipleOfThree", end=" ")
    elif i:
        for digit in str(i):
            print ("FiveInIt", end=" ")
    else:
        print(i, end=" ")

我想在一行中看到这样的:

1 2 MultipleOfThree 4 FiveInIt MultipleOfThree 7 8 MultipleOfThree 10 11 MultipleOfThree 12 13 14 FiveInIt ........ 

但输出给出:

FiveInIt FiveInIt MultipleOfThree FiveInIt FiveInIt MultipleOfThree .......

【问题讨论】:

    标签: python if-statement contains modulo


    【解决方案1】:

    应该是:

    digit = 5
    for i in range(1, 101):
        if i % 3 == 0:
            print ("MultipleOfThree", end=" ")
        elif str(digit) in str(i):
            print ("FiveInIt", end=" ")
        else:
            print(i, end=" ")
    

    【讨论】:

    • 小评:必须是elif str(digit) in str(i):
    • @DanielLenz 对!谢谢!
    • 首先,得到错误:'in ' requires string as left operand, not int 但是当我在str(i)中尝试str(digit)时,没关系谢谢跨度>
    • @ÜmitYaman 感谢 DanielLenz 的评论,我修复了它
    【解决方案2】:

    这应该可以工作

    digit = '5'
    for i in range(1, 101):
        if i % 3 == 0:
            print("MultipleOfThree", end=" ")
        elif digit in str(i):
            print("FiveInIt", end=" ")
        else:
            print(i, end=" ")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-14
      • 2012-12-23
      • 2014-12-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多