【问题标题】:Weird output from a function that calls from an imported function从导入函数调用的函数的奇怪输出
【发布时间】:2014-03-30 19:51:53
【问题描述】:

我这里有这段代码:

import random
def AI():
    choices = ["rock","paper","scissor"]
    return str(random.choice(choices))
print(AI)

打印出来:

function AI at 0x0000000003527378

而不是rockpaperscissor

当我在 shell 或函数外部执行此操作时,它会正常返回并打印,但不会在函数中。我是 Python 新手,所以这让我很困惑。谢谢

【问题讨论】:

    标签: python function random import


    【解决方案1】:

    你需要在函数后面加上()来调用它:

    print(AI())
    

    请看下面的演示:

    >>> import random
    >>> def AI():
    ...     choices = ["rock","paper","scissor"]
    ...     return str(random.choice(choices))
    ...
    >>> print(AI)
    <function AI at 0x0236CFA8>
    >>> print(AI())
    rock
    >>>
    

    另外,不需要将random.choice(choices) 包裹在str 中。下面的代码可以正常工作:

    return random.choice(choices)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-04
      • 2015-01-27
      • 1970-01-01
      相关资源
      最近更新 更多