Python函数打印无 [英] Python function prints None

查看:137
本文介绍了Python函数打印无的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下练习:


参数weekday为True,如果它是
a weekday,并且参数vacation $如果我们在度假,b $ b是真的。如果不是周日或b $ b我们休假,我们b $ b睡觉。如果我们
睡觉,返回True。


这是我所做的,但第二个打印函数只打印'None'

  def sleep_in(weekday,vacation):
如果(不是工作日或假期):
返回True
$ b $ print(sleep_in(False,False))
print(sleep_in(True,False))
print (sleep_in(False,True))

输出:

  True 
None
True


None ,除非明确地指示其他操作。



在你上面的函数中,你没有考虑星期几是 True 的情况。解释器在没有读取返回语句的情况下到达函数的末尾(因为前提条件为 False ),并返回 None
$ b

编辑

  def sleep_in(weekday,vacation):
return(not weekday or vacation)

你去=)

I have the following exercise:

The parameter weekday is True if it is a weekday, and the parameter vacation is True if we are on vacation. We sleep in if it is not a weekday or we're on vacation. Return True if we sleep in.

Here's what I've done, but the second print function only prints 'None'.

def sleep_in(weekday, vacation):
    if(not weekday or vacation):
        return True

print(sleep_in(False, False))
print(sleep_in(True, False))
print(sleep_in(False, True))

Output:

True
None
True

解决方案

Functions in python return None unless explicitly instructed to do otherwise.

In your function above, you don't take into account the case in which weekday is True. The interpreter reaches the end of the function without reading a return statement (since the condition predecing yours evaluates to False), and returns None.

Edit:

def sleep_in(weekday, vacation):
    return (not weekday or vacation)

There you go =)

这篇关于Python函数打印无的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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