Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/335.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用类的计算器出现错误_Python - Fatal编程技术网

Python 使用类的计算器出现错误

Python 使用类的计算器出现错误,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

当我在练习课程时,我试着用课堂制作一个计算器,但它吐出了一些错误。我用另一个stackoverflow问题的答案来帮助我,但那个人用的是python2


您没有将
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