Functions are organized , Reusable , To achieve oneness , Or code snippets associated with functions .
Function can improve the modularity of application , And code reuse .
Python Many built-in functions are provided , such as print()
, But you can also create your own functions , This is called a user-defined function .
Rules for defining functions :
① Function code block to def Key words start with , Followed by function identifier name and parentheses ()
② Any arguments and arguments passed in must be placed between parentheses , Parentheses can be used to define parameters
③ The first line of the function optionally uses the document string — Used to store function descriptions
④ The function content is colon : start , And indent
⑤ return [ expression ] End function , Optionally return a value to the caller , Without expression return It's equivalent to returning to None.
The syntax is as follows :
def Function name ( parameter list ):
" function _ docstring "
The body of the function
return expression
Example
def prt():
print("*")
print("***")
print("*****")
return 1
a=prt() # Receive return value
print(a)
# Output results
*
***
*****
1
Python Use in return Statement returns results
def add (a, b):
c = a + b
return c
# function add Contained in the return sentence , It means add Function has return value , The return value is a and b Add up .
There are two cases when a function is called :
# Call functions in the same file , Just write the function name below the function
def function(a,b):
print(a+b)
function(1,2)
# result
3
# Call functions from different files , You need to import :from File path impo Function name /*
# for example : I am here 2.py Want to call test The inside of the bag 1.py Function of
--- 1.py Function is :
def function(a,b): # image a,b Such uncertain parameters are generally called formal parameters
print(a+b)
function(1,2) # 1,2 This specific parameter is called an argument
--- 2.py call 1 Medium function function
from test.1 import function
function
# result
3
stay python in , Type belongs to object , Variables have no type :
a=[1,2,3]
a="Python"
// In the above code ,[1,2,3] yes List type ,"Python" yes String type , Variables a There is no type
It's just a reference to an object ( A pointer ), It can point to List Type object , It can also point to String Type object
# Functions with parameters
#a and b Is the parameter of the function , They can receive any two numbers passed in when the function is called
def add(a,b): # Formal parameters 、 Shape parameter
print(a+b)
add(20,30) # The actual parameter 、 Actual parameters
add("qwe","asd")
add(2.3,5.8)
# Output results
50
qweasd
8.1
def add(a,b):
print(a+b)
a+=1
b+=2
c=12
d=22.8
add(c,d)
add(d,d)
print(c,d)
# Output results
34.8
45.6
12 22.8
There are several formal parameter types that can be used when calling a function :
When you call a function , If the default parameter is not transferred to the value , The default value of the parameter will be used ;
If default parameter is passed in a value , The new value passed in will be used
Parameters with default values must be at the end of the parameter list , Otherwise, the program will report an error
Usage scenario of parameter default value : Use when there are few parameters , For example, name
def add(a,b=3): # Formal parameters , Shape parameter
print(a+b)
add(11,30) # The actual parameter , Actual parameters
# Output results
41
If you want the function to be called with more parameters than it is defined , You can use variable length arguments when defining functions
Grammar format
def Function name ([formal_args,] *args, **kwargs):
" function _ docstring "
The body of the function 、
return expression
# With an asterisk (*) Parameters of args Unnamed parameters are stored as tuples ;
# Add ** Parameters of kwargs The named parameters will be stored in the form of a dictionary , It's just like key=value Parameters of .
Example
# The form of tuples
def add(*a):
sum=0
for x in a:
sum+=x
print(sum)
add(1,2,3,4,5,6,7,8,9)
# Output results
45
# Dictionary form
def add(b,**a):
for x in a.items():
print(x)
add(1,a=2,c=3,d=4)
# Output results
('a', 2)
('c', 3)
('d', 4)
use **a This parameter transfer method must be key=value In the form of
Example
# Write function description
def printme( str ):
" Print any incoming strings "
print (str)
return
# call printme function , Without parameters, an error will be reported
printme()
# Output results
Traceback (most recent call last):
File "test.py", line 10, in <module>
printme()
TypeError: printme() missing 1 required positional argument: 'str'
Keyword parameters are closely related to function calls , Function calls use key arguments to determine the value of the arguments passed in
Using keyword parameters allows the order of parameters when a function is called to be different from when it is declared , because Python The interpreter can match parameter values with parameter names
In function printme() Call with parameter name , Examples are as follows
# Write function description
def printme( str ):
" Print any incoming strings "
print (str)
return
# call printme function
printme( str = " Hello China ")
The output of the above example :
Hello China
def add(a,b): #a and b They're all tuples
sum=0
for x in a:
sum+=x
for y in b:
sum+=y
print(sum)
add((1,2,3),b=(4,5,6))
# Output results
21
def add(a,b):
for x in range(len(a)):
a[x]+=10
c=[1,2,3] # The address of the collection type , Is the value of the variable , As long as the address remains the same , Any element in the address can be changed
add(c,b=(4,5,6))
print(c)
# Output results
[11, 12, 13]
No parameter , Functions with no return value , Mainly focus on his process
def print_menu():
print('--------------------------')
print(' xx Shabu Shabu Ordering system ')
print(' 1. Mutton Shabu Shabu ')
print(' 2. Beef Shabu Shabu ')
print(' 3. Pork Shabu Shabu ')
print('--------------------------')
print_menu()
# Output results
--------------------------
xx Shabu Shabu Ordering system
1. Mutton Shabu Shabu
2. Beef Shabu Shabu
3. Pork Shabu Shabu
--------------------------
No parameter , Function with return value
# Get the temperature
def get_temperature():
# For the sake of simplicity , First, the simulation returns a data
return 24
temperature = get_temperature()
print(' The current temperature is :',temperature)
# Output results
The current temperature is : 24
With parameters , Functions with no return value
bash
def test(num_one, num_two):
result = num_one + num_two
print(' The calculation result is :%d' % result)
# The output result has no return value
With parameters , Function with return value
Functions with parameters and return values , Such functions can be used in scenarios such as data processing and the need to process results
def num_4(x, y): # There are parameters and return values
result_4 = x + y
return result_4
n = num_4(3, 8)
print(n)
# Output results
11
Example
def nb():
print("nbsl")
print("awsl")
print("finish")
def nba():
print("nba is start")
nb()
print("nba is close")
nba()
# Output results
nba is start
nbsl
awsl
finish
nba is close
def nb(name,age):
print(" My name is "+name+", today %i Year old " %age)
return 1
def nba(name,age,gender):
a=nb(name,age)
if a==1:
print("gender:",gender)
return 2
b=nba(" forceup ",18,"female")
print(b)
# Output results
My name is a Xiang , today 18 Year old
gender: female
2
Python in , Program variables are not accessible anywhere , Access depends on where the variable is assigned .
Demonstrate the scope of a function
name="dawang"
def test(name):
def t(name): #name——》xiaowang
name=" King "
print("t Of name",name)
t(" Xiao Wang ") # Xiao Wang here has been reassigned
print("test Of name",name)
test("xiaowang")
print(name)
# Output results
t Of name King
test Of name xiaowang
dawang
L(Local): Region within a function , Including local variables and parameters .
E(Enclosing): Nested function area outside , Common is the outer function of closure function .
G(Global): Global scope .
B(Built-in): Built in scope .
global Keyword is used to use global variables in functions or other local scopes
Use nonlocal Keyword can modify variables in the nested scope in a nested function
The interior of a function can call other functions . however , If a function does not call other functions inside , It's what I say , This function is a recursive function .
Invoke the sample
b=0
def a(b):
b+=1
if b<=10:
print(" The first %i The second method call starts " %b)
a(b)
print(" The first %i The method call ends " %b)
a(b)
# Output results
The first 1 The second method call starts
The first 2 The second method call starts
The first 3 The second method call starts
The first 4 The second method call starts
The first 5 The second method call starts
The first 6 The second method call starts
The first 7 The second method call starts
The first 8 The second method call starts
The first 9 The second method call starts
The first 10 The second method call starts
The first 11 The method call ends
The first 10 The method call ends
The first 9 The method call ends
The first 8 The method call ends
The first 7 The method call ends
The first 6 The method call ends
The first 5 The method call ends
The first 4 The method call ends
The first 3 The method call ends
The first 2 The method call ends
The first 1 The method call ends
n=int(input(" Please enter an integer :"))
result=1
def jiecheng(num,result):
result*=num
num -= 1
if(num>=1):
jiecheng(num, result)
if num==0:
print(n," The factorial is :",result)
jiecheng(n,result)
# Output results
Please enter an integer :8
8 The factorial is : 40320
lambda [arg1 [,arg2,.....argn]]:expression
#[arg1 [,arg2,...argn]]” Represents the parameter of a function
#“expression” Expression
Example
# Anonymous functions ,lambda Expression to define anonymous functions
sum=lambda a,b:a+b
c=sum(8,7)
print(c)
# Output results
15
---------------------------------------------------------------------------------------------
# Equivalent to the following operation
def add(a,b):return a+b
d=add(8,7)
print(d)
# Output results
15
Add
Compared with ordinary functions , Anonymous functions have many differences :
① Ordinary functions have names when they are defined , Anonymous functions have no names
② The function body of an ordinary function contains multiple statements , The function body of an anonymous function can only be an expression
③ Ordinary functions can achieve more complex functions , The functions that anonymous functions can realize are relatively simple
stay Python in , There are usually several ways to express time :
① Time stamp
② Formatted time string
③ time tuples (struct_time)
Time stamp
The timestamp indicates from 1970 year 1 month 1 Japan 00:00:00 Start offset in seconds .
import time # introduce time modular
ticks = time.time()
print(" The current timestamp is :", ticks)
import time
print(time.strftime("%Y-%m-%d %H:%M:%S"))
# Output results
2022-01-20 00:55:51
The main functions that return time tuples are gmtime()、localtime() and strptime(). Time tuples share 9 A field
- time.altzone
The number of offset seconds to return to the daylight saving time area in Western Greenwich . If the region is east of Greenwich, it will return a negative value ( Western Europe , Including the United Kingdom ).
Enable region for daylight saving time to use .
- time.asctime([tupletime])
Accepts a time tuple and returns a form of "Tue Dec 11 18:07:14 2008"(2008 year 12 month 11 Japan Tuesday 18 when 07 branch 14 second ) Of 24 Character string .
- time.clock( )3.8 Version obsolescence time.process_time()
The number of seconds in floating-point count to return the current CPU Time . Used to measure the time consumption of different programs , Than time.time() More useful .
- time.ctime([secs])
The effect is equivalent to asctime(localtime(secs)), No incoming secs The parameter is equivalent to asctime().
- time.gmtime([secs])
Receive time dropout (1970 year 1 month 1 Japan 00:00:00 Floating point seconds after ) And return the time tuple in Greenwich astronomical time .
- time.localtime([secs])
Receive time dropout ( 1970 year 1 month 1 Japan 00:00:00 Floating point seconds after ) And return time tuple under local time .
- time.mktime(tupletime)
Accept time tuple and return time dropout .
- time.sleep(secs)
Delay calling thread ,secs Is the number of seconds .
- time.strftime(fmt[,tupletime])
Receives a time tuple and returns the local time in a readable string , Format by fmt decision .
- time.strptime(str,fmt='%a %b %d %H:%M:%S %Y')
according to fmt The format parses a time string into a time tuple .
- time.time( )
Returns the timestamp of the current time .
- time.tzset()
According to environment variable TZ Reinitialize time related settings .
- time.timezone
Indicates the local time zone ( Daylight saving time not started ) Offset seconds from Greenwich (>0, America ;<=0 Most of Europe , Asia , Africa )
- time.tzname
Contains a pair of strings that vary from case to case , Local time zone name with daylight saving time , And without a name .
Grammar format
calendar.calendar(year,w=2,l=1,c=6)
Returns the year Annual calendar ,3 Month and row , The interval is c.
The daily width interval is w Characters . The length of each line is 21* W+18+2* C.l Is the number of lines per week .
Print calendar
d=calendar.calendar(2022,2,1,6)
print(d)
# Output results
2022
January February March
Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su
1 2 1 2 3 4 5 6 1 2 3 4 5 6
3 4 5 6 7 8 9 7 8 9 10 11 12 13 7 8 9 10 11 12 13
10 11 12 13 14 15 16 14 15 16 17 18 19 20 14 15 16 17 18 19 20
17 18 19 20 21 22 23 21 22 23 24 25 26 27 21 22 23 24 25 26 27
24 25 26 27 28 29 30 28 28 29 30 31
31
April May June
Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su
1 2 3 1 1 2 3 4 5
4 5 6 7 8 9 10 2 3 4 5 6 7 8 6 7 8 9 10 11 12
11 12 13 14 15 16 17 9 10 11 12 13 14 15 13 14 15 16 17 18 19
18 19 20 21 22 23 24 16 17 18 19 20 21 22 20 21 22 23 24 25 26
25 26 27 28 29 30 23 24 25 26 27 28 29 27 28 29 30
30 31
July August September
Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su
1 2 3 1 2 3 4 5 6 7 1 2 3 4
4 5 6 7 8 9 10 8 9 10 11 12 13 14 5 6 7 8 9 10 11
11 12 13 14 15 16 17 15 16 17 18 19 20 21 12 13 14 15 16 17 18
18 19 20 21 22 23 24 22 23 24 25 26 27 28 19 20 21 22 23 24 25
25 26 27 28 29 30 31 29 30 31 26 27 28 29 30
October November December
Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su
1 2 1 2 3 4 5 6 1 2 3 4
3 4 5 6 7 8 9 7 8 9 10 11 12 13 5 6 7 8 9 10 11
10 11 12 13 14 15 16 14 15 16 17 18 19 20 12 13 14 15 16 17 18
17 18 19 20 21 22 23 21 22 23 24 25 26 27 19 20 21 22 23 24 25
24 25 26 27 28 29 30 28 29 30 26 27 28 29 30 31
31
Process finished with exit code 0
Print a calendar for a single month
m=calendar.month(2020,2,2,1)
print(m)
# Output results
February 2020
Mo Tu We Th Fr Sa Su
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29
calendar. firstweekday()
Returns the setting of the start date of the current week . By default , First load calendar Module returns 0, Monday
calendar.isleap(year)
If it's a leap year, return True, Otherwise False.
calendar.leapdays(y1,y2)
return Y1、Y2 The total number of leap years between two years .
calendar.month(year,month,w=2,l=1)
Returns the year year month Monthly calendar , Two line headings , A Monday trip . The daily width interval is w character . The length of each line is 7* w+6.l Is the number of lines per week .
calendar.monthcalendar(year,month)
Returns a nested list of integers . Each sublist load represents an integer for a week .year year month All dates outside the month are set to 0; All dates in the range are represented by the day of the month , from 1 Start .
calendar.monthrange(year,month)
Returns two integers , The first integer is the date code of the day of the month , The second integer is the date code of the month . Day from 0( Monday ) To 6( Sunday ); Month from 1 To 12.
calendar.prcal(year,w=2,l=1,c=6)
amount to print(calendar.calendar(year,w,l,c))
calendar.setfirstweekday(weekday)
Set the start date code of the week . The range of date codes is 0( Monday )~6( Sunday )
calendar.prmonth(year,month,w=2,l=1)
amount to print(calendar.calendar(year,w,l,c))
calendar.timegm(tupletime)
Accept a time tuple , Return to the time of the moment (1970 Floating point seconds after the era )
calendar.weekday(year,month,day)
Returns the date code of a given date . On weekdays 0( Monday )~6( Sunday ); Month is 1(1 month )~ 12(12 month ).
random.random()
import random
# Generate a random number
print("random():", random.random())
# Generate the second random number
print("random():", random.random())
random.uniform(a,b)
import random
print("random:", random.uniform(50, 100))
print("random:", random.uniform(100, 50))
random.randint(a,b)
import random
# Generate a random number N,N The value range of is 12<=N<=20
print(random.randint(12, 20))
# The generated random number is N,N The result is always 20
print(random.randint(20, 20))
# print(random.randint(20, 10))
# The statement is an error statement , Lower limit a Must be less than the on-line b
random.randrange([start], stop[, step])
import random
print(random.randrange(10, 100, 2))
random.choice(sequence)
import random
mylist = ["apple", "banana", "cherry"]
print(random.choice(mylist))
random.shuffle(X[,random])
import random
demo_list = ["python", "is", "powerful", "simpel", "and so on..."]
random.shuffle(demo_list)
print(demo_list)
random.sample(sequence, K)
import random
list_num =[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Definition slice For random in list_num From 3 Elements
slice = random.sample(list_num, 3)
print(slice)
# The original sequence has not changed
print(list_num)