# Global variables
""" Global variables : global Keyword addition Only immutable types need to be added global int float str bool () Mutable types do not need to be added global list dist set() list 、 Dictionaries 、 aggregate local variable : Only inside the function Variable and immutable : variable : list dist set() list 、 Dictionaries 、 aggregate immutable : When changing the value of a variable , Address change , This type is considered immutable : int float str bool () """
# immutable int float str bool ()
a = 1
print(id(a))
a = 2
print(id(a))
a = ''
print(id(a))
a = 'str'
print(id(a))
a = (1, 2, 3)
print(id(a))
a = (1, 2)
print(id(a))
# variable
a = [1, 2, 3]
print(id(a))
a.remove(3)
print(id(a))
print(' Local and global variables '.center(30, '-'))
x = 100
# Local
def pr():
x = 8
y = 10
print(x)
print(y)
# overall situation
def pr2():
print(x)
# Modify global
def pr3():
global x # It must be declared before it can be moved
x = x - 80 # Global variables cannot be easily moved
print(x)
pr()
pr2()
pr3()
pr2()
# local variable
""" Variable parameters *args : A tuple is loaded by default (); It's a container *kwargs argument A star :* Disassembly package Pack : def function (*arg): ----------> The packaging operation will appear pass unpacking :list、tuple、set When a function is called : function (*list)| function (*tuple)| function (*set) print(sm(1, *ram_lst)) # Call plus * unpacking Unpacking process Two stars :** #<class 'dict'> *kwargs:key word Key parameters Keyword parameter assignment is allowed ; As long as it is not a keyword parameter, an error will be reported Only when passing parameters key=value form , Then you can put it in the dictionary Only ** Will be packed """
# multi-parameter : Sum up
def sm(a, *args):
print(type(args)) # args: Is a tuple <class 'tuple'>
return a + sum(args)
print(sm(1, 2, 3, 4, 5))
x, *y, z = 1, 2, 3, 4, 5
print(x, y, z) # The default is to put it in the list :1 [2, 3, 4] 5
# unpacking
x, y, z = (7, 8, 9)
print(x, y, z)
# Unpack first 、 Back pack
x, *y, z = (7, 8, 9, 2, 3, 4, 5) # Unpack first 、 Back pack
print(x, y, z)
# The sum of the elements in the list
ram_lst = [12, 4, 6, 8, 345, 678, 24, 67, 1, 23]
print(sum(ram_lst))
print(sm(1, *ram_lst)) # Call plus * unpacking
print(" Two stars :**".center(30, "—"))
def show_book(**kwargs): # <class 'dict'> # Keyword parameter assignment is allowed ; As long as it is not a keyword parameter, an error will be reported
print(type(kwargs))
print(kwargs)
for k, v in kwargs.items():
print(k, v, sep='->')
# The dictionary is packed
show_book(name=' Zhang San ', age=18, sex=' male ') # Keyword parameter assignment is allowed ; As long as it is not a keyword parameter, an error will be reported
# Dictionary unpacking
book = {
'name': ' Journey to the west ', 'author': ' Cao xueqin ', 'number': 5}
show_book(**book) # unpacking
print(" Single star * And two stars :** All exist ".center(50, "—"))
def show_all_book(*args, **kwargs):
print(type(args))
print(type(kwargs))
print(args) # ()
print(kwargs) # {}
book = {
'name': ' A dream of red mansions ', 'author': ' Cao xueqin '}
show_all_book(' Zhang San ', ' Li Si ', **book)
show_all_book(' Zhang San ', ' Li Si ', **{
'name': ' A dream of red mansions ', 'author': ' Cao xueqin '}) # Only ** Will be packed
print('{}{}{}'.format('AA', 'BB', 'CC'))
print('{name}->{age}'.format(**{
'name': ' Zhang San ', 'age': 18}))
result = '#'.join('A', 'B', 'C')
print(result)
# Parameters : When you call a function , Is the function of passing values to a function
""" No arguments : def Function name () pass Ginseng : def Function name ( Parameters 1, Parameters 2, Parameters 3) The body of the function pass Functions with multiple arguments : Multiple parameters The default value is 、 Key parameters Default parameter :( It belongs to the default parameter ,) def Function name ( Parameters 1, Parameters 2, Parameters 3= value ) pass def Function name ( Parameters 1, Parameters 2,*args, Parameters 3= value ) pass The call may not assign a value to the default value parameter : Function name ( value 1, value 2) Be careful : Defined function : Normal parameters should precede the default parameters correct :def Function name ( Parameters 1, Parameters 2, Parameters 3= value ) error :def Function name ( Parameters 1, Parameters 3= value , Parameters 2) """
# Log in up to three times :retry_num: Retry count , Three times by default
def login(retry_num=3):
error_num = 1
while error_num <= retry_num:
username = input(' Please enter a user name :')
password = input(' Please input a password :')
if 'admin'.__eq__(username) and '1234'.__eq__(password):
return ' Login successful '
else:
if retry_num - error_num > 0:
print(' User name or password error is allowed {} Time , also {} Time '.format(retry_num, retry_num - error_num))
error_num += 1 # Add... Every time you make a mistake 1
else:
break
return ' Too many user name or password errors , Please try again later !'
rst = login(4)
print(rst)
''' seek 1-n Between and ; however n It must be a parameter '''
def sm(n):
return sum(i for i in range(n + 1))
# Sum two numbers
def get_sm(a, b):
if type(a) == type(b) and isinstance(a, int) and isinstance(b, int): # isinstance: Type judgment
return a + b
else:
return " Different types !"
# call
print(sm(100))
print(get_sm(1, 2))
# Borrow books
1. What is a function
# Basic operation of function
import random
""" function : Reuse Define call : def Function name ([ Parameters ,...]): # [] Represents dispensability Code Function name : get_name() Multiple word underline segmentation search() word Code : Encapsulate duplicates Call mechanism :( Function name ) 1、 Load the import memory first 2、 Use must call Be careful : 1. Parameter passing : Type belongs to object , There are different types of objects , Variables have no type : 2. The order of default parameters is fixed , If the order of assignment is not fixed , Keyword parameters are required : Parameter name =value Such as login(name, password='1234') Parameters : Single parameter 、 multi-parameter Shape parameter 、 Actual parameters """
# A function is also a variable
def create_verification_code():
code = ''
while len(code) < 4:
result = random.randint(0, 127)
if ord('a') <= result <= ord('z') or ord('A') <= result <= ord('Z'):
code += chr(result)
elif 0 <= result <= 9:
code += str(result)
print(code)
print(create_verification_code) # <function create_verification_code at 0x00000218317180D8>: A function is also a variable , Allocate memory space
# Verify that the function is available
create_verification_code()
''' Define a login function admin 1234 Enter the user name and password to verify that they are correct '''
# Define a login function
def login(username, password, is_remember=False): # Default parameter
if 'admin'.__eq__(username) and '1234'.__eq__(password):
return ' Login successful '
else:
return ' Wrong username or password , Login failed !'
name = input(' Please enter a user name :')
pwd = input(' Please input a password :')
rst = login(name, pwd)
print(rst)
rst = login(name, password='1234') # Default parameter assignment
print(rst)
# Shape parameter 、 Actual parameters
library = [' Journey to the west ', ' A dream of red mansions ', ' The romance of The Three Kingdoms ', ' Water margin ']
# Add books
def add_book(book_name):
library.append(book_name)
# Print books
def show_book(books):
for book in books:
print(book)
add_book(' Ming and Qing Dynasties ') # Add books
print(show_book(library))
2. Function parameter comments
# Function parameter description
""" Function parameter description : def Function name ( Parameters 1、 Parameters 2、 Parameters 3...): Basic notes ” The comment “ Advanced notes : ”“” Parameter description : :param username: user name :param password: password Return value description : :return: Is login successful “”“ """
def login(username, password):
""" User name password login :param username: user name :param password: password :return: Return to success 、 Failure """
if username == 'admin' and password == '1234':
" Return the business logic after success "
print(" Login successful !")
else:
" Return the business logic after failure "
print(" Login failed !")
login("admin", "1234")
practice
# practice Function documentation comments
""" local variable : Save data temporarily , When the function is called, it is recycled Global variables : outside ,(global) Be careful : Variable homonymy problem , local variable > Global variables """
import datetime
lst = [' Journey to the west ', ' A dream of red mansions ', ' The romance of The Three Kingdoms ', ' Water margin ']
def show_book(books):
return [book for book in books if book == ' The romance of The Three Kingdoms '] # List derivation
print(show_book(lst))
num_lst = [1, 4, 90, 35, 79, 34, 89, 12, 90, 34, 89, 26, 90, 99]
# Delete less than 50
def remove_element():
[num_lst.remove(n) for n in num_lst[::-1] if n < 50] # Cause omission, so reverse delete , That way, even if the subscript change does not affect the overall result
print(num_lst)
remove_element() # Delete less than 50
print(num_lst)
print(' Function use exercise '.center(50, '-'))
''' demand : Login during authentication :is_login Customize a function is_login: Parameters :username 、password The body of the function : Judge whether the user name and password entered by the user are correct , If it is correct, return True, Otherwise return to False Borrow books : Define a function borrow_book Parameters : Title :book_name The body of the function : Determine whether to log in , How to log in, you can borrow books If you are not logged in, you will be prompted : You can't borrow books before you log in '''
# Log in
is_rem = False
def is_login(username, password, is_remember=False):
global is_rem # Global variable name used
if username == 'admin' and password == '1234':
is_rem = is_remember
return True
else:
return False
# Borrow books
def borrow_book(book_name):
if is_rem or login():
print(" Login successful , Successfully borrowed %s!" % book_name)
else:
print(" You can't borrow books without logging in , Please log in !")
n = 3
while n > 0:
if login():
print(" Login successful , You can borrow books !")
else:
n -= 1
print(" user name / Wrong password , You have {} Second try !".format(n))
def login():
name = input(" Please enter a user name :")
pwd = input(" Please input a password :")
is_remember = bool(input(" Remember user name and password (True/False):"))
# Sign in
return is_login(name, pwd, is_remember)
# Borrow books
borrow_book(' A dream of red mansions !') # You need to log in for the first time , Sure is_remember Do not enter or enter True
borrow_book(' Journey to the west !') # There is no need to log in
''' Global variables : Parking Rate : 1 Hours 4 Yuan 、 Calculate parking fee 15 A dollar a minute { License plate :[ Entry time , Time to leave ]} def enter(): # Enter the license plate number with the keyboard pass def go_out(): # Enter the license plate number with the keyboard pass def car_billing(): # charging pass '''
start_time = datetime.datetime.now()
end_time = datetime.datetime.now()
# car_park = [{' shan A1234': [start_time, end_time]}]
car_park = []
def enter():
""" Enter the parking lot : Start billing :return: NONE """
print(" Welcome to xxx The parking lot ".center(30, '-'))
car_num = input(' Enter the license plate number with the keyboard :')
global start_time
start_time = datetime.datetime.now()
print(start_time)
car_info = {
car_num: [start_time, end_time]}
car_park.append(car_info)
print("{} Has entered the parking lot ".format(car_num))
def go_out():
""" Charge for driving :return: Return billing information """
print(" sign out xxx The parking lot ".center(30, '-'))
car_num = input(' Enter the license plate number with the keyboard :')
global end_time
global car_park
global end_time
for car in car_park:
if isinstance(car, dict): # Can replace ( The dictionary defaults to and key Compare ): for car_num in car
# The dictionary defaults to and key Compare
for key in car.keys():
if car_num == key:
end_time = datetime.datetime.now()
car.update({
key: [start_time, end_time]})
print(car_billing(car_num))
def car_billing(car_num):
spend_time = 0
for car in car_park:
if isinstance(car, dict):
car_time = car.get(car_num)
print(car_time)
if isinstance(car_time, list):
print(car_time[1], car_time[0])
spend_time = car_time[1] - (car_time[0])
print("spend_time:", spend_time)
return ' Stop often {}, Total fare {}.'.format(spend_time, spend_time / 60 * 4)
enter()
go_out()
# Anonymous functions + Advanced functions
""" Anonymous function definition : lambda parameter list : Operation expression Any parameter can be accepted , But you can only return the value of one expression Use scenarios : Higher order function ( The argument to one function is another function , Commonly known as higher-order function ) 1. Anonymous functions as parameters 2. Higher order function of system :max min sorted 3. filter( Anonymous function requires that bool type , And bool Type true is filtering ) 4. map: extract 、 Processing data , Compose iterations 5. reduce 6. zip """
from functools import reduce
def su(a):
return a + 1
print(su)
print(su(5))
r = lambda b: b + 1
print(r)
print(r(5))
print(" Anonymous functions : Use scenarios -> Advanced functions ".center(30, "-"))
def test(n):
print("-------test----->", n)
def func(a, f):
print("----func---->", a)
f(a)
func(6, test)
print("--------------------------------------------------")
print("------------- Anonymous functions as parameters ------------")
def func1(a, f):
print("++++++++++", a)
print("=========>", f(a))
func1(5, lambda x: x ** 2) # Anonymous functions are passed as arguments
print("------------- Higher order function of system ------------")
lst = [("tom", 20), ("Tony", 23), ("rose", 30), ("Lily", 10)]
result = max(lst, key=lambda x: x[1])
print(result)
result = min(lst, key=lambda x: x[1])
print(result)
result = sorted(lst, key=lambda x: x[1])
print(result)
result = sorted(lst, key=lambda x: x[1], reverse=True) # From small to small
print(result)
result = filter(lambda x: x[1] > 18, lst) # filter Filter
print(list(result))
result = map(lambda x: x[1] + 1, lst) # map mapping , extracted
print(result)
print(list(result))
result = map(lambda x: x[0].title(), lst) # map mapping , extract , Processed
print(result)
print(list(result))
resu = reduce(lambda x, y: x + y, [1, 2, 3, 4, 5]) # It's an operation
print(resu)
result = zip(lst)
print(result)
# Function return value
""" Parameters : The value is transferred from the outside to the inside Return value : The content in it is transmitted to the outside world def Function name ( Parameter name ): The body of the function return Return value call : notice return Returns the value outward ; As long as you return, you need to accept data Be careful :Python Unique characteristics : Return multiple values : Will return as tuples (a,b) return: You can end the call """
def get_sum(*args):
return sum(args)
print(get_sum(*[1, 1, 2, 3, 4, 5])) # Unpack
lst = [1, 3, 2, 9, 4, 5, 13, 56, 34, 23, 67]
# Find the maximum and minimum : Returns two values : Tuples ()
def get_max_min(num_lst):
return min(num_lst), max(num_lst)
print(get_max_min(lst)) # (1, 9)
a, b = get_max_min(lst)
print(a, b) # (1, 9)
print(' Bubble sort '.center(30,'-'))
# Bubble sort
for i in range(len(lst) - 1):
for j in range(len(lst) - i - 1):
if lst[j] > lst[j + 1]:
lst[j], lst[j + 1] = lst[j + 1], lst[j]
print(" Ascending :", lst)
for i in range(len(lst) - 1):
for j in range(len(lst) - i - 1):
if lst[j] < lst[j + 1]:
lst[j], lst[j + 1] = lst[j + 1], lst[j]
print(" Descending :", lst)
# Recursive function
""" File traversal """
# 1-10 The accumulation of numbers
def count(n):
if n > 0:
n -= 1
else:
return n # Consider ending
return n + count(n)
print(count(10 + 1)) # Find... By recursion 1-10 And
print(count(100 + 1)) # Find... By recursion 1-100 And
print(" Recursively implement the Fibonacci sequence ".center(30, '-'))
# Recursively implement the Fibonacci sequence , And print
def fibonacci(n):
if 0 < n <= 2:
return 1
result = fibonacci(n - 1) + fibonacci(n - 2)
return result
for i in range(1, 10):
print("------------>", fibonacci(i))
# A function closure + nesting
"""" nesting : Be careful : 1. Internal functions can use variables of external functions 2. Internal functions cannot modify variables of external functions ,nonlocal a External function variables can be modified and need to be added to internal functions , add to nolocal Closure :( function 、 The variables are in the following order ) Inner function -------> Global function ---------> Outer functions --------> System function (builtins) Closure has three characteristics : 1. Nested function 2. The inner function references the variables of the outer function 3. The return value is an internal function Use scenarios : Decorator use """
def outer():
a = 100
def inner():
nonlocal a # Reference external function variables
b = 200
b += a
a += b
print(" I am an inner function !", b)
result = locals() # Local variable view , Return... As a dictionary :{'a': 100, 'inner': <function outer.<locals>.inner at 0x00000247463281F8>}
print(result)
print(a)
print(inner) # <function outer.<locals>.inner at 0x0000017531E381F8>
inner() # call
print(a) # a By nonlocal Local function modification
return inner
r = outer() # <function outer.<locals>.inner at 0x00000236F60381F8>
print(r)
print(" Closure ".center(30, '*'))
r() # Call the inner function
# Decorator
""" Decorator : principle : Follow the principle of opening and closing , Without changing the original function , Extended function functions characteristic : 1. journal 、 Permission to check 、 cache 2. Statistics Definition : def aaa(func): def xxx( Parameters ,...): .... func() ... return xxx decorate : @aaa def Primitive function (): pass Generation parameter decorator :*arg,**kwargs The original function has parameters , The decorator must also have parameters *arg: Variable parameters **kwargs: Key parameters Decorator decorated function with return value : The original function has a return value ,wrapper Must have a return value in Re entry decorator : """
def foo():
print("foo")
def func():
print("func")
foo = func # The function name is just a variable , Equivalent to variable assignment , Address change
foo()
print(" Decorator ".center(20, "#"))
def deco_house(fu):
""" 1. Define decorators : Decorate the house :param fu : A decorated quotation :return wrapper : Returns the decorated object The address of ; amount to house_a The address changes before and after decoration amount to house_a = house----- Address pointing has changed ----->house_a = wrapper """
def wrapper():
fu()
print(" Install appliances ----->")
print(" Install bed sofa ----->")
print(" Fine decoration is completed ----->")
return wrapper # Returns the internal function
@deco_house # Will call deco_house function --->house_a = deco_house(house_a)
def house_a():
print(" Rough house A")
@deco_house
def house_b():
print(" Rough house B")
house_a()
house_b()
print(" Parameter decorator ".center(30, '*'))
def de_house(fu):
def wrapper(*args, **kwargs): # wrapper() got an unexpected keyword argument 'name':(name=" Shangri la Hotel ") Modify the add **kwargs
fu(*args, **kwargs) # fu Namely house; Tuple unpacking ( With star splitting tuple ):*args
print(" Install appliances ----->")
print(" Install bed sofa ----->")
print(" Fine decoration is completed ----->")
return wrapper # Returns the internal function
@de_house
def house(address):
print(" The address of the house is :{}, It is a blank room ".format(address))
@de_house
def chang_fang(address, area):
print(" The address of the house is :{}, It is a blank room . The building area is :{} Square meters ".format(address, area))
@de_house
def hotel(name, address, area=40):
print("{} The address of is :{}, It is a blank room . The building area of a single room is :{} Square meters ".format(name, address, area))
house(" Xi'an Bell Tower ")
print("--------------------------")
chang_fang(" Xi'an Yanta District ", 130)
print("------------ Default parameters --------------")
hotel(" All season hotel ", " Xi'an Yanta District ")
print("------------ Specify default parameters --------------")
hotel(" All season hotel ", " Xi'an Yanta District ", 80)
print("---------- Key parameters ----------------")
hotel(name=" All season hotel ", address=" Xi'an Yanta District ", area=80)
print("---------- Key parameters : Change order ----------------")
hotel(address=" Xi'an high tech Zone ", name=" Shangri la Hotel ", area=150)
print(" Decorator decorated function with return value ".center(30, '*'))
def make_house(fu):
def wrapper(*args, **kwargs): # wrapper() got an unexpected keyword argument 'name':(name=" Shangri la Hotel ") Modify the add **kwargs
r = fu(*args, **kwargs) # fu Namely house; Tuple unpacking ( With star splitting tuple ):*args
print(" The estimated decoration cost is :{} element ".format(r))
print(" Install appliances ----->")
print(" Install bed sofa ----->")
print(" Fine decoration is completed ----->")
return r # The original function has a return value ,wrapper Must have a return value in
return wrapper
@make_house
def new_house():
print(" Rough house ....")
return 50000
result = new_house()
print(result)
# Function review
import sys
""" Function return value : return return Returns one or more values , It can also be used alone return keyword return : Indicates that the function ends the call Be similar to break; Yeah, but break Interrupting the current loop will also perform the operations after the loop , and return End function directly , Don't follow return a return a,b ------------>(a,b) Global and local variables Global variables 1. What is a global variable 、 The location of the global variable Global variables can be used directly , But it cannot be modified in the function 2. Global variables are immutable types : It cannot be modified in the function , If you want to modify, you must add global Keyword declaration 3. Global variables are mutable types Function can be modified 4. globals() function : You can view global variables local variable ( function ): 1. The internal definition of the function makes 2. The scope of use is only within the function ; When the function call ends, the variable is recycled ( The life cycle is inside ) 3. Dredging collaterals locals View local variables ----> Dictionaries 4. Internal functions can also be treated as local variables Variable and immutable parameters : Relationship between current value and address : variable : The value has changed , The address hasn't changed ; dict list set immutable : The value has changed The address has also changed ; int str bool tuple float Address reference : Pass an address 1. Ordinary assignment relation : The caller will also have a reference 2. Function parameter What are the function parameter types : Variable or immutable Nested function : Closure ( Decorator ): 1. Must be a nested function 2. Internal functions refer to external function variables 3. The return value is an internal function """
print(globals()) # View global variables : Return to the format Dictionary :1. Global variables of the system 2. Custom global variables
lst = [1, 2, 3]
lst1 = lst
print(sys.getrefcount(lst1)) # Because the call will reference , So the result is 3
# summary
""" function : Scope :LFGB L: local Local local variable F:encloseing nesting G:Global overall situation B:built-in Built in functions Nested function : Closure : 1. Inner function 2. The inner function refers to the variable of the outer function 3. Returns the inner function 4. Function as an argument to the outer function Use decorators : @ Name of decorator def Function name (): pass # Summary function Ordinary function 1. No parameter : def func(): pass 2. With parameters General parameters : def func(a,b): pass Variable parameters : def func(*args,**kwargs): args Single element ; kwargs: Key parameters pass func() 、func(1) 、func(a=1) The default value is : def func(a=1,b=2): pass func(a=100) # Key parameters func(900) # By default a assignment 3. Return value no return value def func(): pass x = func() ------->X=None There is a return value : def func(): return 'a','b' # Return multiple values x = func() ---------> x= ('a','b') Nested function :-------> Closure --------> Decorator 1. Closure : def func(): def wrapper(): pass return wrapper() 2. Decorator : Single Decker : def decorate(func): def wrapper(*args,**kwargs): # With or without parameters pass return wrapper @decorate def house(): pass @decorate() def new_house(a,b): Multi layer decorator : @deco2() @deco1() def func(a,b): pass Decorator with parameters : def outer(a): def decorate(func): def wrapper(*args,**kwargs): pass return wrapper return decorate @outer(10) def house(10): pass @outer(100) def house(10): pass Anonymous functions :lambada function : Return value Recursive function : Call yourself Scope of variable : global nonlocal globals locals LFGB """