*Memo:
- My post explains a function (2).
- My post explains parameters and arguments in a function.
-
My post explains the iterable unpacking with
*
and a function (1). -
My post explains the dictionary unpacking with
**
within a dictionary and function. -
My post explains
*args
. -
My post explains
**kwargs
. - My post explains a lambda.
- My post explains a variable assignment.
- My post explains an identifier.
- My post explains naming convention.
A function:
- is the statement which can do a specific task, reusing and reducing code and whose type is
func
. - must have a
def
, identifier,():
and its body code. - can have zero or more parameters.
- can have zero or more return statements.
- can have one or more pass statements, return statements and values to do nothing, returning
None
. - can be assigned a variable, function and class to.
- can be defined a variable, function and class in.
- can be written in one line.
- can be indirectly assigned to a variable and parameter but not directly.
- and parameter name can have letters,
_
, the digits except for the 1st character and can be a reserved soft keyword but cannot start with a digit and cannot be a reserved keyword and should be lower_snake_case.
A function is the statement whose type is func
to do a specific task, reusing and reducing code as shown below:
def func(num1, num2):
return num1+num2
print(func(3, 5))
# 8
print(func(7, 2))
# 9
print(func(1, 4))
# 5
def func(num1, num2):
return num1+num2
print(func)
# <function func at 0x00000197701259E0>
print(type(func))
# <class 'function'>
*Code is more if not using a function.
num1 = 3
num2 = 5
print(num1+num2)
# 8
num1 = 7
num2 = 2
print(num1+num2)
# 9
num1 = 1
num2 = 4
print(num1+num2)
# 5
Zero or more parameters can be set in a function as shown below:
def func():
print("No param")
func()
# No param
def func(p1, p2='p2'):
print(p1, p2)
func('param1')
func(p1='param1')
# param1 p2
func('param1', 'param2')
func('param1', p2='param2')
func(p1='param1', p2='param2')
func(p2='param2', p1='param1')
# param1 param2
def func(p1, /, p2='p2', *, p3='p3'):
print(p1, p2, p3)
func('param1')
# param1 p2 p3
func('param1', 'param2')
func('param1', p2='param2')
# param1 param2 p3
func('param1', p3='param3')
# param1 p2 param3
func('param1', 'param2', p3='param3')
func('param1', p2='param2', p3='param3')
# param1 param2 param3
def func(*args, **kwargs):
print(args, kwargs)
func()
# () {}
func(0, 1)
func(*[0, 1])
# (0, 1) {}
func(A=2, B=3)
func(**{'A':2, 'B':3})
# () {'A': 2, 'B': 3}
func(0, 1, A=2, B=3)
func(*[0, 1], **{'A':2, 'B':3})
# (0, 1) {'A': 2, 'B': 3}
One or more return
statements can be set in a function as shown below:
def func():
return "Hello"
print(func())
# Hello
def func():
return [0, 1, 2]
print(func())
# [0, 1, 2]
def func():
return "Hello"
return [0, 1, 2]
print(func())
# Hello
def func():
return [0, 1, 2]
return "Hello"
print(func())
# [0, 1, 2]
def func():
return
print(func())
# None
Top comments (0)