python - 2 if 语句与 1 else 破坏循环
问题描述
这里我的 Python 代码是
while True:
a = int(input("enter a digit"))
if a < 10:
print("digit is less than 10")
if a < 50 and a > 10:
print("digit is more than 10")
else:
print("error")
所以我的疑问是,当我为 (a < 10) 运行该程序时,它会显示相对于它的 if 语句的正确输出,但它也会给出 else 语句的输出以及 if。但是对于第二个短语中提到的 if 条件(a<50 和 a > 10),输出只是“数字大于 10”,这是正确的,但是当值小于时,为什么会有额外的 else 输出10.
解决方案
如果您希望所有if
语句都属于同if..else
一块,那么您应该这样做:
while True:
a = int(input("enter a digit"))
if a < 10:
print("digit is less than 10")
elif a < 50 and a > 10:
print("digit is more than 10")
else:
print("error")
解释:
您当前的代码有两个不同的if..else
块:
a = int(input("enter a digit"))
if a < 10:
print("digit is less than 10")
if a < 50 and a > 10:
print("digit is more than 10")
else:
print("error")
所以如果a<10
,它会打印"digit is less than 10"
。然后该if
块结束,您的代码进入第二个if
块。既然a
不在 and 之间10
,50
就会进入else
语句并打印"error"
。
推荐阅读
- python - 如何使用 python PIL 在处理后的图像中获取一组颜色
- database - 订单排名列算法
- flutter - 如何在flutter中只写十个动态标签的条件
- python - 使用 LPproblem 类添加“每隔一天约束”
- c - 为什么Linux内核包含重复代码?
- flutter - 如何路由到特定屏幕?如何在 custom_Navigator 中正确执行嵌套路由
- python - 在 MMS 中将请求作为媒体发布
- object-detection-api - 使用 tensorflow 对象检测 api 训练 CenterNet MobileNetV2 FPN 512x512 时出现错误“indices[0] = 0 not in [0,0)”
- java - Java流,从对象中获取多个属性
- python - Ubuntu Apache 上的 Flask / 错误 404 在此服务器上找不到请求的 URL