为什么没有作为输出? [英] Why None as Output?

查看:62
本文介绍了为什么没有作为输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Sorry I know it's a terribly easy question. But i don't understand why my code returns 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 是一个在Python中不返回任何值的函数.它只会在屏幕上向用户打印自己的参数.

print is a function that doesn't return any value in Python. It only print its own arguments to the user on the screen.

此处是修改后的代码:

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"参数.这是我更惯用的版本,只是为了养成更好的习惯:

For better readability, it is better to use "long" arguments after "short". Here is my more idiomatic version, just to build better habit:

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]))

这篇关于为什么没有作为输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆