我需要设计一个具有以下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 个数字,然后简单地打印出答案(。
我需要帮助使我制作的计算器类中的函数工作。当我尝试运行到目前为止我所拥有的东西时,它让我输入我的数字等等,但随后它就结束了。它不会运行操作或其他任何操作。我知道到目前为止我只有加法,但如果有人能帮我弄清楚加法,我想我可以做剩下的。
原样代码不起作用。在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
程序接受输入,运行一系列操作,然后结束而不显示结果。 在 while 循环结束后尝试类似print(sum)
的操作。