2017-08-04 55 views
0

你好我有一個麻煩,在做我的簡單的計算器代碼:d堅持一個簡單的Python程序「ELIF」

def cal(): 

while True: 

print ("welcome to my calculator!") 
print("choose an operation") 

op = input(" +, - ,/ ,*") 


if op == "+": 

    num1 = float(input("enter your first number:")) 
    num2 = float(input("enter your second number:")) 

    print(str(num1 + num2) 



elif op == "/": 

    num1 = float(input("enter your first number:")) 
    num2 = float(input("enter your second number:")) 

    print(str(num1/num2) 


else: 

break 



cal() 

當過我運行的代碼,它說無效語法ELIF

這裏有什麼問題?

+0

很難告訴你的縮進被 –

+0

缺少括號'有兩個左括號和一個左括號,這是一個問題,還有其他類似的行,確保你的圓括號匹配 – cxrodgers

+2

'打印(STR(NUM1 + NUM2)的elif的前2位的print語句 – Kevin

回答

3

你錯過了一堆括號。如果你想利用你的程序還用這個作爲一個模型:

# This function adds two numbers 
def add(x, y): 
    return x + y 

# This function subtracts two numbers 
def subtract(x, y): 
    return x - y 

# This function multiplies two numbers 
def multiply(x, y): 
    return x * y 

# This function divides two numbers 
def divide(x, y): 
    return x/y 

print("Select operation.") 
print("1.Add") 
print("2.Subtract") 
print("3.Multiply") 
print("4.Divide") 

# Take input from the user 
choice = input("Enter choice(1/2/3/4):") 

num1 = int(input("Enter first number: ")) 
num2 = int(input("Enter second number: ")) 

if choice == '1': 
    print(num1,"+",num2,"=", add(num1,num2)) 

elif choice == '2': 
    print(num1,"-",num2,"=", subtract(num1,num2)) 

elif choice == '3': 
    print(num1,"*",num2,"=", multiply(num1,num2)) 

elif choice == '4': 
    print(num1,"/",num2,"=", divide(num1,num2)) 
else: 
    print("Invalid input") 
+0

不錯謝謝你:D –

4

您從未關閉打印功能中的括號。其他if聲明也一樣。您以後也應該使用4個空格的縮進。

if op == "+": 
    num1 = float(input("enter your first number:")) 
    num2 = float(input("enter your second number:")) 
    print(str(num1 + num2)) 
+0

你可以使用4個空格,但我只是發現使用標籤more方便 – Stack

+0

@Stack我總是儘可能地使我的代碼儘可能乾淨,這也涉及以下[PEP8](https://www.python.org/dev/peps/pep-0008/#indentation) –

+1

它沒有關係,標籤給出了相同數量的空格,這是理所當然的不易按壓標籤一次,而不是按壓空間4次。反正按照你想要的:) – Stack