这个错误是什么意思?我正在尝试创建一个返回元组的函数。我确定我做错了。任何帮助表示赞赏。
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)
答案 0 :(得分:9)
如果None
,您的代码会返回a != b
。
因为,你在while循环中有return
语句,如果while循环永远不会被执行,Python返回默认值None
,它不能分配给new_A, new_B
。< / p>
>>> print make_them_different(2, 3)
None
>>> print make_them_different(2, 2)
(2, 1)
你可以通过返回默认值来解决这个问题(因为它们不同,这就是你想要做的事情)
def make_them_different(a,b):
while a == b:
a = randint(1,3)
b = randint(1,3)
return (a,b) # Dedented the return line.
演示 -
>>> make_them_different(2, 2)
(3, 2)
>>> make_them_different(2, 3)
(2, 3)
答案 1 :(得分:1)
缩小返回一级:
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)
否则a,b只会重生一次 - 之后它们可能会再次发生碰撞,因为你永远不会循环。