【问题标题】:Unclear output from a function [duplicate]函数的输出不清楚[重复]
【发布时间】:2020-05-20 17:54:54
【问题描述】:

我是编码新手,我正在尝试使用这些天学到的工具。我想问的第一件事是为什么当我输入一个数字为 x 时,输出总是“好”。我做错了什么?其次,当我试图把 return 而不是 print 例如return Y 输出为空白,这是为什么呢?

如果有任何不清楚的地方,请告诉我。谢谢。

def championships_won(x):
    if (championships_won == x):
        print("bad")
    else:
        print("good")

x = 5

championships_won(5)

【问题讨论】:

标签: python


【解决方案1】:

总是“好”的原因是您将championships_won(它是函数)与在您的情况下是整数的函数参数进行比较。这将始终为 False,这就是输出始终为“好”的原因。

尝试将您的代码更改为:

def championships_won(x):
    if (x == 5):
        print("bad")
    else:
        print("good")

championships_won(5) # output: bad

其次,输出和返回值是两个不同的东西。除非您打印,否则函数的返回值不会显示为输出。

def championships_won(x):
    if (x == 5):
        return "bad"
    else:
        return "good"

print(championships_won(5)) # output: bad

【讨论】:

  • 这太清楚了!非常感谢,真的很感谢它:)
  • 太棒了!如果对您有帮助,请考虑接受答案。
【解决方案2】:

为什么当我输入一个数字为 x 时,输出总是“好”?

championships_won 是一个函数对象,而不是一个数字。除非x = championships_won,否则championships_won == x 永远不会为真。我不确定你想在那里做什么。

当我尝试使用 return 而不是 print 时,例如return Y 输出为空,这是为什么呢?

因为您没有打印任何内容,并且在 Python 中也不会隐式打印任何内容。如果要打印返回值,只需这样做:

print(championships_won(5))

【讨论】:

  • 明白了,谢谢哥们。我并没有尝试什么特别的东西,我只是想玩弄一些函数来理解它们,这显然我以前没有。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-06
  • 1970-01-01
  • 2022-01-25
  • 2015-06-21
  • 2017-02-09
  • 2016-06-20
相关资源
最近更新 更多