Python中return()和print()有什么区别?

2024-06-25 23:41:07 发布

您现在位置:Python中文网/ 问答频道 /正文

在python中,return()和print()会对以下代码产生不同的影响。有什么区别?为什么?在

def count_wins(teamname):
    wins = 0
    for team in nfl:
        if team[2] == teamname:
            wins +=1
    return wins

def count_wins(teamname):
    wins = 0
    for team in nfl:
        if team[2] == teamname:
            wins +=1
    print wins

nfl = [['2009', '1', 'Pittsburgh Steelers', 'Tennessee Titans'], ['2009', '1', 'Minnesota Vikings', 'Cleveland Browns']]


Tags: 代码inforreturnifdefcountteam
3条回答

print只是打印东西。如果你需要对结果做任何额外的处理,这不是你想要的。在

return从函数返回一个值,以便将其添加到列表、存储在数据库中等。不打印任何内容

可能让您感到困惑的是Python解释器将打印返回值,因此,如果您所做的只是这些,那么它们可能会执行相同的操作。在

例如,假设您需要计算总赢款:

def count_wins(teamname):
    wins = 0
    for team in nfl:
        if team[2] == teamname:
            wins +=1
    return wins

total_wins = 0
for teamname in teamnames:
    # doing stuff with result
    total_wins += count_wins(teamname) 

# now just print the total
print total_wins

^{pr2}$

我猜你是在用这个。在

打印输出给定的任何内容。仅此输出,结果不能供其他函数或操作进一步使用。在

return返回函数的结果。使用此选项可使结果可供其他函数和操作进一步使用。在空闲中,使用返回打印值

示例:

def doso():
return 3+4

>>> doso()
7

现在7可用于任何操作或赋予任何功能

参见:

^{pr2}$

打印和返回是非常无关的。也许你是个新手。 简而言之,“return”用于从被调用的函数返回值/控件。 “打印”输出传递到指定记录器的参数,通常是控制台屏幕。在

你可能想看看: https://docs.python.org/2/tutorial/controlflow.html

同时: Why would you use the return statement in Python?

相关问题 更多 >