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

2024-10-01 09:16:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在为一门程序设计课程制作一个基本计算器,我已经读了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()

Tags: theforinputifdivisionfirstprintenter
2条回答
def addition(intFirstOperand, intSecondOperand):
    addition = intFirstOperand + intSecondOperand
    return addition

您需要返回计算的值。那么你的打印报表应该行得通。在

我建议您在函数中选择一个不同的变量名,因为函数和变量同名可能会令人困惑。您可以选择从函数内部打印,也可以返回一个值,然后在函数外部打印返回的值。在

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。在

相关问题 更多 >