Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/26.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:for循环和输入在使用由类组成的列表时失败_Python_Python 3.x_List_Class_Input - Fatal编程技术网

Python:for循环和输入在使用由类组成的列表时失败

Python:for循环和输入在使用由类组成的列表时失败,python,python-3.x,list,class,input,Python,Python 3.x,List,Class,Input,首先,我对python和一般的编码非常陌生,我不是在构建一些巨大的东西,只是一些基本的东西 因此,我尝试创建一个包含我所有产品列表的程序,当某个产品售出时,我可以将售出产品的ID提供给输入(x),然后我开始一个for循环,如果输入等于其中一个产品ID,它应该被删除,但不会发生,它被完全忽略,没有任何内容被删除您的x是一个字符串。因此,if子句变得类似于“102”==102,其计算结果为False。如果将行更改为: class products: def __init__(self, id

首先,我对python和一般的编码非常陌生,我不是在构建一些巨大的东西,只是一些基本的东西
因此,我尝试创建一个包含我所有产品列表的程序,当某个产品售出时,我可以将售出产品的ID提供给输入(x),然后我开始一个for循环,如果输入等于其中一个产品ID,它应该被删除,但不会发生,它被完全忽略,没有任何内容被删除

您的
x
是一个字符串。因此,if子句变得类似于
“102”==102
,其计算结果为
False
。如果将行更改为:

class products:
    def __init__(self, id, size, color, price, is_sold):
        self.id = id
        self.size = size
        self.color = color
        self.price = price
        self.is_sold = is_sold
total = 0
product_102 = products(102, 34, 'red', 160, False)
product_104 = products(104, 32, 'blue', 140, False)
all_products = [product_102.id, product_104.id]
print(all_products)
x = input('Enter product id: ')
for each in all_products:
    if each == x:
        all_products.remove(each) 
print(all_products)

请考虑预先检查您的输入,因为如果输入了十进制字符串,此转换可能导致异常。

< P> Python中的所有用户输入均为字符串类型。

假设用户输入了104,实际上是“104”

x = int(input('Enter product id: ')) 
把它改成一个整数

>>> 104 == '104'
False

您最好使用这个简单的构造,并确保使用显式类型转换到int,就像Python中一样,原始输入是3.x中输入的默认行为

for each in all_products:
if each == int(x):
    all_products.remove(each)
甚至更简单

x = int(input('Enter product id: '))
if x in all_products:
    all_products.remove(x) 
    print('removed product:',x)
print(all_products)
if x in all_products: all_products.remove(x)