简体   繁体   English

python从函数差异返回的两种方法

[英]python two ways to return from function differences

I would like to know if there are any relevant difference in functions below: 我想知道以下功能是否有任何相关差异:

def function1(n):
    if n%2 == 0:
        return n
    else:
        return "Number " +str(n)+ " is odd."

and

def function2(n):
    if n%2 == 0:
        return n
    else:
        print "Number " +str(n)+ " is odd."
        return

In some online course I noticed that in one task (deffinitely more complex code than that printed above, but I made it simple to show just only a concept) automated grading was returning me an error that function did not exit normally when I used design from function1 and when I changed to design from function2 I got full score. 在一些在线课程中,我注意到在一项任务中(绝对比上面打印的代码复杂得多,但是我只显示了一个简单的概念就很简单),自动评分给我一个错误,当我使用以下设计时函数无法正常退出function1,当我从function2更改为设计时,我得到了满分。 I am really intrested why I could not use function1 as correct design, maybe somebody with more than I expierence will explain a bit and show correct with short explanation. 我真的很奇怪为什么我不能使用function1作为正确的设计,也许我经验丰富的人会稍微解释一下并显示正确。

Your second function if the else is executed will return None where in the first it will return the value of "Number " +str(n)+ " is odd." 您的第二个函数(如果执行else)将返回None ,而在第一个函数中它将返回"Number " +str(n)+ " is odd."的值"Number " +str(n)+ " is odd."

So if to need to use the value in the "Number " +str(n)+ " is odd." 因此,如果需要使用"Number " +str(n)+ " is odd."的值,则"Number " +str(n)+ " is odd." should the else be reached you would not be able to, you would only see it printed. 如果您无法达到其他条件,则只会看到它打印出来。

In [9]: x = function1(11)

In [10]: print x
Number 11 is odd.

In [11]: x = function2(11)
Number 11 is odd.

In [12]: print x
None

In your course the grader was more than likely not calling the functions using print so to see the output you would have to print function1(11) ,it is the same using any ide like pycharm etc.., just calling the function when you just have a return will not show the return value. 在你的课程平地机比可能不会使用打电话功能的详细print所以看到输出,你将不得不print function1(11)它是使用任何相同ide像pycharm等,只需调用函数时,你只是有退货将不会显示退货价值。

Without seeing the more complex code there are too many possibilities but one certain part of just printing is your function will return None which may well be required as a value elsewhere for code to terminate. 在没有看到更复杂的代码的情况下,存在太多的可能性,但是仅打印的一个特定部分就是您的函数将返回None ,这很可能是终止代码所需要的其他值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM