Python中奇怪的多个返回值

时间:2012-11-23 05:41:09

标签: python

进入Python只需5天,通过Code Academy学习。我不懂任何其他语言(对Ruby的知识很少!)。

这段代码我做错了什么?


  

问:编写一个调用第二个函数by_three的函数cube,   如果一个数字可以被3整除,"False"则可以整除。你应该   然后返回从cube获得的结果。至于cube,那个功能   应返回从by_three传递的数字的多维数据集。 (Cubing a   数字与将它提升到第三种力量相同。)

     

因此,例如,by_three应该取9,并确定它是均匀的   可被3整除,并传递给立方体,立方体返回729(结果为   9 ** 3)。但是,如果by_three获得4,则应返回False并离开   就在那。

     

最后,在11,12和13上分三次分别致电by_three

ANS:

def by_three(n):
    orig_num = n
    if (isinstance(orig_num, int) and orig_num%3 == 0 ):
        cube(orig_num)
    else:
        print "False"

def cube(orig_num):
    cube = orig_num**3
    print cube
    return

by_three(11)
by_three(12)
by_three(13)

当我运行上面的代码时,这就是我得到的。为什么这些值以这种方式出现?

False
1728
False
==> None
False
False
1728
Oops, try again.

3 个答案:

答案 0 :(得分:1)

我不能说你为什么会看到奇怪的结果。当我将代码复制到解释器中时,我看到:

>>> def by_three(n):
...     orig_num = n
...     if (isinstance(orig_num, int) and orig_num%3 == 0 ):
...         cube(orig_num)
...     else:
...         print "False"
... 
>>> def cube(orig_num):
...     cube = orig_num**3
...     print cube
...     return
... 
>>> by_three(11)
False
>>> by_three(12)
1728
>>> by_three(13)
False

我认为这个问题比你制作这个问题简单得多。很难说,因为问题写得很差,但这是我的答案:

def by_three(n): return False if n % 3 else cube(n)

def cube(n): return n**3

by_three(11)
by_three(12)
by_three(13)

这就是解释器中的样子:

>>> def by_three(n): return False if n % 3 else cube(n)
... 
>>> def cube(n): return n**3
... 
>>> by_three(11)
False
>>> by_three(12)
1728
>>> by_three(13)
False

答案 1 :(得分:1)

首先,您需要更改cube函数以实际返回cube。您甚至可以简化cube方法,只需返回cube而不存储临时结果: -

def cube(orig_num):
    return orig_num**3   # Just return the cube

然后在你的by_three函数中,而不是打印“False”,你应该返回它。另外,返回value函数返回的cube: -

def by_three(n):
    if (isinstance(n, int) and n % 3 == 0):
        return cube(n)  # Added return here
    else:
        return False  #Changed print to return.

您还可以将此方法简化为single行返回语句。如果要在try-except中传递值,则应使用isinstance块而不是使用function检查实例:

def by_three(n):
    try:
        return cube(n) if n % 3 == 0 else False
    except TypeError, e:
        return False

然后,当您调用该方法时,打印获得的结果: -

print by_three(11)
print by_three(12)
print by_three(13)

答案 2 :(得分:0)

cube方法中,您实际上并未返回任何内容。与返回块中最后一个语句的Ruby不同,您必须明确说明要返回的内容。也没有必要创建价值的防御性副本。此外,您不能重复使用名称cube,否则会破坏您的方法定义。

def cube(orig_num):
    return orig_num ** 3

接下来,您必须返回调用方法中的值。我会把它作为练习留给你 - 不要太难以从这里弄清楚。

第三,你(有点)不需要担心数字是int还是float。虽然浮点数不精确,但值不能完全被3整除。