计算器函数不输出任何内容

Calculator function outputs nothing

我需要设计一个计算器 UI:

Welcome to Calculator!
1  Addition
2  Subtraction
3  Multiplication
4  Division
Which operation are you going to use?: 1
How many numbers are you going to use?: 2
Please enter the number: 3
Please enter the number: 1
The answer is 4.

这是我目前拥有的:

print("Welcome to Calculator!")

class Calculator:
    def addition(self,x,y):
        added = x + y
        return sum
    def subtraction(self,x,y):
        diff = x - y
        return diff
    def multiplication(self,x,y):
        prod = x * y
        return prod
    def division(self,x,y):
        quo = x / y
        return quo


calculator = Calculator()

print("1 \tAddition")
print("2 \tSubtraction")
print("3 \tMultiplication")
print("4 \tDivision")
operations = int(input("What operation would you like to use?:  "))

x = int(input("How many numbers would you like to use?:  "))

if operations == 1:
    a = 0
    sum = 0
    while a < x:
        number = int(input("Please enter number here:  "))
        a += 1
        sum = calculator.addition(number,sum)

我真的需要一些帮助! Python 3 中所有关于计算器的教程都比这简单得多(因为它只需要 2 个数字,然后简单地打印出答案)。

我需要帮助才能使用计算器 class 中的功能。当我尝试 运行ning 到目前为止,它让我输入我的数字和诸如此类的东西,但它就结束了。它不 运行 操作或其他任何东西。我知道到目前为止我只有加法,但如果有人能帮我算出加法,我想我可以做剩下的。

您的程序接受输入,运行一系列操作,然后结束而不显示结果。在 while 循环结束后尝试类似 print(sum) 的操作。

原样的代码不起作用。在 addition 函数中,您 return 变量 sum 将与内置 sum 函数发生冲突。

所以只需添加 return 并且通常避免使用 sum,使用类似 sum_ 的内容:

这对我来说很好用:

print("Welcome to Calculator!")

class Calculator:
    def addition(self,x,y):
        added = x + y
        return added
    def subtraction(self,x,y):
        diff = x - y
        return diff
    def multiplication(self,x,y):
        prod = x * y
        return prod
    def division(self,x,y):
        quo = x / y
        return quo

calculator = Calculator()

print("1 \tAddition")
print("2 \tSubtraction")
print("3 \tMultiplication")
print("4 \tDivision")
operations = int(input("What operation would you like to use?:  "))

x = int(input("How many numbers would you like to use?:  "))

if operations == 1:
    a = 0
    sum_ = 0
    while a < x:
        number = int(input("Please enter number here:  "))
        a += 1
        sum_ = calculator.addition(number,sum_)

    print(sum_)

运行:

$ python s.py
Welcome to Calculator!
1   Addition
2   Subtraction
3   Multiplication
4   Division
What operation would you like to use?:  1
How many numbers would you like to use?:  2
Please enter number here:  45
Please enter number here:  45
90