2013-02-28 33 views
0

我正在嘗試創建一個簡單的計算器,但是我使用的IDE不斷告訴我,我正在嘗試使用字符串執行數學運算。我嘗試將所有變量分配給雙打,但它沒有奏效。數學和變量問題 - Python 3.3

"""Calculator program""" 


loop = 1 # 1 means loop; anything else means don't loop. 
choice = 0 # This variable holds the user's choice in the menu 
add1 = 0.0 
add2 = 0.0 
sub1 = 0.0 
sub2 = 0.0 
mul1 = 0.0 
mul2 = 0.0 
div1 = 0.0 
div2 = 0.0 
result = 0.0 
while loop == 1: 
    # Print the options user has 
    print ("Welcome to calculator.py") 

    print ("your options are:") 
    print (" ") 
    print ("1) Addition") 
    print ("2) Subtraction") 

    print ("3) Multiplication") 

    print ("4) Division") 
    print ("5) Quit calculator.py") 
    print (" ") 
    #Perform the desired operation 
    choice = int(input("Choose your option: ").strip()) 
    if choice == 1: 
     add1 = input() 
     add2 = input() 
     result = add1 + add2 
     print(add1, add2) 
     print (add1, "+", add2, "=", result) 
    elif choice == 2: 
     sub2 = input() 
     sub1 = input() 
     result = sub1 - sub2 
     print (sub1, "-", sub2, "=", result) 
    elif choice == 3: 
     mul1 = input("Multiply this: ") 
     mul2 = input("with this: ") 
     result = mul1 * mul2 
     print (mul1, "*", mul2, "=", result) 
    elif choice == 4: 
     div1 = input("Divide this: ") 
     div2 = input("by this: ") 
     result = div1/div2 
     print (div1, "/", div2, "=", result) 
    elif choice == 5: 
     loop = 0 

print ("Thank-you for using calculator.py!") 
+0

@casperOne:這是不是很難說什麼是問。他是Python的新手。顯然,他不知道究竟應該問什麼。但答案很清楚。請重新提出問題,讓提問者有機會與世界交流。 – pepr 2013-02-28 18:44:48

+0

「無效」符合含糊,模糊和不完整的定義。 – casperOne 2013-02-28 19:00:58

+0

@casperone:感謝您關閉'模糊'問題,但我不明白它是如何模糊的。我是Python新手,這是我甚至試圖編寫的第一個程序。 '沒有工作'noes不適合曖昧。含糊不清:「對多個解釋開放。」在這種情況下,'沒有工作'表明我嘗試的解決方案無效,你可能想知道它是如何工作的,但它與手頭的問題無關。 – Xethaios 2013-03-04 15:54:20

回答

3

input()返回一個字符串,而不是數字。你必須要轉換的是:

add1 = int(input()) 

add1 = float(input()) 

取決於你希望你的計算器,支持什麼,否則你是確實與字符串進行數學運算。

+0

此解決方案奏效,謝謝。我希望我事先知道這一點,所以我不會浪費你的時間。 – Xethaios 2013-03-04 16:07:09

0

嘗試堅持一個

int() 

使

int(input)) 

希望這有助於