The function returning the tuple gives a TypeError: the "NoneType" object is not iterable

What does this error mean? I am trying to make a function that returns a tuple. I am sure that I am doing everything 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) 
+4
source share
2 answers

Your code returns None if a != b

Since you have a return inside the while loop, if the while loop never executes, 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 can fix this by returning the default values ​​(since they are different and 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) 
+8
source

Indentation returns 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 - after that they can collide again, since you never loop.

+1
source

Source: https://habr.com/ru/post/1494530/


All Articles