【问题标题】:Calculator function outputs nothing计算器功能不输出任何内容
【发布时间】:2018-01-05 00:48:11
【问题描述】:

我需要设计一个具有以下 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 类中的函数。当我尝试运行我目前拥有的东西时,它可以让我输入我的数字和诸如此类的东西,但它就结束了。它不运行操作或其他任何东西。我知道我到目前为止只有加法,但如果有人能帮我弄清楚加法,我想我可以做剩下的。

【问题讨论】:

标签: python python-3.x calculator


【解决方案1】:

代码原样不起作用。在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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 谢谢!我不敢相信我忘记了哈哈。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-08
    • 1970-01-01
    • 2017-06-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多