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

Introduction to Python functions (function reference, variable scope, parameter passing, common four types of parameters, anonymous functions, recursive functions)

編輯:Python

One 、 References to functions

# 0. Common built-in functions : max,min,sum, divmod
# Functions must have inputs and outputs .
# max_num = max(1, 2, 3)
# print(max_num)
# 1. How to create functions ? Defined function , The contents of the function do not execute
# The input specialty of a function is called a parameter , The output of the function is called the return value .
# a key :
# - Shape parameter : Formal parameters , Not the real value ( Parameters when defining a function )
# - Actual parameters : The actual parameter , It's the real value ( Parameters when calling the function )
def get_max(num1, num2):
result = num1 if num1 > num2 else num2
return result
# 2. How to call a function ?
max_num = get_max(30, 80)
print(max_num)

Two 、 Scope of variable

First of all, we should understand that Variable data type and Immutable data types

Variable data types are data types that can be added, deleted, or modified , On the contrary, it is an immutable data type .
Variable data type : list (list)、 aggregate (set)、 Dictionaries (dict)
Immutable data types : Tuples (tuple)、 character string (str)、 Numerical form

Next , Understand global and local variables

# 1. Global variables : Globally effective variables . Variables outside the function .
name = 'admin'
def login():
print(name)
login()
# 2. local variable : Locally effective variables . Variables within a function .
def logout():
age = 19
print(age)
logout()
# 3. Modifying global variables within a function .
# 1). money Is it a local variable or a global variable ? Global variables
# 2). If you want to modify the global variable in the function , Cannot be modified directly . Need to use global Keyword declares that the modified variable is a global variable .
# 3). The immutable data type must be used to modify the global variable global Statement , Variable data types do not require .
def hello():
global money
money += 1
users.append('user1')
print(money, users)
money = 100 # Immutable data types
users = [] # Variable data type
hello()

3、 ... and 、 Parameter passing

  1. Formal parameters and actual parameters
  2. Parameter check :isinstance(var, int) Judgment variable var Is it int
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: Maximum
"""
## The above is equivalent to declaring the defined function .
if isinstance(num1, int) and isinstance(num2, int):
return num1 if num1 > num2 else num2
else:
return 0
result = get_max(6.3, 2) ## So even the return value is 0
print(result)

Four 、 Common four types of parameters

1. Required parameters : Parameters that must be passed

def get_max(num1: int, num2: int) -> int:
return num1 if num1 > num2 else num2
result = get_max(20, 30)
print(result)

2. Default parameters : Parameters that can be passed or not

def pow(x, y=2):
return x ** y
result = pow(3) # x=3, y=2, result=9
print(result)
result = pow(2, 4) # x=2,y=4, result=2**4=8
print(result)

3. Variable parameters : The number of parameters will change , It can be transmitted 0,1,2,3,…n

args Is a tuple
args=arguments

def my_sum(*args):
return sum(args)
result = my_sum(4, 5, 6) # 15
print(result)

4. Key parameters : It can deliver key and value

kwargs Store 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’, sports=[‘ Basketball ’, ‘ badminton ’])

5、 ... and 、 Anonymous functions

1. Definition and basic examples of 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 )

Python use lambda Syntax defines anonymous functions , Just use an expression without declaring .( The use of def Standard steps for declaring functions )**

## actually lambda :, The colon is preceded by the value you want to enter , The colon is followed by the value you want to output
pow = lambda x, y=2: x ** y
print(pow(2))
get_max = lambda num1,num2 :num1 if num1 > num2 else num2
print(get_max(1,2))
sumjiang = lambda *args : sum(args)
print(sumjiang(1,2,6))

2. Anonymous function example

 Given an array of integers , All of the 0 Move to the end , Not 0 Items remain unchanged ;
Move on the original array , Do not create new arrays ;
Input : Array records ;0 7 0 2
Output : The contents of the adjusted array ; 7 2 0 0
# nums = [0,7,0,2]
# num = sorted(nums,reverse=True)
# print(num)
## Even numbers come first Odd number after
nums = [0, 7, 0, 2]
num = sorted(nums, key=lambda nums: 0 if nums % 2 == 0 else 1)
print(num)
nums = [0, 7, 0, 2]
a= sorted(nums,key=lambda nums: 1 if nums == 0 else 0)
# nums.sort(key=lambda nums: 1 if nums == 0 else 0)
print(a)

3.sort() and sorted() The difference between

1.sort() yes list Methods , Only list It works , and sorted() It's a built-in function , You can sort all iterable objects ;
sort() When sorting a list, you need to use ,sort() The method is to sort the list in place , It is a direct operation on the original list , Does not return a new list .sort() Methods need to be used alone , If and assignment , Print, etc , The result will return None
2.list Of sort() The method is to operate in situ , No return value , And the built-in function sorted() Method is to return a new list.

sorted() Usage of
grammar :
sorted(iterable, key=None, reverse=False)

Parameters :
iterable – Represents an object that can be iterated , For example, it can be dict.items()、dict.keys() etc. .
key – It's a function , Used to select the elements involved in the comparison .
reverse – Sort rule ,reverse = True Descending , reverse = False Ascending ( Default ).

6、 ... and 、 Recursive function

## leecode Most of the problems of binary trees on Most of them use recursive functions
res = 1
n= input()
for i in range(1,int(n)+1):
res = res*i
print(res)
The following is the use of recursive functions :
# def f(n):
# if n ==1:
# return 1
# else:
# return n*f(n-1)
# print(f(5))

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