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

wAo*_*wAo -6 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
Run Code Online (Sandbox Code Playgroud)

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

Joh*_*ooy 6

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
Run Code Online (Sandbox Code Playgroud)
def count_wins(teamname):
    wins = 0
    for team in nfl:
        if team[2] == teamname:
            wins +=1
    print wins

    for teamname in teamnames:
        # count_wins just returns None, so can't calculate total
        count_wins(teamname) 
Run Code Online (Sandbox Code Playgroud)