我正在编写一个编程课程的基本计算器,我已经阅读了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()
答案 0 :(得分:2)
我建议在你的函数中选择一个不同的变量名,因为它可能会让一个具有相同名称的函数和变量感到困惑。您可以选择在函数内打印,也可以返回一个值,然后在函数外部打印返回的值。
def addition(first,second):
result = int(first) + int(second)
#print result
return result
print(addition(5,3)) #prints 8 in python 3.x
或者,您可以跳过为“结果”分配值,而只是返回第一个+第二个。
答案 1 :(得分:0)
def addition(intFirstOperand, intSecondOperand):
addition = intFirstOperand + intSecondOperand
return addition
您想要返回您计算的值。那么你的打印陈述应该有效。