6

这个错误是什么意思?我正在尝试创建一个返回元组的函数。我确定我做错了。任何帮助表示赞赏。

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

2 回答 2

11

您的代码返回Noneif a != b

因为,你return在 while 循环中有语句,如果 while 循环永远不会被执行,Python 会返回默认值,None它不能被分配给new_A, new_B.

>>> 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)
于 2013-07-31T15:21:14.413 回答
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 只会重新生成一次 - 之后它们可能会再次碰撞,因为你永远不会循环。

于 2013-07-31T15:24:38.333 回答