程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python functions

編輯:Python

List of articles

  • introduction
  • One 、 Function definition and call
      • 1. Defined function
      • 3. Call function
      • 4. Parameter passing
  • Two 、 Parameters
      • 1. Default parameters
      • 2. Indefinite length parameter
      • 3. Necessary parameters
      • 4. Key parameters
  • 3、 ... and 、 On the types of function parameters
  • Four 、 Four types of functions
  • 5、 ... and 、 Nested use of functions
  • 6、 ... and 、 Scope of variable
      • 1. What is scope
      • 2. Scope classification
      • 3. LEGB principle
      • 4. local variable
      • 5. Global variables
      • 6. global and nonlocal keyword
  • 7、 ... and 、 Recursive functions and anonymous functions
      • 1. Recursive function
      • 2. Anonymous functions
  • 8、 ... and 、 Date time function
      • 1. Time function
      • 2. Calendar function
  • Nine 、 Random number function

introduction

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 .

One 、 Function definition and call

1. 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
  1. The return value of the function

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 .

3. Call function

There are two cases when a function is called :

  • Call... In the current file of the function
  • Call functions in other files
  1. Current file calls :
# 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
  1. Different file calls :
# 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

4. Parameter passing

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
  • If you want to define a function that can calculate the sum of any two numbers , When we define a function , Let the function receive data , This is the argument to the function
# 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

Two 、 Parameters

There are several formal parameter types that can be used when calling a function :

  1. Required parameters
  2. Key parameters
  3. Default parameters
  4. Indefinite length parameter

1. Default parameters

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

2. Indefinite length parameter

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

3. Necessary parameters

  • The required parameters must be passed into the function in the correct order , The number of calls must be the same as when they were declared
  • call printme() function , You have to pass in a parameter , Otherwise, there will be grammatical errors

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'

4. Key parameters

  • 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

3、 ... and 、 On the types of function parameters

  • Generally, variable length parameters are written after immutable parameters
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]

Four 、 Four types of functions

  • According to the parameters and return values of the function , There are four types of functions :
    ① No parameter , Functions with no return value
    ② No parameter , Function with return value
    ③ With parameters , Functions with no return value
    ④ With parameters , Function with return value

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

5、 ... and 、 Nested use of functions

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

6、 ... and 、 Scope of variable

1. What is scope

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

2. Scope classification

  • The scope of a variable determines which part of the program can access which specific variable name
  • Python There are a total of 4 Kind of , as follows :
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 .

3. LEGB principle

  • Python The middle variable is based on L –> E –> G –>B Search in the order of .
  • Python When looking for variables, you will first look in the scope of the function , If it is not found, it will go to the nested function scope to find , If you can't find it again, go to the global scope to find , Finally, go to the built-in scope to find .

4. local variable

  • So called local variables , It's a variable defined inside a function
  • The scope of a local variable is within a function , It is only valid in the function that defines it , Once the function ends, it disappears .

5. Global variables

  • Variables defined outside functions have global scope
  • Global variables can be accessed throughout the program
  • If the names of global variables and local variables are the same , Then the local variables are accessed first in the function

6. global and nonlocal keyword

  • 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

7、 ... and 、 Recursive functions and anonymous functions

1. Recursive 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
  • Use recursion to realize factorial calculation
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

2. Anonymous functions

  • Anonymous functions are functions without names , That is, no longer use def Function defined by statement .
  • If you want to define an anonymous function , You need to use lambda keyword .
  • The definition format of anonymous functions is as follows :
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

8、 ... and 、 Date time function

1. Time function

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)
  • Formatted time string
  • We can use time Modular strftime Method to format the date
import time
print(time.strftime("%Y-%m-%d %H:%M:%S"))
# Output results 
2022-01-20 00:55:51
Format symbol explain %y Two digit year representation (00~99)%Y Four digit year representation (000~9999%m month (01~12)%d One day in the month %H24 Hours in hours (0~23)%l12 Hours in hours (01~12)%M Minutes (00~59)%S second (00~59)
  • time tuples

The main functions that return time tuples are gmtime()、localtime() and strptime(). Time tuples share 9 A field

Serial number Field value 0tm_year20081tm_mon1 To 122tm_mday1 To 313tm_hour0 To 234tm_min0 To 595tm_sec0 To 616tm_wday0 To 67tm_yday1 To 3668tm_isdst-1,0,1,-1 It's the flag that decides if it's daylight time
- 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 .

2. Calendar function

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 function
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 ).

Nine 、 Random number function

  • random.random()
  • return 0 And 1 Between random floating-point numbers N, The scope is 0<=N<1.0.
import random
# Generate a random number 
print("random():", random.random())
# Generate the second random number 
print("random():", random.random())
  • random.uniform(a,b)
  • return a And b Between random floating-point numbers N, The scope is [a,b]. If a The value is less than b Value , Then the generated random floating-point number N The value range of is a<=N<=b; If a The value is greater than b Value , Then the generated random floating-point number N The value range of is b<=N<=a.
import random
print("random:", random.uniform(50, 100))
print("random:", random.uniform(100, 50))
  • random.randint(a,b)
  • Returns a random integer N,N The value range of is a<=N<=b. It should be noted that ,a and b The value of must be an integer , also a The value of must be less than b Value .
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])
  • Returns a random number in the specified increasing cardinality set , The default value of cardinality is 1. among ,start Parameter is used to specify the starting value in the range , It is included in the scope ;end Parameter is used to specify the end value of the range . It is not included in the scope ;sep These parameters must be integers .
import random
print(random.randrange(10, 100, 2))
  • random.choice(sequence)
  • from sequence Returns a random number in , among sequence Parameters can be lists 、 Tuples or strings . if sequence It's empty , Will trigger IndexError abnormal .
import random
mylist = ["apple", "banana", "cherry"]
print(random.choice(mylist))
  • random.shuffle(X[,random])
  • Used to disorganize the elements in the list , Be commonly called “ Shuffle ”.
import random
demo_list = ["python", "is", "powerful", "simpel", "and so on..."]
random.shuffle(demo_list)
print(demo_list)
  • random.sample(sequence, K)
  • Get... Randomly from a specified sequence K Elements returned as a fragment ,sample Function does not modify the original sequence .
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)

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved