【问题标题】:How do I run a function in a print statement? Where the function itself contains a print statement如何在打印语句中运行函数?函数本身包含打印语句的位置
【发布时间】:2019-05-18 00:42:39
【问题描述】:

我正在尝试创建一个变量以在多个地方使用以打印一行脚本

我尝试使用它来打印:print(helped),没有用,它给出了您看到的错误。我试过这样做:打印帮助(),给出了一个语法错误

def helped():
     print('''Type
Type
Type''')

weirdness = input('''What function would you like to run?
Type "Help" for possible commands ''')

if weirdness.upper() == "HELP":
    print (helped)

当我在提示时输入“帮助”时,我得到: 你想运行什么功能? 键入“帮助”以获得可能的命令帮助 我想你需要一点帮助 而不是获取打印语句

我该如何解决这个问题,以免发生这种情况?

【问题讨论】:

  • 你必须调用这个函数。 print(helped())

标签: python python-3.x


【解决方案1】:

在 Python 中调用函数时,必须使用括号。所以既然你的函数的名字是helped,你应该这样称呼它:

print( helped() )

无论你的函数是否有参数,你都应该这样做。

附带说明,在 Python 2.6 中,您也可以使用不带括号的 print 函数,如下所示:

print helped()

但 Python 3.x 并非如此

【讨论】:

    【解决方案2】:

    您只需要执行该功能。目前,helped() 函数已定义但未在您的代码中运行。本质上,它从未使用过。现在你使用 print (helped) 并且应该得到一个错误,而你应该 call 函数

    改变

    print(helped)
    

    print(helped())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-08-14
      • 2014-12-27
      • 2020-01-05
      • 2013-05-04
      • 1970-01-01
      • 2014-10-24
      • 1970-01-01
      相关资源
      最近更新 更多