我的简单if ... elif ...语句有什么问题

时间:2018-10-26 19:25:59

标签: python python-3.x

该脚本将输入的内容全部格式化为<blockquote> <p>You know you’re in love when you can’t fall asleep because reality is finally better than your dreams.</p> <p>Bottom text</p> </blockquote>类型的格式。

它可以与前两个"1/1"语句一起使用,但是当移至第三个语句时,它仍会在数字前分配elif。如下所示,应该跳到2/3/

非常感谢您的帮助。

4/

3 个答案:

答案 0 :(得分:4)

问题在于您要尝试链接比较:

elif int(port) >= 53 <= 100:

这将检查是否int(port) >= 5353 <= 100。由于53 <= 100始终为true,因此此块将捕获int(port) >= 53处的所有内容。我认为您的意思是:

elif 53 <= int(port) <= 100:

这只会捕获int(port)在53到100(含)之间的情况。您需要对其余elif个块进行类似的更改。

答案 1 :(得分:1)

您混淆了if条件。修复:

def getPort(port):

    # https://stackoverflow.com/questions/12265451/ask-forgiveness-not-permission-explain
    # only convert to int once, if that does not work check for / else bail out
    try:
        p = int(port)
    except ValueError:
        if "/" in port: # no need for regex
            return port
        else:
            raise ValueError("Port either integer or somthing with / in it")

    if p <= 48:               # 49-52 are not covered
        port = "1/" + port

    elif  53 <= p <= 100:     # move the condition between, the way you did it theyre True
        port = "2/" + port    # no matter because 53 <= 100 all the time

    elif 105 <= p <= 152:     # 101-104 are not covered
        port = "3/" + port

    elif 157 <= p <= 204:     # 152-156 are not covered
        port = "4/" + str(port)

    else:
        raise ValueError("Port either integer or somthing with / in it")

    return port

for p in ["1","54","99","121","180","47/11","2000"]:
    try:
        print(getPort(p))
    except ValueError as e:
        print (e)

输出:

# Input: ["1","54","99","121","180","47/11","2000"]

1/1
2/54
2/99
3/121
4/180
47/11
Port either integer or somthing with / in it

您发现一些丢失的端口范围,即50英尺未涵盖,将导致ValueError。

答案 2 :(得分:1)

您的错误在这里:

elif int(port) >= 53 <= 100:

这表示(您可以阅读有关chained comparisson operators的信息):

elif int(port) >= 53 and 53 <= 100:

,由于第二部分的原因,它将始终为True;因此,这就是为什么以后的elif永远无法到达的原因。


我的建议:

port = input("Enter port number:")
int_port = int(port)    # so we don't repeat the same operation multiple unnecessary times

if bool(re.search('\/', port)):
    pass
elif int_port <= 48:
    port = "1/" + port
elif 53 <= int_port <= 100:
    port = "2/" + port
elif 105 <= int_port <= 152:
    port = "3/" + port
elif 157 <= int_port <= 204:
    port = "4/" + port

print(port)