【问题标题】:Why None as Output? [duplicate]为什么没有作为输出? [复制]
【发布时间】:2019-08-02 23:50:50
【问题描述】:

抱歉,我知道这是一个非常简单的问题。但我不明白为什么我的代码返回 None

def fun(x, y):
    ''' takes an orderd list and an another number
    as input'''

    if y in x:
        return print("it's in the list")
    else:
        return print("number is not in the list")

print(fun([2,3,4,5], 5))

【问题讨论】:

  • 函数print返回None。所以:return "it's in the list"

标签: python python-3.x function return-value


【解决方案1】:

print 是一个在 Python 中不返回任何值的函数。它只在屏幕上向用户打印自己的参数。

这里是修改后的代码:

def fun(x, y):
    '''Takes an ordered list and another number as input'''

    if y in x:
        return "it's in the list"
    else:
        return "number is not in the list"

print(fun([2,3,4,5], 5))

为了更好的可读性,最好在“short”之后使用“long”参数。这是我更惯用的版本,只是为了养成更好的习惯:

def contains(item, sequence):
    '''Check if item contains in sequence'''
    if item in sequence:
        return True
    else:
        return False

print(contains(5, [2,3,4,5]))

【讨论】:

  • 你甚至可以减少它return item in sequence
  • 哇,非常感谢!!没想到这种问题会有这么好的答案!
【解决方案2】:

您打印从函数返回的 print 的返回值。

def fun(x, y):
    ''' takes an orderd list and an another number
    as input'''

    if y in x:
        return print("it's in the list")
    else:
        return print("number is not in the list")

fun([2,3,4,5], 5)

【讨论】:

  • 谢谢!!帮助了很多 ot 更好地理解它:)
猜你喜欢
  • 1970-01-01
  • 2021-07-02
  • 1970-01-01
  • 1970-01-01
  • 2022-09-29
  • 1970-01-01
  • 2014-01-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多