繁体   English   中英

如何在 for/range python 缓冲区中打印大于值且小于值的数字? [关闭]

[英]how do i print numbers great than a value and less than a value in a for/range python buffer? [closed]

我试过这段代码:

for i in range(100):
        if i < 10:
                print("The following number is less than 10")
        if i > 50:
                print("The following numbers are greater than 50")
        else:
                print("The following numbers are between 10 and 50, including 10 and 50")
        print(i)

但有些数字总是用两个打印值显示

我猜所有小于 10 的数字都会打印 2 次? 在这种情况下,您需要在第二个条件中添加一个elif

for i in range(100):
        if i < 10:
                print("The following number is less than 10")
        elif i > 50:
                print("The following numbers are greater than 50")
        else:
                print("The following numbers are between 10 and 50, including 10 and 50")
        print(i)

考虑i = 5的情况

if i < 10:   # - True
    print("The following number is less than 10")

if i > 50:   # - False
    print("The following numbers are greater than 50")
else:        # executed because the condition is False
    print("The following numbers are between 10 and 50, including 10 and 50")

第一个条件将评估为 True,因此将打印“小于 10”消息。 第二个条件的计算结果为 False,因此,执行else块中的语句。

您想要的是在第二个条件中使用elif ,这样如果第一个条件为 True,则不会执行else子句:

if i < 10:     # - True
    print("The following number is less than 10")
elif i > 50:   # skipped because first condition is True
    print("The following numbers are greater than 50")
else:          # skipped because first condition is True
    print("The following numbers are between 10 and 50, including 10 and 50")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM