2017-03-15 102 views
-2

我目前正在嘗試編寫一個小計算器,因爲我正在學習python。我的問題是,它始終在else語句處輸出Syntax錯誤,因爲我仍然是初學者,我不知道爲什麼。 :( Code of my calculator其他語句語法錯誤(簡單計算器)

+2

這裏您需要另一個'elif'聲明。在'else'之後,不能檢查其他條件(因此'else')。 – Jan

+0

我把else改成了elif,但它仍然輸出無效語法,並標記elif紅色。 – Skulptis

+1

請將您的代碼添加爲文字,而不是圖片。 – user2314737

回答

0

你缺少一個colon :與其他

應該else: {your logic}

Here's an example

更新:其實你有結腸,但有一個條件,即應該是一個。 elif而不是一個else

更改最後elseelif,如果沒有默認檢查,你不一定需要別的東西。

0

實際上你的代碼有幾個問題。

  1. 你是不是字符串和整數等"4" + "5"之間的轉換是不是9,這是"45",因爲它結合了兩個字符串。但如果你這樣做int("4") + int("5")那麼你會得到9.

  2. 當做一個else語句時,沒有條件。

因此,一個基本如果elif的,否則將是:

a = "yay" 
if a == "yay": 
    print("a likes you") 
elif a == "no": 
    print("a doesn't like you") 
else: 
    print("a doesn't want to respond") 

的Python 2.7

print ("Welcome to your friendly Python calculator. Use + for addition and - for substraction") 
print ("This code uses period (.) for decmimals") 

first = "Please enter your first number " 
second = "Please enter your second number " 

operator = raw_input("Please choose an operation (+ or -) ") 
if operator == "+": 
    num1 = input(first) 
    num2 = input(second) 
    print ("Result: " + str(num1 + num2)) 
elif operator == "-": 
    num1 = input(first) 
    num2 = input(second) 
    print ("Result: " + str(num1 - num2)) 
else: 
    print("You didn't enter a valid operator.") 

的Python 3.6

print ("Welcome to your friendly Python calculator. Use + for addition and - for substraction") 
print ("This code uses period (.) for decmimals") 

first = "Please enter your first number " 
second = "Please enter your second number " 

operator = input("Please choose an operation (+ or -) ") 
if operator == "+": 
    num1 = int(input(first)) 
    num2 = int(input(second)) 
    print ("Result: " + str(num1 + num2)) 
elif operator == "-": 
    num1 = int(input(first)) 
    num2 = int(input(second)) 
    print ("Result: " + str(num1 - num2)) 
else: 
    print("You didn't enter a valid operator.")