2015-10-06 50 views
-1

我的第二個else語句拋出語法錯誤,爲什麼?else:聲明語法錯誤,簡單的Python

這是用於檢查sideswap數字代碼:

number1 = int(input("Enter a number between 0 and 9")) 
number2 = int(input("Enter a number between 0 and 9")) 
number3 = int(input("Enter a number between 0 and 9")) 


X = number1 + number2 + number3 

while True: 
     if X%3 !=0: 
      print("Not a valid sideswap number") 
      number1 = int(input("Enter a number between 0 and 9")) 

      number2 = int(input("Enter a number between 0 and 9")) 

      number3 = int(input("Enter a number between 0 and 9")) 

     else: 
      if number2 - number3 == 1: 
       print("Not a valid sideswap number") 
       number1 = int(input("Enter a number between 0 and 9")) 

       number2 = int(input("Enter a number between 0 and 9")) 

       number3 = int(input("Enter a number between 0 and 9")) 

     else:   
      if number3 - number1 == 1: 
       print("Not a valid sideswap number") 
       number1 = int(input("Enter a number between 0 and 9")) 

       number2 = int(input("Enter a number between 0 and 9")) 

       number3 = int(input("Enter a number between 0 and 9")) 

     else: 
      if number1 - number2 == 1: 
       print("Not a valid sideswap number") 
       number1 = int(input("Enter a number between 0 and 9")) 

       number2 = int(input("Enter a number between 0 and 9")) 

       number3 = int(input("Enter a number between 0 and 9")) 

回答

2

代替

else: 
    if number2 - number3 == 1: 

表達是

elif number2 - number3 == 1: 

看看在documentation

>>> if x < 0: 
...  x = 0 
...  print 'Negative changed to zero' 
... elif x == 0: 
...  print 'Zero' 
... elif x == 1: 
...  print 'Single' 
... else: 
...  print 'More' 
1

有沒有像在Python else if。使用elif

例如:

else:   
    if number3 - number1 == 1: 

更改爲:

elif number3 - number1 == 1: 
1

你不能有多個else爲同一if。你在找什麼是elif:。示例 -

while True: 
     if X%3 !=0: 
      print("Not a valid sideswap number") 
      number1 = int(input("Enter a number between 0 and 9")) 

      number2 = int(input("Enter a number between 0 and 9")) 

      number3 = int(input("Enter a number between 0 and 9")) 

     elif number2 - number3 == 1: 
       print("Not a valid sideswap number") 
       number1 = int(input("Enter a number between 0 and 9")) 

       number2 = int(input("Enter a number between 0 and 9")) 

       number3 = int(input("Enter a number between 0 and 9")) 

     elif number3 - number1 == 1: 
       print("Not a valid sideswap number") 
       number1 = int(input("Enter a number between 0 and 9")) 

       number2 = int(input("Enter a number between 0 and 9")) 

       number3 = int(input("Enter a number between 0 and 9")) 

     elif number1 - number2 == 1: 
       print("Not a valid sideswap number") 
       number1 = int(input("Enter a number between 0 and 9")) 

       number2 = int(input("Enter a number between 0 and 9")) 

       number3 = int(input("Enter a number between 0 and 9"))