Python elif语句不起作用

时间:2015-01-06 02:03:24

标签: python if-statement

我不明白为什么我的下一段代码不起作用:

running = True
name = input("Whats your name?: ")
print ("Hi", name, "Which Program Would You Like to Use")
print ("1. Upper to Lower Case converter")
print ("2. Lower to Upper Case converter")
print ("3. Character Count")

x = input("Enter the Number: ")

if  x==1:
    print ("You have selected the Upper to Lower Case converter")
    y = input("Enter the text you would like converted: ")
    print (y.lower())
elif x==2:
    pass print ("You have selected the Lower to Upper Case converter")
    z = input("Enter the text you would like converted: ")
    print (z.lower()

running = False

2 个答案:

答案 0 :(得分:3)

你需要在这里:

x = int(input("Enter the Number: "))

输入采用字符串

if x==1:   you were comparing string with integer

答案 1 :(得分:2)

您可能在这里错过了一个结束括号:print (z.lower()

在此声明if x==1:中,您将x(一个字符串)与一个int进行比较,并且正如您已经了解的那样,您无法做到这一点。

此问题的一个解决方案是在您收到用户的输入后直接将x转换为int

x = int(input("Enter a number: "))

或者将x与字符串编号进行比较:

if x== "1":
    # do stuff

当然,这取决于你想做什么。