2016-04-18 51 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

相關問題