[英]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.