函数

目录


Python中的函数使用 def 来进行声明。Python中的函数可以接受两种类型的参数:普通参数和命名参数(named arguments)。

In [1]: def check_num(num, ignore=False):
   ...:     if ignore:
   ...:         return
   ...:
   ...:     if num < 0:
   ...:         print("num < 0")
   ...:     elif num == 0:
   ...:         print("num == 0")
   ...:     else:
   ...:         print("num > 0")
   ...:

In [2]: check_num()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-2-e2de90bec545> in <module>
----> 1 check_num()

TypeError: check_num() missing 1 required positional argument: 'num'

In [3]: check_num(1)
num > 0

In [4]: check_num(2)
num > 0

In [5]: check_num(2, ignore=True)

In [6]: check_num(2, True)

如果 return 后面不接返回值,那么默认将会返回 None



支付宝和微信赞赏

你的赞赏是我写作的动力😍(支持支付宝和微信)