Hello, everyone. I'm Peter.
Recently wrote Python function functions and made some mistakes. This article is to sort out the Python function passing mechanism, the main content contains:
I. The simplest function (no return value, parameters)
def hello_python(): print("hello python!")
hello_python() # Direct call
Output:
hello python!
II. The simplest function (with return value, no parameters)
def hello_python(): data = "hello python!" return data # data is the return value
hello_python()
Output:
'hello python!'
III. With one parameter (no default value)
def hello(data): result = "hello " + data return result
hello("python")
Output:
'hello python'
Pass in another value:
hello("java")
Output:
'hello java'
It is also possible to modify the information of the parameters internally:
def hello_name(name): result = "Hello " + () + "!" return result hello_name("tom")
'Hello Tom!'
hello_name("jack")
'Hello Jack!'
IV. With multiple parameters (no default values)
def information(name, age): data = "I'm calling." + () + ", this year" + str(age) + "Years." return data
information("tom", 23)
"My name is Tom, I'm 23 years old.
information("JACK", 18)
"My name is Jack, I'm 18 years old.
V. Parameter setting defaults (one parameter)
def hello_name(name="Peter"): result = "Hello " + name return result
If the parameter is not given a specific value, the default value is used
hello_name()
'Hello Peter'
Give the parameter an actual value, such as Tom in the following example; this is often referred to as a real parameter
hello_name(name="Tom")
'Hello Tom'
VI. Default values for parameterization (multiple parameters)
def information(name="Peter", age=20): data = "I am." + name + ", this year" + str(age) + "Years." return data
1. Use default values for all:
information()
"I'm Peter, I'm 20 years old.
2. Pass in all the actual values:
information(name="Tom", age=27)
"I'm Tom, I'm 27 years old.
3, only part of the actual value of the parameter is passed in; the default value is used for those not passed in:
information(name="Tom")
"I'm Tom, I'm 20 years old.
information(age=18)
"I'm Peter, I'm 18 years old.
VII. Use of default values for some parameters
Parameters with default values must be placed last; parameters with default values must be placed last
def information(name, age=20): data = "I am." + name + ", this year" + str(age) + "Years." return data
information("Peter") # age defaults to 20
"I'm Peter, I'm 20 years old.
information(name="Peter")
"I'm Peter, I'm 20 years old.
information("Peter", age=18)
"I'm Peter, I'm 18 years old.
The following approach reports an error directly:
information(age=18, "Peter")
File "<ipython-input-26-2d03cd04a05a>", line 1
information(age=18, "Peter")
^
SyntaxError: positional argument follows keyword argument
information(age=18, name="Peter") # age defaults to 20
"I'm Peter, I'm 18 years old.
Focus: In a function you must first list the formal parameters that do not have a default value, and then list the formal parameters that do have a default value:
def information(age=20, name): data = "I am." + name + ", this year" + str(age) + "Years." return data
File "<ipython-input-28-d36363c3194c>", line 1
def information(age=20, name):
^
SyntaxError: non-default argument follows default argument
How do I understand that parameters with default values must be placed at the end?
Here's a custom get_name function that passes in the first, last, and middle names, but not everyone has a middle name:
def get_name(first_name, last_name, middle_name=''): if middle_name: # If a middle name exists name = first_name + middle_name + last_name else: name = first_name + last_name return name
get_name(first_name="Chang.", last_name="Fly.", middle_name='')
'Zhang Fei'
get_name(first_name="Sun.", last_name="Empty.", middle_name='Enlightenment')
'Monkey King'
The result of not passing middle_name is definitely not what we want:
get_name(first_name="Sun.", last_name="Empty.")
'Sun Kong'
VIII. Positional real parameters
def get_information(name, age): data = "I am." + name + ", this year" + str(age) + "Years." return data
get_information("Tom", 20)
"I'm Tom, I'm 20 years old.
get_information("20","Tom") # Be sure to pass the formal parameters in the same order as they were passed #
"I'm 20, and I'm Tom.
The above result is definitely not what we want
IX. Keyword real parameters
When keywords are used to pass real parameters, it has nothing to do with the order:
get_information(name="Tom", age=20)
"I'm Tom, I'm 20 years old.
get_information(age=20, name="Tom")
"I'm Tom, I'm 20 years old.
X. Mixed use of positional and keyword real parameters
get_information("Tom", age=20)
"I'm Tom, I'm 20 years old.
You still have to follow the order in the original function when you use it, or you will report an error:
get_information(age=20,"Tom")
File "<ipython-input-39-bc20bc544493>", line 1
get_information(age=20,"Tom")
^
SyntaxError: positional argument follows keyword argument
XI. Advanced: *args use
Sometimes we realize that we don't know how many arguments a function needs to accept, and this time we can collect any number of arguments through the usage of *args or **kwargs.
Let's start by introducing the use of *args. Suppose we want to make the height of every student in a class in meters, i.e., divide by 100:
def height(*args): data = args return data
height()
By default the function collects an empty tuple:
()
height(178)
When data is passed in, it is represented as a tuple:
(178,)
height(178,189)
(178, 189)
def height(*args): for data in args: # Loop over elements in args print("The height is: {}m".format(data / 100))
height(189,180,167,172) # Call
Height: 1.89m
Height: 1.8m
Height: 1.67m
Height: 1.72m
XII. Advanced:** kwargs use
**kwargs allows variable-length key-value pairs to be passed as arguments to a function.
def information(**kwargs): data = kwargs print(data)
Dictionaries are collected by default:
information(name="Peter")
{'name': 'Peter'}
information(name="Peter", age=23)
{'name': 'Peter', 'age': 23}
def information(**kwargs): for k, v in (): print("{0} == {1}".format(k,v))
information(name="Peter")
name == Peter
information(name="Peter", age=23)
name == Peter
age == 23
information(name="Peter", age=23, height=175)
name == Peter
age == 23
height == 175
XIII. Advanced: *args and formal parameter concatenation
def fun(x, *args): print("x:", x) print("args:", args)
fun(1)
x: 1
args: ()
fun(1,2)
x: 1
args: (2,)
fun(1,2,3,4)
x: 1
args: (2, 3, 4)
fun(1,2,3,4,"Peter")
x: 1
args: (2, 3, 4, 'Peter')
XIV. Advanced: **kwargs and formal parameter concatenation
def fun(x, **kwargs): print("x:", x) print("kwargs:", kwargs)
fun(1)
x: 1
kwargs: {}
fun(1,name="Peter")
x: 1
kwargs: {'name': 'Peter'}
fun(1,name="Peter",age=23)
x: 1
kwargs: {'name': 'Peter', 'age': 23}
XV. Advanced: formal parameter + *args + **kwargs used in conjunction with the
def fun(x, *args, **kwargs): print("x:", x) print("args:", args) print("kwargs:", kwargs)
fun(1)
x: 1
args: ()
kwargs: {}
fun(1,2,3)
x: 1
args: (2, 3)
kwargs: {}
fun(1,name="Peter",age=23)
x: 1
args: ()
kwargs: {'name': 'Peter', 'age': 23}
fun(1,2,3,name="Peter",age=23)
x: 1
args: (2, 3)
kwargs: {'name': 'Peter', 'age': 23}
kwargs = {"name":"Peter","age":23}
fun(1,2,3,**kwargs)
x: 1
args: (2, 3)
kwargs: {'name': 'Peter', 'age': 23}
Above is an article to understand the details of Python's function passing mechanism, more information about Python function passing mechanism, please pay attention to my other related articles!