Python初学者,简单计算器程序的数学函数

0 投票
2 回答
2086 浏览
提问于 2025-04-17 15:56

我正在为一个编程课程制作一个简单的计算器,我看过一些PDF文件,但我还是搞不清楚怎么写一个函数,然后用这个函数来打印两个数字相加的结果。有人能帮我吗?

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()

2 个回答

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

你想要返回你计算出来的值。那么你的打印语句就应该能正常工作。

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的结果。

撰写回答