Python Function Parameter
December 21, 2024 · 4 min read · Page View:
If you have any questions, feel free to comment below.
This blog will review the function parameter of Python. Mainly about the parameter passing, Keyword and Position Parameter, Anonymous Function, and unit test with assert
.
CH5 Function #
Function Parameter #
Parameter Passing #
Formal and Actual Parameters #
- Formal parameter: parameter in function definition, actually variable name
- Actual parameter: parameter in function call, actually variable value
Position Parameter #
- Assign value to formal parameter according to position order
- Actual parameter and formal parameter must be one-to-one, one cannot be more, one cannot be less
def function(x, y, z):
print(x, y, z)
function(1, 2, 3) # x = 1; y = 2; z = 3
Keyword Parameter #
- Break position limit, directly call name to pass value (formal parameter = actual parameter)
def function(x, y, z):
print(x, y, z)
function(y=1, z=2, x=3) # x = 1; y = 2; z = 3
- Position parameter can be mixed with keyword parameter, position parameter must be placed before keyword parameter
function(1, z=2, y=3)
Default Parameter #
- Assign value to formal parameter in definition stage – the common value of the parameter
- Default parameter must be placed after non-default parameter
- When calling function, the parameter can be omitted
def register(name, age, sex="male"):
print(name, age, sex)
register("timerring", 18)
- Default parameter should be set to immutable type (number, string, tuple)
def function(ls=[]):
print(id(ls))
ls.append(1)
print(id(ls))
print(ls)
function()
# 1759752744328
# 1759752744328
# [1]
function()
# 1759752744328
# 1759752744328
# [1, 1]
As can be seen from the above, the address of the list has not changed. Each operation is performed on the original address list, and the content has changed, so it seems to have a memory function. Because the default parameter is set to a mutable type (list).
def function(ls="Python"):
print(id(ls))
ls += "3.7"
print(id(ls))
print(ls)
function()
# 1759701700656
# 1759754352240
# Python3.7
function()
# 1759701700656
# 1759754353328
# Python3.7
Will not produce “memory function”, each increment to a new address
Variable Length Parameter *args
#
- Don’t know how many parameters will be passed
*args
- This parameter must be placed at the end of the parameter list
def foo(x, y, z, *args):
print(x, y ,z)
print(args)
foo(1, 2, 3, 4, 5, 6) # Extra parameters, packaged and passed to args
# 1 2 3
# (4, 5, 6)
- Unpacking actual parameters
def foo(x, y, z, *args):
print(x, y ,z)
print(args)
foo(1, 2, 3, [4, 5, 6]) # List is packaged as a tuple and assigned to args
# 1 2 3
# ([4, 5, 6],)
foo(1, 2, 3, *[4, 5, 6]) # * unpacks these lists, strings, tuples, or sets
# 1 2 3
# (4, 5, 6)
Variable Length Parameter **kwargs
#
def foo(x, y, z, **kwargs):
print(x, y ,z)
print(kwargs)
foo(1, 2, 3, a=4, b=5, c=6) # Extra parameters, packaged and passed to kwargs in the form of a dictionary
# 1 2 3
# {'a': 4, 'b': 5, 'c': 6}
- Unpacking actual parameters
def foo(x, y, z, **kwargs):
print(x, y ,z)
print(kwargs)
foo(1, 2, 3, **{"a": 4, "b": 5, "c":6})
# 1 2 3
# {'a': 4, 'b': 5, 'c': 6}
Variable Length Parameter Combination #
def foo(*args, **kwargs):
print(args)
print(kwargs)
foo(1, 2, 3, a=4, b=5, c=6)
# (1, 2, 3)
# {'a': 4, 'b': 5, 'c': 6}
Function Body and Variable Scope #
- Function body is a piece of code that will only be executed when the function is called, and the code structure is no different from other code
- Local variable – only defined and used within the function body
- Global variable – all variables defined outside are global variables, and global variables can be used directly within the function body
- Define global variable in function body through
global
def multipy(x, y):
global z
z = x*y
return z
print(multipy(2, 9))
# 18
print(z)
# 18
Return Value #
Single Return Value #
def foo(x):
return x**2
Multiple Return Values – in the form of a tuple #
def foo(x):
return 1, x, x**2, x**3 # Comma separated, packaged and returned
print(foo(3))
# (1, 3, 9, 27)
a, b , c, d = foo(3) # Unpacking assignment
print(a) # 1
print(b) # 3
print(c) # 9
print(d) # 27
No return statement default is None #
Suggestions #
- Function and parameter naming:A combination of lowercase letters and underscores.
- Should include a brief description of the function’s functionality, followed by the function definition
def foo():
# This function is used to...
pass
- Leave two lines before and after the function definition
def f1():
pass
# Leave two lines
def f2():
pass
- Default parameter assignment does not require spaces on both sides
Unit Test with assert
– Assertion
#
- assert expression
- Trigger exception when expression result is false
assert game_over(21, 8) == False
---------------------------------------------------------------------------
AssertionError Traceback (most recent call last)
<ipython-input-42-88b651626036> in <module>
----> 4 assert game_over(21, 8) == False
AssertionError:
Anonymous Function #
The most suitable use of anonymous functions is with key = lambda Ensemble: Function body
, especially when paired with sort()
sorted()
- Sort
sort()
sorted()
ls = [(93, 88), (79, 100), (86, 71), (85, 85), (76, 94)]
ls.sort(key = lambda x: x[1])# Sort by the second data of each tuple
ls
# [(86, 71), (85, 85), (93, 88), (76, 94), (79, 100)]
ls = [(93, 88), (79, 100), (86, 71), (85, 85), (76, 94)]
temp = sorted(ls, key = lambda x: x[0]+x[1], reverse=True)# Get descending sort
temp
# [(93, 88), (79, 100), (85, 85), (76, 94), (86, 71)]
max()
min()
ls = [(93, 88), (79, 100), (86, 71), (85, 85), (76, 94)]
n = max(ls, key = lambda x: x[1])
n
# (79, 100)
Related readings
- Python Control Structure
- Python Composite Data Type
- Python Basic Data Type
- Python Basic Syntax Elements
If you find this blog useful and want to support my blog, need my skill for something, or have a coffee chat with me, feel free to: