2017-08-04 7 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

それはのelif –

+0

括弧が欠けていると言うのは難しいです。 '2つの左括弧と1つの左括弧があり、これは問題である。このような他の線が同様に存在することを確認あなたの括弧のマッチングを行います – cxrodgers

+2

'プリント(STR(NUM1 + NUM2)の前に、あなたのインデントはprint文に2つのスペース – 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つのスペースを使用することができますが、私はちょうどタブは複数を使用して検索します私はいつも、できるだけ自分のコードをクリーンにしようととても便利。 – Stack

+0

@Stack、また[PEP8](https://www.python.org/dev/peps/pep-0008/#indentation)それは問題doesntの –

+1

を以下の関係、タブは同じ数のスペースを与えます。それはjusですスペースを4回押すよりもタブを1回押すのが簡単です。とにかくあなたが望むものに従います。) – Stack

関連する問題