退货有什么作用?什么都不会回来 [英] What does return do? Nothing is ever returned

查看:65
本文介绍了退货有什么作用?什么都不会回来的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经学习 Python 好几天了.但是,我不明白返回.我从我的教科书和网上阅读了一些解释;他们没有帮助!

I have been learning Python for some days now. However, I do not understand return. I have read several explanations from my textbooks and online; they don't help!

也许有人可以用简单的方式解释返回的作用?我写了几个有用的(对我来说)Python 脚本,但我从来没有用过 return,因为我不知道它的作用.

Maybe someone can explain what return does in a simple way? I have written several useful (for me) Python scripts but I have never used return because I don't know what it does.

您能否提供一个简单示例来说明为什么应该使用 return ?

Could you provide an easy example that shows why return should be used?

它似乎也什么都不做:

def sqrt(n):
    approx = n/2.0
    better = (approx + n/approx)/2.0
    while better != approx:
        approx = better
        better = (approx + n/approx)/2.0
    return approx

sqrt(25)

我的教科书告诉我:尝试以 25 作为参数调用此函数,以确认它返回 5.0."

我知道如何检查的唯一方法是使用打印.但我不知道这是否是他们正在寻找的.问题只是说用 25 调用.它没有说要在代码中添加更多内容以确认它返回 5.0.

The only way I know how to check this is to use print. But I don't know if that is what they are looking for. The question just says to call with 25. It doesn't say to add anything more to the code to confirm that it returns 5.0.

推荐答案

return 从函数返回一个值:

def addseven(n):
    return n + 7

a = 9
b = addseven(a)
print(b)        # should be 16

也可以用来退出函数:

def addseventosix(n):
    if n != 6:
        return
    else:
        return n + 7

然而,即使你在函数中没有 return 语句(或者你在没有指定返回值的情况下使用它),该函数仍然会返回一些东西 - None.

However, even if you don't have a return statement in a function (or you use it without specifying a value to return), the function still returns something - None.

def functionthatisuseless(n):
    n + 7

print(functionthatisuseless(8))        # should output None

有时您可能希望从函数返回多个值.但是,您不能有多个 return 语句 - 控制流在第一个语句之后离开函数,因此它之后的任何内容都不会被执行.在Python中,我们通常使用元组,并且元组解包:

Sometimes you might want to return multiple values from a function. However, you can't have multiple return statements - control flow leaves the function after the first one, so anything after it won't be executed. In Python, we usually use a tuple, and tuple unpacking:

def addsevenandaddeight(n):
    return (n+7, n+8)        # the parentheses aren't necessary, they are just for clarity

seven, eight = addsevenandaddeight(0)
print(seven)        # should be 7
print(eight)        # should be 8

return 语句允许您根据其他函数的结果调用函数:

return statements are what allow you to call functions on results of other functions:

def addseven(n):
    return n+7

def timeseight(n):
    return n*8

print(addseven(timeseight(9))

# what the intepreter is doing (kind of):
# print(addseven(72))    # 72 is what is returned when timeseight is called on 9
# print(79)
# 79

这篇关于退货有什么作用?什么都不会回来的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆