gpt4 book ai didi

python - Python 中奇怪的多个返回值

转载 作者:行者123 更新时间:2023-12-01 05:53:01 26 4
gpt4 key购买 nike

通过 Code Academy 学习 Python 仅 5 天。我对任何其他语言一无所知(对 Ruby 知之甚少!)。

这段代码我做错了什么?

<小时/>

Q: Write a function, by_three, that calls a second function, cube, if a number is evenly divisible by 3 and "False" otherwise. You should then return the result you get from cube. As for cube, that function should return the cube of the number passed from by_three. (Cubing a number is the same as raising it to the third power).

So, for example, by_three should take 9, determine it's evenly divisible by 3, and pass it to cube, who returns 729 (the result of 9**3). If by_three gets 4, however, it should return False and leave it at that.

Lastly, call by_three on 11, 12, and 13 on three separate lines.

答:

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.

最佳答案

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

>>> 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

关于python - Python 中奇怪的多个返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13523652/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com