计算器功能什么都不输

时间:2017-07-28 20:45:53

标签: python python-3.x calculator

我需要使用以下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个数字,然后只是打印出答案)。

我需要帮助获取我工作的Calculator类中的函数。当我尝试运行到目前为止,它让我输入我的数字和诸如此类的东西,然后它就结束了。它没有运行任何操作。我知道到目前为止我只有添加,但如果有人可以帮助我找出补充,我想我可以做其余的事。

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

代码不起作用。在addition函数中,您返回的变量sum将与sum函数中的内置版本冲突。

因此,只需返回已添加内容,并且通常会避免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