“超出范围”的else子句导致语法错误

时间:2018-09-24 17:38:25

标签: python python-3.x

我要检查输入数字的值范围,然后打印正确的“大小”(小,中或大)。如果该值超出了我的可接受范围,那么我希望else语句打印出该数字无效。

我的问题的最小示例:

n = int(input("number= "))
if 0 <= n < 5:
    a = "small"
if 5 <= n < 10:
    a = "medium"
if 10 <= n <= 20:
    a = "large"
print("this number is",a)
else:
    print("thats not a number from 0 to 20")

根据Google的说法,这是缩进的问题。我尝试了多种方式来缩进这一点。我可以修复语法,但是逻辑不正确。

7 个答案:

答案 0 :(得分:3)

让我们解决您的直接问题:您有一个else,没有相应的if语句。从句法上讲,这是因为您有一条中间的“伸出的”语句print,该语句终止了一系列if

从逻辑上讲,这是因为您有两个决策层:“这是0-20吗?”和“在该范围内,它有多大?”问题源于仅编写if的一个级别来做出此决定。为了与预期的逻辑流程保持紧密联系,请在外部写一个通用的if,并将您的小/中/大决策封装在该分支中进行打印;在另一个分支中,插入“以上皆非”语句:

n = int(input("number= "))
if 0 <= n <= 20:
    if n < 5:
        a = "small"
    elif n < 10:
        a = "medium"
    else:
        a = "large"
    print("this number is", a)    
else:
    print("that's not a number from 0 to 20")

答案 1 :(得分:2)

您应该尝试类似

n = int(input("number= "))
if 0 <= n < 5:
    a = "small"
elif 5 <= n < 10:
    a = "medium"
elif 10 <= n <= 20:
    a = "large"
else:
    a = "not a number from 0 to 20"

print("this number is",a)

答案 2 :(得分:1)

else语句之前的print语句需要删除或缩进以匹配:

a= "large"

答案 3 :(得分:1)

您遇到语法(缩进)错误:

n = int(input("number= "))
if 0 <= n < 5:
    a = "small"
if 5 <= n < 10:
    a = "medium"
if 10 <= n <= 20:
    a = "large"
#print("this number is",a) indentation error in this line
else:
    print("thats not a number from 0 to 20")

答案 4 :(得分:1)

问题出在打印语句上。

它在与if块相同的级别上缩进,因此if块在包含print语句的行上结束。

因此,下一行的else不正确。

要实现您想要的目标,您应该执行以下操作:

n = int(input("number= "))
if 0 <= n < 5:
    a = "small"
elif 5 <= n < 10:
    a = "medium"
elif 10 <= n <= 20:
    a = "large"
else:
    print("not between 0 and 20")

print("The number is", a)

答案 5 :(得分:1)

您还可以使用以下代码

n = int(input("number= "))

if 10 <= n <= 20:
    a = "large"
    print("this number is",a)
elif 5 <= n < 10:
    a = "medium"
    print("this number is",a)
elif 0 <= n < 5:
    a = "small"
    print("this number is",a)
else:
    print("thats not a number from 0 to 20")

答案 6 :(得分:0)

打印语句需要放置在else块之后 之后。同样,在这种情况下,最好使用 elif 语句而不是 if 语句。

n = int(input("Enter a number between 0 and 20: "))
if 0 <= n <= 5:
    a = "small."
elif n <= 10:
    a = "medium."
elif n <= 20:
    a = "large."
else:
    a = "invalid / out of range."
print("This number is ", a)