【问题标题】:Beginner at Python, math functions for a simple calculator programPython初学者,一个简单计算器程序的数学函数
【发布时间】:2013-01-30 21:20:15
【问题描述】:

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

【问题讨论】:

  • 在加法函数中添加return 语句:return addition,如果您使用的是 py3.x,那么不要忘记先将字符串转换为整数(input() 返回py3x 中的字符串)。

标签: python string function math integer


【解决方案1】:
def addition(intFirstOperand, intSecondOperand):
    addition = intFirstOperand + intSecondOperand
    return addition

您想要返回您计算的值。那么你的打印语句应该可以工作了。

【讨论】:

  • 如果你使用的是 Python3,它需要是print(addition(firstOperand, secondOperand))
  • @NickDrzewiecki 在 py3x 中使用 print()
  • 就个人而言,我发现 addition 这个词的各种用法在您的回答中令人困惑。我会使用 result 作为本地参数,以保持这两种用途完全明确。或者只返回没有局部变量的目录。
  • @TravisGriggs:sum 是 Python 内置的,是标识符的错误选择。 直接返回是更好的方法。
  • @Johnsyweb。哎哟,捂脸。固定的。谢谢。应该避免我想说的确切的模棱两可,我换了另一种。
【解决方案2】:

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

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

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

或者,您可以跳过将值分配给“结果”,而只返回 first+second。

【讨论】:

  • @AshwiniChaudhary 感谢您指出这一点。我已经编辑了我的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多