what is the function
Functions are organized, reusable pieces of code that implement a single function. For example, when we need to implement the function of "printing", we will use print(); when we need to implement the function of "get data length", we will use len(). And "print()" and "len()" are our functions.
define and call functions
define function
Syntax for defining a function: def function name (parameter name) (note: the brackets can be empty, or multiple parameters, and multiple parameters can be separated by commas) automatically detect def function name (parameter 1
,
parameter 2, ... parameter n):
function body
return statement
Once a return statement is encountered inside the function, it will stop executing and return the result. For functions without a return statement, Python will also implicitly add return None at the end, that is, return a None value (return None can be abbreviated as return.)
Call functions
(1) Functions without parameters
are automatically detected
def A():
print('Graduation at the foot of the mountain')
A()
Function call without parameters: Direct function name + parentheses can call (run) the function.
(2) Functions with parameters
In fact, our print statement print() is also a built-in function, and its format is roughly as follows:
Automatic detection
def print('string'):
(print the contents of 'string')
print('string')
After looking at it in the form of the print() function, we will better understand how functions with parameters are called. Here is another example:
automatic detection
def teacher(name):
print(name)
teacher(‘七七’)
Here we define the function teacher with a parameter name. The name here is equivalent to a keyhole, and the teacher is equivalent to a door. If we do not open the hole with a key, we cannot open the door to use the things inside. So in order to open the door of teacher, we use the key 'Qiqi' to successfully open (assign) to name, so that we can use the printing function inside.
Important concepts of functions
default parameters
Default arguments must be placed after positional arguments. If no parameter is passed when the function is called, it will be the default value, but if data is passed to the default parameter when the function is called, the default parameter will be replaced by the new parameter.
automatic detection
def menu(appetizer,course,dessert='Mung bean paste'):
print('An appetizer:'+appetizer)
print('A staple food:'+course)
print('A dessert:'+dessert)
menu ('Plum Peanut', 'Beef Ramen')
#The result is displayed as: Because only two parameters are given when calling, the third parameter is the default value
#一个Appetizer:话梅花生
#One staple food: Beef Ramen
#One dessert: mung bean paste
menu('Plum Peanut','Beef Ramen','Tremella Soup')
#The result is displayed as: because three parameters are given when calling, the third parameter is updated
#一个Appetizer:话梅花生
#A staple food: Beef Ramen
#A dessert: white fungus soup
variable length parameter
An asterisk * followed by the parameter name. It is used when the number of parameters passed here is uncertain, and the data type is tuple (tuple): the writing method is to put the data in parentheses (), its usage is similar to that of the list, the main difference is that in the list The elements of a can be modified at any time, but the elements in a tuple cannot be changed. Like a list, a tuple is an iterable object, which means we can use a for loop to traverse it).
When the default parameter is after the variable-length parameter, if you want to change the default parameter, you need to indicate dessert='white fungus soup', for example:
automatic detection
def menu(appetizer,course,*barbeque,dessert='Mung bean paste'):
print('An appetizer:'+appetizer)
print('A main course:'+course)
print('A dessert:' +dessert)
for i in barbeque:
print('A skewer:'+i)
menu('Plum Peanut','Beef Ramen','Grilled Chicken Wings','Grilled Eggplant','Grilled Corn',dessert= 'Tremella Soup')
#The result is displayed as:
#一个饭香菜:话梅花生
#One main dish: Beef Ramen#One dessert:
white fungus soup#
One grilled skewer: grilled chicken wings
#One grilled skewer: grilled eggplant
#One grilled skewer: grilled corn
When the default parameter is before the variable-length parameter, the parameters are passed in order by default (the default parameter will change), and the remaining parameters are passed to the variable-length parameter.
automatic detection
def menu(appetizer,course,dessert='Mung bean paste',*barbeque):
print('An appetizer:'+appetizer)
print('A main course:'+course)
print('A dessert:' +dessert)
for i in barbeque:
print('A skewer:'+i)
menu('Plum Peanut','Beef Ramen','Tremella Soup','Grilled Chicken Wings','Grilled Eggplant','Grilled corn')
#The result is displayed as:
#一个饭香菜:话梅花生
#One main dish: Beef Ramen#One dessert:
white fungus soup#
One grilled skewer: grilled chicken wings
#One grilled skewer: grilled eggplant
#One grilled skewer: grilled corn
return statement
Our length calculation statement len() is also a built-in function, and its format is roughly as follows:
Automatic detection
def len('content'):
(calculate the length of 'content')
return length value
a='content'
print(len(a))
Here's another example to explain the return statement:
Autodetection
def A():
name = ‘七七’
return name
print(A())
Here, the content defined by our function A assigns the value 'Qiqi' to the variable name, and returns (return) this value. In line 5 of the code, we print this function, because the value name is returned, so 'Qiqi' will be printed '.
Note: After the return statement is executed, the statement below return will not be executed (only seven or seven will be printed here)
automatic detection
def A():
name = 'Qiqi'
return name
print('Cassie')
print(A())
variable scope
local variable
Variables defined inside a function can only be used inside the function (local scope)
auto-detection
def A():
name='Qiqi'
print(name)
The above statement will report an error because name is a variable within the function (that is, a local variable).
global variable
All variables assigned outside the function can be used anywhere in the program (global scope)
auto-detection
teacher = 'Qiqi'
def A():
name='Cassie'
print(teacher)
print(teacher)
A()
After the above statement is executed, "77" will be printed twice, because the variable teacher is a global variable, and the teacher can be printed normally when the function is executed.
global statement
Local variables can be converted to global variables, generally written in the first line of the function body
Automatic detection
def A():
global name
name=‘七七’
A()
print(name)
The above statement converts our local variable name into a global variable, so that we can print name normally externally. (Note: the global statement must be executed only after function A is executed, and the local variable can be converted into a global variable)
error-prone
Try not to use the same name for local variables and global variables to avoid confusion
Automatic detection
sum = 0
def A():
sum = sum + 1
print(sum)
A()
The above code will report an error: "UnboundLocalError: local variable 'sum' referenced before assignment", what is the reason? This is because when we run function A, in the statement sum = sum + 1, the first sum is a local variable in our function, and the second sum, the system cannot tell whether it is a global or a local variable. Let's say I don't know, so if you want to correct it, you need to convert local variables into global variables:
automatic detection
sum = 0
def A():
global sum
sum = sum + 1
print(sum)
A()
function nesting
The result of sum = rent + cost() is sum = rent + variable_cost (the return value of the cost() function). When calling the function at the end, you only need to call sum_cost().
automatic detection
rent = 3000
def cost():
utilities = int(input('Please enter the cost of water and electricity for this month'))
food_cost = int(input('Please enter the cost of ingredients for this month'))
variable_cost = utilities + food_cost
print(' The variable cost of this month is' + str(variable_cost))
return variable_cost
def sum_cost():
sum = rent + cost()#Call the function
print('The total cost of this month is' + str(sum))
sum_cost()
knowledge development
list() function
Data can be converted to a list
Autodetection
a='Qiqi'
a=list(a)
print(a)
The result is: ['7', '7']
reversed() function (the following is only for reference)
The reversed() function can reverse the data and iterate from the back to the front.
After reversed(), the results of the second for loop, list(), tuple(), and join() are all empty. The reason is that b is not a reversed list itself, but a list reverse iterator, so it is directly output The return value of the function will be similar to garbled characters, and after reversed(), the value will only be returned in the first traversal.
The autodetect
parameters are list 1:
a=[1,2,3,4,5]
b=reversed(a)
print(a)
The result is displayed as:
#[1, 2, 3, 4, 5]
print(b)
The result is displayed as:
<listreverseiterator object at 0x06A9E930>
for i in b:# first traverse
print(i)
The result is displayed as:
#5 4 3 2 1
for i in b:#The second traversal is empty
print(i)
The result is displayed as: nothing
The autodetect
parameters are list 2:
a=[1,2,3,4,5]
b=reversed(a)
print(list(b))#Converted to a list for the first time
#The result is displayed as:
#[5,4,3,2,1]
print(list(b))# second time
The result is displayed as:
#[]
autodetection
#arguments are tuples
t=(4,5,6)
tt=reversed(t)
print(t)
The result is displayed as:
#(4, 5, 6)
print(tt)
The result is displayed as:
<reversed object at 0x06A07E50>
print(tuple(tt))
The first conversion to a tuple
results in
(6, 5, 4)
print(tuple(tt))
#The second time is empty
#The result is displayed as ()
autodetection
#argument is a string
s='cba'
ss=reversed(s)
print(s)
#The result is displayed as
'cba'
print(ss)
#The result is displayed as
<reversed object at 0x06A07E70>
print(list(ss))#Converted to a list for the first time
The result is displayed as
['a', 'b', 'c']
print(list(ss))#The second time is empty
#The result is displayed as
[]