2016-04-18 54 views
0

我只是让自己习惯于如果在python中的其他语句,但我有一些麻烦试图让我的工作,究竟发生了什么?为什么我的if else语句不正确?

x = input("Enter your string") 
while not set(x).issubset({'m', 'u', 'i'}): 
    print("false") 
    x = input("Enter your string") 
else: 
    print("Your String is " + x) 
Question = int(input("Which rule would you like to apply? enter numbers 1-4: ")) 
if Question is 1: 
    print("hello") 
    '''issue arises in the else area below''' 
else if Question is not 1: 
     print("other") 

回答

6

在Python,你不写else if,就像您在C++中。您将elif写为特殊关键字。

if Question is 1: 
    print("hello") 
elif Question is not 1: 
    print("other") 
+1

您不应该使用'is'来比较数字。 – JBernardo

+0

@JBernardo,是的,但这并没有引起这个问题的问题 – Holloway

+0

如果你正在使用它来重新检查你刚刚检查过的同样的条件,那么'elif'是多余的。 – khelwood

1

此行

else if Question is not 1: 

应该读

elif Question is not 1: 
1

的if ... else语句的语法是 -

if expression(A): 
    //whatever 
elif expression(B): 
    //whatever 
else: 
    //whatever 
1

我想你应该在这种情况下要书写的是:

if Question==1: 
    print("hello") 
else: 
    print("other") 

你不需要if检查Question是不是1,因为那是什么else的意思是:即if上面的语句不匹配。

此外,请使用==来比较数字,而不是is

在您确实需要else if的情况下,Python关键字为elif

if Question==1: 
    print("hello") 
elif Question==2: 
    print("goodbye") 
else: 
    print("other") 
+0

@joelgoldstick实际上'q是1'会检查'q'是否与这个其他'int'具有值'1'相同的对象,实际上它会为'1'工作,但通常还是比较数字的错误方法。 – khelwood

相关问题