I am trying to print all the items but there is an error:
TypeError: float() argument must be a string or a number, not 'NoneType'
I have no clue why it is giving this error.
I am using float for price and int for quantity, because it initialises as a string by default, which will give another error because strings are not allowed as inputs for price and quantity.
import csv
class Item:
pay_rate = 0.8 # The pay rate after 20% discount
all = []
def __init__(self, name: str, price: float, quantity=0):
# Run validations to the received arguments
assert price >= 0, f"Price {price} is below 0!"
assert quantity >= 0, f"Price {price} is below 0!"
# Assign to self object
self.name = name
self.price = price
self.quantity = quantity
# Actions to execute
Item.all.append(self)
def calculate_total_price(self):
return self.price * self.quantity
def apply_discount(self):
self.price = self.price * self.pay_rate
@classmethod
def instantiate_from_csv(cls):
with open('items.csv', 'r') as f:
reader = csv.DictReader(f)
items = list(reader)
for item in items:
Item(
name=item.get('name'),
price=float(item.get('price')),
quantity=int(item.get('quantity')),
)
def __repr__(self):
return f"Item('{self.name}', {self.price}, {self.quantity})"
Item.instantiate_from_csv()
print(Item.all)
CSV File:
name , price , quantity
"Phone" , 100 , 1
"Laptop" , 1000 , 3
"Cable" , 10 , 5
"Mouse" , 50 , 5
"Keyboard" , 75 , 5
CodePudding user response:
The dict.get
method will return None
if the given key is not present in the dictionary. You then attempt to call float()
on this result and get the error in the title. I assume you are using dict.get
because when you tried to use the index operator ([]
), you got a KeyError
. Someone else can try to do the work here, but to solve this problem you need to determine why the keys you expect to be present are not.
CodePudding user response:
The true is the example csv data cause the key name of item is ' price ' (which with the space).
So item.get('price') will return default value None because it could not match ' price '.