What does this error mean? I'm trying to make a function that returns a tuple. I'm sure i'm doing all wrong. Any help is appreciated.
from random import randint
A = randint(1,3)
B = randint(1,3)
def make_them_different(a,b):
while a == b:
a = randint(1,3)
b = randint(1,3)
return (a,b)
new_A, new_B = make_them_different(A,B)
The Python TypeError: NoneType Object Is Not Iterable error can be avoided by checking if a value is None or not before iterating over it. This can help ensure that only objects that have a value are iterated over, which avoids the error.
The Python "TypeError: argument of type 'NoneType' is not iterable" occurs when we use the membership test operators (in and not in) with a None value. To solve the error, correct the assignment of the variable that stores None or check if it doesn't store None .
The TypeError: 'NoneType' object is not iterable error is raised when you try to iterate over an object whose value is equal to None. To solve this error, make sure that any values that you try to iterate over have been assigned an iterable object, like a string or a list.
It means you have not returned anything. You must add a return statement into the function. For example: def fun(a, b):
Your code returns None
if a != b
.
Since, you have the return
statement inside the while loop, if the while loop never gets executed, Python returns the default value of None
which cannot be assigned to new_A, new_B
.
>>> print make_them_different(2, 3)
None
>>> print make_them_different(2, 2)
(2, 1)
You could fix this by returning the default values (since they are different and that's what you intend to do)
def make_them_different(a,b):
while a == b:
a = randint(1,3)
b = randint(1,3)
return (a,b) # Dedented the return line.
Demo -
>>> make_them_different(2, 2)
(3, 2)
>>> make_them_different(2, 3)
(2, 3)
Indent the return one level lower:
from random import randint
A = randint(1,3)
B = randint(1,3)
def make_them_different(a,b):
while a == b:
a = randint(1,3)
b = randint(1,3)
return (a,b)
new_A, new_B = make_them_different(A,B)
Otherwise a,b will be regenerated only once - they may collide again after that, since you're never looping.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With