Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function that returns a tuple gives TypeError: 'NoneType' object is not iterable

Tags:

python

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)
like image 908
Nathan Avatar asked Jul 31 '13 15:07

Nathan


People also ask

How do I fix NoneType object is not iterable in Python?

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.

How do you fix TypeError argument of type NoneType is not iterable?

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 .

How do I iterate NoneType in Python?

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.

Why is my function returning NoneType Python?

It means you have not returned anything. You must add a return statement into the function. For example: def fun(a, b):


2 Answers

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)
like image 90
Sukrit Kalra Avatar answered Oct 10 '22 08:10

Sukrit Kalra


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.

like image 20
viraptor Avatar answered Oct 10 '22 08:10

viraptor