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

Use of [Python basics] function

編輯:Python

Use of functions

  • One 、 Create and use functions
  • Two 、 The scope of the function
    • (1)、 Global variables
    • (2)、 local variable
  • 3、 ... and 、 Common four types of parameters
  • Four 、 Anonymous functions
  • 5、 ... and 、 Exercises
  • 6、 ... and 、 Recursive function

One 、 Create and use functions

1、 Create and use functions

 Defining a function does not execute
The input to a function is called an argument , The output of the function is called the return value
Shape parameter : Formal parameters , Not the real value ( Parameters when defining a function , for example num1,num2)
Actual parameters : Actual parameters , It's the real value ( Parameters when calling the function , for example 30,80)
def get_max(num1,num2): Defined function
result = num1 if num1 > num2 else num2
return result
max_num = get_max(30,80) Using functions
print(max_num)
# result 
80

Two 、 The scope of the function

(1)、 Global variables

Variables that are globally valid

name = 'admin'
def login():
print(name)
login()
# result 
admin

(2)、 local variable

1、 local variable
Locally effective variables , Variables within a function

def logout():
age = 19 there age Variables are local
logout()
print(age) No output
# result 
NameError: name 'age' is not defined

2、 Modifying global variables within a function

 there mongey Global variable
If you want to modify the global variable in the function , Cannot be modified directly .
If you want to modify global variables , Need to use global Declare the modified variable
def hello():
global money Declare global variables
money +=1
print(money)
money = 100
hello()
# result 
101

3、 Add
For variable data types : There is no need to declare global variables in the definition function
For immutable data types : You need to declare global variables in the function

def hello():
global money Variable data needs to be declared globally
money +=1
users.append('user1')
print(money,users)
money = 100 Immutable data types
users = [] Variable data type
hello()
# result 
101 ['user1']

3、 ... and 、 Parameter passing
1、 Formal parameters and actual parameters
2、 Parameter check
Set prompt

def get_max(num1:int,num2:int)->int:
return num1 if num1 > num2 else num2
result = get_max('hello',1)
print(result)

After setting the parameters, there will be a check prompt

3、 The one between the three quotation marks will be used as an explanation ,help Can show instructions

def get_max(num1:int,num2:int) -> int:
""" Find the maximum of two numbers param num1: Integer numbers 1 param num2: Integer numbers 2 """
return num1 if num1 > num2 else num2
result = get_max(2,1)
print(result)
print(help(get_max))
# result 
2
Help on function get_max in module __main__:
get_max(num1: int, num2: int) -> int
Find the maximum of two numbers
param num1: Integer numbers 1
param num2: Integer numbers 2

4、 Really judge the parameter type

def get_max(num1:int,num2:int) -> int:
""" Find the maximum of two numbers param num1: Integer numbers 1 param num2: Integer numbers 2 """
if isinstance(num1, int) and isinstance(num2,int): Here is to judge the parameters , Is it an integer
return num1 if num1 > num2 else num2
else:
return 0
result = get_max(2,30.1)
print(result)
# result 
0 It's not an integer , So return as else Value 0

3、 ... and 、 Common four types of parameters

1、 Required parameters
The required parameters in the code are arguments 2,30

def get_max(num1: int, num2: int) -> int:
return num1 if num1 > num2 else num2
result = get_max(2, 30)
print(result)
print(help(get_max))
def pow(x, y=2):
return x ** y

2、 Default parameters
The default parameter here is the formal parameter y=2

def pow(x, y=2):
return x ** y
result = pow(3) # here x=3,y Using default parameters y=2
print(result)
result = pow(2,4) # here x=2, Changing the default parameters makes y=4
print(result)
# result 
9
16

3、 Variable parameters
The countability of parameters will change , It can be transmitted 0,1,2,3,…n Parameters
args=arguments
Its type is tuple

def my_sum(*args):
print(args)
my_sum(1,2,3)
my_sum(1,2,4,5,6,)
my_sum(1)
my_sum()
# result 
(1, 2, 3)
(1, 2, 4, 5, 6)
(1,)
()

In this way, multiple parameters can be calculated

def my_sum(*args):
return sum(args)
result=my_sum(1,2,3)
print(result)
# result 
6

4、 Key parameters :
It can deliver key and value
**kwargs Can be stored in a dictionary

def enroll(name,age=18,**kwargs):
print(f""" Admission information 1. full name :{
name} 2. Age :{
age} 3. other :{
kwargs} """
)
enroll(' Zhang San ',country='china',english='GRE',sport=[' Basketball '])
# result 
Admission information
1. full name : Zhang San
2. Age :18
3. other :{
'country': 'china', 'english': 'GRE', 'sport': [' Basketball ']}

Four 、 Anonymous functions

Anonymous functions refer to a class of functions or subroutines that do not need to define identifiers .Python use lambda Syntax defines anonymous functions , Just use an expression without declaring .( The use of def Standard steps for declaring functions )
Example 1

get_max = lambda num1,num2:num1 if num1 > num2 else num2
result=get_max(1,10)
print(result)
# result 
10

Example 2

get_max = lambda x,y=2:x ** y
result=get_max(4)
print(result)
# result 
16

5、 ... and 、 Exercises

Will array [0,7,0,2] Output is [1,2,0,0]
The method of combining algorithm and anonymous function
Their thinking

""" 0 7 0 2 Before ordering 1 0 1 0 Specify the rules :(1 if num==0 else 0) 0 0 1 1 7 2 0 0 After ordering """
nums = [0,7,0,2]
nums.sort(key=lambda num: 1 if num==0 else 0)
print(nums)
# result 
[7, 2, 0, 0]

Put all even numbers first , Behind the odd row

nums = [1,10,2,4,8,17]
nums.sort(key = lambda num: 1 if num%2==1 else 0)
print(nums)
# result 
[10, 2, 4, 8, 1, 17]

6、 ... and 、 Recursive function

1、 The use of recursion
demand : seek n The factorial
Method 1:for loop

res = 1
n = 3 #3!=3*2*1
for i in range(1,n+1):
res = res * i
print(res)

Method 2: recursive
n! = n*(n-1)!=n*(n-1)*(n-2)!

def f(n):
return 1 if n==1 else n*f(n-1)
print(f(5))
# result 
120

2、 Recursively implement the Fibonacci sequence

def fib(n):
if n ==1 or n==2: It's set here n=1,n=2 Time value
return 1
else:
return fib(n-1)+fib(n-2)
print(fib(7))

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