首页 > 解决方案 > 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.

标签: pythonpython-3.xif-statementnested

解决方案


如果您希望所有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 之间1050就会进入else语句并打印"error"


推荐阅读