2013-02-14 98 views
0

我正在爲一門編程課程做一個基本的計算器,我已經閱讀了PDF的,但我不知道如何製作一個函數,然後用它來打印添加兩個數字的結果。有人可以幫我嗎?Python初學者,一個簡單的計算器程序的數學函數

def addition(intFirstOperand, intSecondOperand): 
    addition = intFirstOperand + intSecondOperand 

print ('What mathematical operation would you like to perform? Enter a number:') 
print ('1 - addition') 
print ('2 - subtraction') 
print ('3 - multiplication') 
print ('4 - division') 

intOperation = input() 
intOperation = int(intOperation) 

addition = '1' 
subtraction = '2' 
multiplication = '3' 
division = '4' 

if intOperation == 1 : 
    print ('Please enter the first operand for addition:') 
    intFirstOperand = input() 
    print ('Please enter the second operand for addition:') 
    intSecondOperand = input() 
    print addition(intFirstOperand, intSecondOperand) 

if intOperation == 2 : 
    print ('Please enter the first operand for subtractiom:') 
    intFirstOperand = input() 
    print ('Please enter the second operand for subtraction:') 
    intSecondOperand = input() 

if intOperation == 3 : 
    print ('Please enter the first operand for multiplication:') 
    intFirstOperand = input() 
    print ('Please enter the second operand for multiplication:') 
    intSecondOperand = input() 

if intOperation == 4 : 
    print ('Please enter the first operand for division:') 
    intFirstOperand = input() 
    print ('Please enter the second operand for division:') 
    intSecondOperand = input() 
+0

在另外的功能添加一個'return'聲明: '返回addition',如果你對py3.x然後不要忘記字符串先轉換成整數('輸入()'返回py3x中的字符串)。 – 2013-02-14 22:57:38

回答

0
def addition(intFirstOperand, intSecondOperand): 
    addition = intFirstOperand + intSecondOperand 
    return addition 

你想回到你的計算值。那麼你的打印報告應該工作。

+0

我得到這個語法錯誤:print addition(intFirstOperand,intSecondOperand):m:\ functest.py,第2418行 – 2013-02-14 23:00:25

+0

@NickDrzewiecki你的python版本? – 2013-02-14 23:01:14

+0

4.1.7-1(轉26990)WING IDE和Python 3.2.3 – 2013-02-14 23:02:38

2

我會建議在你的函數中選擇一個不同的變量名稱,因爲它可能會令人困惑的是具有一個具有相同名稱的函數和變量。您可以選擇從函數內打印,也可以返回一個值,然後在函數外打印返回的值。

def addition(first,second): 
    result = int(first) + int(second) 
    #print result 
    return result 

print(addition(5,3)) #prints 8 in python 3.x 

或者,您可以跳過將值賦給'result',而只是返回first + second。

+0

@AshwiniChaudhary感謝您指出了這一點。我已經編輯我的答案。 – purpleladydragons 2013-02-14 23:13:20