r/pythonhelp • • Jul 13 '22

why sometimes my code doesnt work?

sport_list = ["weight","bike","soccer ball"]

food_list = ["coffee","pasta","tofu"]

import random

while len(sport_list) != 0 or len(food_list) != 0:

lists_list = [sport_list,food_list]

randomed_list = random.choice(lists_list)

if len(randomed_list) == 0:

if lists_list[0] == randomed_list:

randomed_list = lists_list[1]

else:

randomed_list = 0

randomed_product = random.choice(randomed_list)

print(randomed_product)

randomed_list.remove(randomed_product)

it says: Traceback (most recent call last):

File "C:\Users\ohadb\PycharmProjects\pythonProject3\main.py", line 16, in <module>

randomed_product = random.choice(randomed_list)

File "C:\Users\ohadb\AppData\Local\Programs\Python\Python310\lib\random.py", line 378, in choice

return seq[self._randbelow(len(seq))]

TypeError: object of type 'int' has no len()

2 Upvotes

3 comments sorted by

2

u/carcigenicate Jul 13 '22

Think about this line:

randomed_list = 0

Do these lines make sense together?:

randomed_list = 0
randomed_product = random.choice(randomed_list)

1

u/Ok_Minute_1156 Jul 15 '22

Thank you so much. Btw how in the world you programmers can locate such tiny mistakes?

1

u/carcigenicate Jul 15 '22 edited Jul 15 '22

In this particular case, the error indicated that at the time this code runs:

randomed_product = random.choice(randomed_list)

randomed_list must have been a integer (object of type 'int' has no len() means whatever was given to choice was an integer). The key debugging step is then to look back on the previous lines and see why that's the case. Only a line earlier, you assigned an integer to it.

The error message almost always tells you all you need to know. Think about what the error is telling you, and figure out why what it's saying is the case. The slightly difficult thing here is, you have to also realize that it's choice that's calling len, and that seq is randomed_list.