Python 使用类的计算器出现错误
当我在练习课程时,我试着用课堂制作一个计算器,但它吐出了一些错误。我用另一个stackoverflow问题的答案来帮助我,但那个人用的是python2Python 使用类的计算器出现错误,python,Python,当我在练习课程时,我试着用课堂制作一个计算器,但它吐出了一些错误。我用另一个stackoverflow问题的答案来帮助我,但那个人用的是python2 您没有将input的值保存到self.x和self.y,因此它们一直是None。您正在returning它,但也没有将它保存在那里 对x执行以下操作,对y执行相同操作 def prompt_x(self): try: self.x = int(input('Enter the first number: ')) e
您没有将
input
的值保存到self.x
和self.y
,因此它们一直是None
。您正在return
ing它,但也没有将它保存在那里
对x
执行以下操作,对y
执行相同操作
def prompt_x(self):
try:
self.x = int(input('Enter the first number: '))
except ValueError:
print('Sorry, wrong value')
或
现在,如果您输入例如字母,您将得到
“对不起,错误的值”
,您需要再次运行该程序。添加一个while True
循环,它将继续询问,直到您给出一个可以转换为int
然后用一种常用的方法来代替方法,避免用同样的方法写两遍
def prompt(self, value_type):
while True:
try:
return int(input(f'Enter the {value_type} number: '))
except ValueError:
print('Sorry, wrong value')
在run
方法中这样使用
self.x = self.prompt('first')
self.y = self.prompt('second')
对于操作员来说,它可以简化,并通过
while
循环进行改进
def prompt_op(self):
while self.op not in Calc.operations:
self.op = input("Enter an operation: " + ', '.join(Calc.operations) + ":")
您没有将输入
x和y
分配给实例变量
更新你的代码如下
def prompt_x(self):
try:
# added self.x
self.x = int(input('Enter the first number: '))
except ValueError:
print('Sorry, wrong value')
# you dont have to return them
# return self.x
def prompt_y(self):
try:
# added self.y
self.y = int(input('Enter a second number: '))
except ValueError:
print('Sorry, wrong value')
# you dont have to return them
# return self.y
错误是什么?请在
self.prompt\ux
和self.prompt\uy
中显示a.您没有分配给self.x
和self.y
。现在不需要返回self.x或self.y谢谢您的帮助!对于糟糕的邮件,很抱歉。那么,“在run
method中这样使用”@abdullahna将您的方法命名为run
def prompt_op(self):
while self.op not in Calc.operations:
self.op = input("Enter an operation: " + ', '.join(Calc.operations) + ":")
def prompt_x(self):
try:
# added self.x
self.x = int(input('Enter the first number: '))
except ValueError:
print('Sorry, wrong value')
# you dont have to return them
# return self.x
def prompt_y(self):
try:
# added self.y
self.y = int(input('Enter a second number: '))
except ValueError:
print('Sorry, wrong value')
# you dont have to return them
# return self.y