【问题标题】:Why is this function returning no output and only working with print?为什么这个函数不返回输出而只使用打印?
【发布时间】:2021-04-14 06:51:21
【问题描述】:
def get_formatted_text(first,last):
  full_name=(f'{first} {last}').title()
  return full_name #only works with print. Why?

get_formatted_text('Dick','Long')

当我执行函数调用时,我在终端中看不到任何输出。它适用于打印功能,但我不明白为什么在返回显示输出时需要打印?

【问题讨论】:

  • 因为return 不是print...不知道你在这里问什么。
  • 好吧,没有print() 将不会打印任何内容。就这么简单。

标签: python function printing return


【解决方案1】:

Return 不会打印该值。它只是'returns'它。当直接在 Python 终端中编码时,它会打印该值,但这是终端的额外功能,而不是 return。在所有其他情况下,需要print 才能输出到终端。

【讨论】:

    【解决方案2】:

    它只是返回值它取决于你对值做什么 如果你返回值,括号 r 也不需要

    def get_formatted_text(first, last):
        full_name = f'{first} {last}'.title()
        return full_name  # only works with print. Why?
    
    
    x = get_formatted_text('Dick', 'Long')
    print(x)
    

    但如果你返回一个值,你甚至可以像这样操作

    def get_formatted_text(first, last):
         full_name = f'{first} {last}'.title()
         return full_name  # only works with print. Why?
    
    
     x = get_formatted_text('Dick', 'Long')
     print(x.lower())
    

    【讨论】:

      【解决方案3】:

      您的return 语句返回标题大小写字符串。它不会在控制台中打印元素。

      获取格式化文本后,您可以根据需要对其进行更新。

      def get_formatted_text(first,last):
        full_name=(f'{first} {last}').title()
        return full_name
      
      formatted_text = get_formatted_text('john','doe')
      print(f"Formatted text with title case: {formatted_text}")
      

      输出:

      Formatted text with title case: John Doe
      

      参考:

      【讨论】:

      • @IsmailHafeez,字符串在 OP 的代码中。之前没有检查。更新了字符串。谢谢。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-13
      • 2021-12-30
      • 2022-10-14
      • 2019-11-23
      相关资源
      最近更新 更多