【问题标题】:What's the difference between return() and print() in Python? [duplicate]Python 中的 return() 和 print() 有什么区别? [复制]
【发布时间】:2015-10-06 19:27:59
【问题描述】:

在 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', '匹兹堡钢人队', '田纳西泰坦队'], ['2009', '1', '明尼苏达维京人队', '克利夫兰布朗队']]

【问题讨论】:

  • 有什么区别?一切。也许会问相似之处是什么。两者是如此无关,以至于要求“差异”毫无意义。也许读一本介绍性的 python 书,应该解释两者。

标签: python


【解决方案1】:

打印和退货很不相关。可能是您不熟悉编码。 简而言之,“return”用于从被调用的函数返回值/控制。 “打印”输出传递给指定记录器的参数,通常是控制台屏幕。

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

还有: Why would you use the return statement in Python?

【讨论】:

    【解决方案2】:

    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
    

    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) 
    

    【讨论】:

      【解决方案3】:

      我猜你正在使用 IDLE

      print 输出给定的任何内容。只是那个输出,结果不能被其他函数或操作进一步使用。

      return 返回函数的结果。使用它可以使结果可供其他功能和操作进一步使用。在 IDLE 中,使用 return 打印值

      例子:

      def doso():
      return 3+4
      
      >>> doso()
      7
      

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

      见:

      doso()+3
      10
      >>> 
      

      【讨论】:

        猜你喜欢
        • 2022-12-14
        • 2022-08-06
        • 1970-01-01
        • 2022-11-14
        • 2016-03-03
        • 1970-01-01
        • 2019-01-16
        相关资源
        最近更新 更多