Chap6 list

  • List creation and deletion
  • List query operations
  • Add, delete, and modify list elements
  • Sorting of list elements
  • List derivation

The list of

Why use lists

  • Variables can store one element, while lists are “large containers” that can store more than N elements, making it easy for programs to manipulate the data as a whole
  • Lists are equivalent to arrays in other languages

List creation

  • Use [] for lists, and separate elements with commas
  • You can create a list in either of the following ways
    • Use []->list=[” “,” “,23]
    • Use the built-in function list()->list=list([” zhang Three “,” Li Four “,23])

Features of lists

  • The list elements are sorted in order
  • Index maps unique data
  • Lists can store duplicate data
  • Arbitrary data type obfuscation
  • Dynamically allocate and reclaim memory as needed

Gets the index of the specified element in the list

  • index()
    • If n identical elements exist in the query list, return the index of the first element
    • An error is reported if the queried element does not exist in the list
    • You can also look up within the specified index range
    • There are forward and reverse indexes. The forward index starts from 0, and the reverse index starts from -1

Query operations for list elements

  • Gets multiple elements in a list
    • [start:stop:step]

List =[10,20,30,40,50,60,70,80] print(id(list)) # step Print (list[:3:1]) # step print(list[:3:1]) # step print(list[:3:1]) # step Print (list[:3:-1]) print(list[:3:-1]) print(list[:3:-1]) print(list[:3:-1]) print(list[:3:-1]) print(list[:3:-1])Copy the code
  • Judgment and traversal of list elements
    • Use in and not in to determine if an element exists in the list
    • List element traversal uses for in
List =[10,20,30,40,50,60,70,80] print(10 in list) print(90 not in list) for item in list: print(item)Copy the code
  • Add operations to list elements

List =[10,'hello',30,'world',50] print(id(list)) print(list) List2 =[1,2,3] list.extend(list2) print(list) # Add an element to list.insert(1,'zhaosi') Print (list) # add at least one element to list[2::]=list2; print(list)Copy the code
  • The deletion of a list element

List =,20,30,40,50,60,20,70,80 [10] print (list) # delete an element at a time, repeating deleted first, List. Remove (20) print(list) # list. Remove (8) print(list) # list. List.pop (1) print(list) list.pop() print(list) # list[5::]=[] print(list) # list.clear() Print (list) print(list)Copy the code
  • List element modification operations
    • Assigns a new value to the element of the specified index
    • Assigns a new value to the specified slice
,20,30,40,50,60,20,70,80 list = [10] the element at the specified index of the # is assigned a new value list [3] = 30 print # (list) for the specified section gives a new value list [made] = [100100100] print(list)Copy the code
  • The sorting operation of list elements
    • There are two common ways
      • Call sort(), all elements in the list are sorted in descending order. Reverse =True can be specified to sort the list in descending order
      • Call the built-in sorted() function, which can specify reverse=True for descending sorting. The original list is not changed and a new list object is generated
Call sort() to sort all the elements in the list in descending order. Can specify the reverse = True in descending order print (' -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- ') list = [52,32,12,42,1,100,56,43] Print (list,id(list)) list.sort() print(list,id(list)) list=[52,32,12,42,1,100,56,43] print(list) list.sort(reverse=True) Print (list) # call sorted(reverse=True) The original list do not change the print (" -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- ') list = [52,32,12,42,1,100,56,43] print (list, id (list)) NewList = sorted (list) print (list, id (newList)) list = [52,32,12,42,1,100,56,43] print (list) newList=sorted(list,reverse=True) print(newList)Copy the code
  • List generator

Print (list) =[I *2 for I in range(1,6)] print(list)Copy the code

Chap7 dictionary

  • What is a dictionary
  • How dictionaries work
  • Dictionary creation and deletion
  • Dictionary query operations
  • Add, delete, and modify dictionary elements
  • Dictionary derivation

What is a dictionary

  • One of Python’s built-in data structures, like a list, is a mutable sequence
  • To store data in key-value pairs, dictionaries are oneA disorderlySequences, keys are immutable sequences
  • Integers and strings are immutable sequences, dictionaries and lists are mutable sequences

  • Dictionary diagram

The implementation principle of dictionaries

  • The implementation principle of dictionary is similar to that of dictionary lookup. Dictionary lookup is based on the radical or pinyin to find the corresponding page number. Dictionary in Python is based on the key to find the corresponding position of value, which is efficient because no matter how many key-value pairs there are, the hash value of the key is needed to search

Dictionary creation

  • The most common way: use curly braces
  • Using the dict() built-in function
# using curly braces dic = {' name ':' zhang ', 'age: 56, "gender" : "male",' info ':' Joe barbecue '} print (dic) # using built-in functions dict () Dic2 =dict(name=' dic3 ',age=56,gender=" male ",info=' dic3 ') print(dic2)Copy the code

Common operations for dictionaries

Get the dictionary element

  • There are two ways to get elements in a dictionary:
    • [] values
    • The get () value
  • [] value and get() value difference
    • [] raises keyError if there is no key in the dictionary
    • Get () returns none if the dictionary key does not exist in parentheses. Value can be set to return if the specified key does not exist
# score value [] dic = {' name ':' Joe ', 'age: 56, "gender" : "male",' info ':' Joe barbecue '} print (dic) [' name '] # print (dic) [' phone '] # the get () value Print (di.get ('gender')) print(di.get ('phone',-1))Copy the code

The judgment of the key

Deletion of dictionary elements

  • Format: del dic[‘ key ‘]

New dictionary element

  • Format: dic [key] = value
} print('name' in dic) print('name' in dic) print('name' not in dic Dic ['phone']='13225365215' print(dic Dic. Clear () print(dic)Copy the code

Three methods to get a dictionary diagram

Dic = {' name ':' zhang ', 'age: 56, "gender" : "male",' info ':' Joe barbecue '} # to obtain a list all of the key and switch to print (list (dic) keys ())) # for all the value Print (list(di.items ())) print(di.items ())Copy the code

Traversal of dictionary elements

# using curly braces dic = {' name ':' zhang ', 'age: 56, "gender" : "male",' info ':' Joe barbecue '} for item in dic: print (item, dic (item), dic. Get (item))Copy the code

Features of dictionaries

  • All elements in a dictionary are key-value pairs. Keys are not allowed to be repeated, but values can be repeated
  • The elements in the dictionary are unordered
  • Keys in dictionaries must be immutable objects
  • Dictionaries can also scale dynamically as needed
  • Dictionaries are a huge waste of memory and are space-for-time constructs

Dictionary generation

  • Use the built-in function zip()
    • Use to take an iterable object as an argument, pack the corresponding elements of the object into a tuple, and return a list of those tuples

Item =['name','sge','gender'] prices=[' bigfoot ',52,1] dic={item:price for item,price in zip(items,prices)} print(dic)Copy the code

Chap 8 tuple, set

  • What is a tuple
  • How tuples are created
  • Traversal of tuples
  • What is a set
  • Collection creation
  • Collection of add, delete, change and check operations
  • Set generator

What is a tuple

  • tuples
    • One of python’s built-in data structures, eleven do not change the sequence
  • Immutable sequence and mutable sequence
    • Immutable sequences: strings, tuples
      • Immutable sequences have no add, delete, or change operations
    • Mutable sequences: lists, dictionaries
      • Variable sequence: the object address does not change

How tuples are created

Use (d1) = # (' zhang ', 'bill', 'pockmarked) print (d1) # create parentheses, brackets can be omitted d2 =' zhang ', 'bill', 'mike' print # (d2) use parentheses to create, Print (d4,id(d4),type(d4)) # print(d4,id(d4),type(d4)) # create an empty tuple d5=() print(d5)Copy the code

Why design tuples as immutable sequences?

  • In the multi-task environment, there is no need to lock objects simultaneously, so immutable sequences are used as much as possible in programming
  • Matters needing attention: Objects stored in tuples are references
    • If the object in the tuple itself is immutable, it can no longer refer to other objects

    • If the object in the tuple itself is mutable, the reference to the mutable object is not allowed to change, but the data can change

Traversal of tuples

  • Tuples are iterable, so they can be traversed using for-in
D1: print(item) for item in d1: print(item)Copy the code

What is a set

  • Built-in data structures provided by the Python language
  • Like list dictionaries, these are mutable types of sequences
  • A set is a dictionary with no value

How collections are created

  • Use {} directly
  • Use the built-in function set()
Set () s2=set(range(1,9)) print(s2) print(s2 Print (set([5,2,63,7,56,42])) Print (set((1,1,2,663,5,5,5,9)) print(set('python')) # print(set({5,2,63,7,56,42})) # print(set({5,2,63,7,56,42})) # print(set({5,2,63,7,56,42}) print(set())Copy the code

Operations related to the collection

Judgment operations on collection elements

  • In or not in

New operations for collection elements

  • Call the add() method to add elements one at a time
  • Call the update() method to add at least one element

The deletion of a collection element

  • The remove() method is called to remove the specified element one at a time, raising keyError if the specified element does not exist
  • The discard() method is called to remove the specified element one at a time, without throwing an exception if the specified element does not exist
  • Call the pop() method to remove any element at a time
  • Call the clear() method to clear the collection
S1 ={1,5,9,6,32,15,52} print(1 in s1) print(9 not in s1) Print (s1) print(s1) print(s1) update([666,444,222,333]) print(s1) Print (s1) # s1.remove(999) print(s1) # s1.remove(999) keyerror: S1.discard (333) print(s1) s1.discard(999) print(s1) Delete any element s1.pop() one at a time; s1.pop(); Clear () print(s1) print(s1)Copy the code

Relationships between sets

  • Whether two sets are equal
    • You can use the operators == or! = Judge
  • Whether a set is a subset of another set
    • You can call the method issubset to determine
  • Whether a set is a superset of another set
    • You can call the method isSupperSet to determine
  • Whether two sets have no intersection
    • You can call the method isdisJoint to determine
,20,30,40,50 s1 = {10} s2 = {20,10,40,30,50} s3 = {10, 30} s4 = 60; seven} {print (s1 = = s2) print (s3) issubset (s1)) print(s2.issuperset(s3)) print(s2.isdisjoint(s3)) print(s4.isdisjoint(s3))Copy the code

Mathematical operations on sets

  • Intersection: Use the function intersection() or &
  • The union and set: use function () or |
  • Difference set: Use the function difference() or –
  • Symmetric difference set: use the function symmetric_difference() or ^

Intersection (); s2={10,20,30,40} s2={20,30,40,50} # Using the function the union () or | print (s1) union (s2)) print (s1 | s2) # difference set: Print (s1-s2) print(s1-s2) # symmetric_difference( print(s1.symmetric_difference(s2)) print(s1^s2)Copy the code

Set generator

s1={i*i for i in range(10)}
print(s1)
Copy the code

List, dictionary, tuple, set comparison

Chap9 string

  • The residency mechanism for strings
  • Common operations on strings
  • String comparison
  • Slicing of a string
  • Formatted string
  • String encoding conversion

The residency mechanism for strings

  • String: In Python a string is a primitive data type, an immutable sequence of characters
  • The python resident mechanism only stores a copy of the same and immutable string, and different values are stored in the string resident pool. The Python resident mechanism only stores a copy of the same string, and does not create a new space for subsequent creation of the same string
  • Several cases of the resident mechanism (interaction mode)
    • The length of the string is 0 or 1
    • A string conforming to an identifier (alphanumeric underscore)
    • Strings reside only at compile time, not run time
    • An integer between [-5,256]
  • The intern method in sys forces two strings to point to the same object
  • Pycharm optimizes the string
  • Advantages and disadvantages of the string resident mechanism
    • When you need strings with the same value, you can directly use them from the string pool to avoid frequent creation and destruction, improve efficiency and save memory. Therefore, concatenating strings and modifying strings will affect performance
    • When string concatenation is needed, it is recommended to use STR join method instead of +, because join method calculates the length of all strings first and then copies the object. It is more efficient than + to only new the object once.
>>> a=''
>>> b=''
>>> print(a is b)
True
>>> c='%'
>>> c='%'
>>> d='%'
>>> print(c is d)
True
>>> e='123%'
>>> f='123%'
>>> print(e is f)
False
>>> a='123x_'
>>> b='123x_'
>>> print(a is b)
True
>>> a='abc'
>>> b='a'+'bc'
>>> c='a'.join('bc')
>>> print(a is b)
True
>>> print(a is c)
False
>>> a='-5'
>>> b='-5'
>>> print(a is b)
False
>>> a=-5
>>> b=-5
>>> print(a is b)
True 
Copy the code

Common operations on strings

String query operation

s1='hello,hello'
print(s1.index('lo'))
print(s1.rindex('lo'))
print(s1.find('lo'))
print(s1.rfind('lo'))

# print(s1.index('k')) ValueError
# print(s1.rindex('k')) ValueError


print(s1.find('k'))
print(s1.rfind('ko'))

Copy the code

Case conversion of a string

Print (a,id(a)) print(b,id(b)) c='WORLd' d= c.power () # print(c,id(c)) Print (e,id(e)) print(f,id(f)) I ='HeLLo' j=i.capitalize() # Print (I,id(I)) print(j,id(j)) m=' Hello world good Night 'n= m.tip () # print(m,id(m)) print(n,id(n))Copy the code

Alignment of string contents

S ='hello,python' # center align print(s.enter (20,"#")) # Print (s.enter (10)) # left-aligned print(s.just (20,"*")) Print (s.just (20,"1")) print(s.just (20,"1")) Print (s.fill (20))Copy the code

The split operation of a string

S = "hello world python" s1 = "hello world | | life is too short | I use python" # from left split lis1 = s.s plit () print (lis1) # param1: according to what to separate param2: Maximum number of separated lis2 = s1. The split (" | ", maxsplit = 1) print (lis2) # from the right split lis3 = s.r split () print (lis3) lis4 = s1. Rsplit (" | ", maxsplit = 2) print(lis4)Copy the code

String judgment

Print ("abc_123".isidentifier()) print("abc_123".isidentifier()) print("abc_123".isidentifier()) Print (" zhao forty percent ". Isidentifier ()) print (" -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- ") # all determine whether the specified string by white space characters (carriage return, newline, Isspace () print("\t".isspace()) print("\tabc".isspace()) print(" ".isspace()) Print (" -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- ") # all determine whether the specified string is made up of letters isalpha () print (" ABC ". Isalpha ()) Print (" zhang ". Isalpha ()) print (" abc123 ". Isalpha ()) print (" -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- ") # all determine whether the specified string composed of decimal digits Isdecimal () print("#123".isdecimal()) print("0123".isdecimal()) print("0123".isdecimal()) print("0123".isdecimal()) print("0123 4 ".isdecimal()) Print (" -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- ") # all determine whether the specified string is composed of digital isnumeric () Roman numerals to true print (" 123 ". Isnumeric ()) Print (" 123 four "isnumeric ()) print (" 123 zhang SAN". Isnumeric ()) print (" -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- ") # Isalnum () print("123abn".isalnum()) print("123abn".isalnum()) print("123abn".isalnum()) print("123".isalnum()) Print (" 123 -- -- -- ". Isalnum ())Copy the code

String substitution and merge operations

S1 ="hello python" print(s1.replace("python"," Java ")) s2="hello python python python" # param1:old STR Param2 :new STR param3: maximum number of replacements print(s2.replace("python"," Java ",2)) # string merge s3=["hello"," Java ","python"] print("|".join(s3)) s4="hello" print("*".join(s4))Copy the code

String comparison operations

  • Operators: >,>=,<,<=,==,! =
  • Comparison rule: The first character in two strings is compared first. If they are equal, the next character is compared, and so on. When the characters in two strings are not equal, the comparison result is the comparison result of two strings, and all subsequent characters in two strings are not compared
  • Comparison Principle: When two strings are compared, their ordinal value(original value) is compared. The original value of a specified character can be obtained by calling the built-in function ORD. The built-in function CHR corresponds to the built-in function ORD
  • Note: 'is' compares id,'==' compares value
print("abc"=="abc")
print("abc">"ab")
print("apple">"banana")


print(ord("a"))
print(ord("b"))


print(chr(97))
print(chr(98))



Copy the code

Slicing of a string

  • A string is an immutable type and does not have the ability to add, delete, or modify. Slicing generates a new string
s1='hello,python'

print(s1[:5:])
print(s1[0:5:])
print(s1[0:8:2])
print(s1[::-1])
print(s1[:-6:-1])

Copy the code

Formatted string

# format print(" name,age ") # format print(" name,age ") # format print(" Format (name,age)) # f-string print(f" Print ("%.3f" % 3.14526655) #.3f print("%10.3f" %) #.3f print("%10.3f" % 3.14526655) # 10 represents the total width; Format (3.25566)) # print("{0:.3}". Format (3.25566)) # print("{0:.3}". Print ("{0:10.3}". Format (3.25566)) Print ("{0:.3f}". Format (3.25566)) #.3f print("{0:.3f}". Format (3.25566)) #.3f print("{0:.3f}". Print ("{:.3f}".format(3.25566)) print("{0:10.3f}".format(3.25566)) print("{0:10.3f}". 3f represents the reserved decimal number, while 0 represents the index and can be omittedCopy the code

String encoding and transcoding

  • How to encode and decode
    • Encoding: Convert string to binary data (bytes)
    • Decode: Converts bytes data to a string
Print (s.encode(" utF-8 ")) print(s.encode(" utF-8 ")) print(s.encode(" utF-8 ")) print(s.encode(" utF-8 ") Byte =s.encode("GBK") print(byt.decode ("GBK") byte=s.encode("UTF-8") print(byt.decode ("UTF-8")) byte=s.encode("UTF-8") print(byt.decode ("UTF-8"))Copy the code

Chap10 function

  • Function creation and invocation
  • Function parameter passing
  • The return value of the function
  • The parameter definition of a function
  • Scope of a variable
  • Recursive function

Function creation and invocation

What is a function

  • A function is a piece of code that performs a specific task and function

Why do WE need a function

  • Reuse code
  • Hiding implementation details
  • Provides maintainability
  • Improved readability and debugging

Function creation

Def add(a,b): c=a+b return c sum=add(10,30) print(sum)Copy the code

Function parameter passing

  • Passing arguments to a function call
    • Position the arguments
      • Arguments are passed according to the corresponding position of the parameter
    • Keyword argument
      • Arguments are passed by parameter name
def add(a,b): Return c sum=add(10,30) # 10 Print (sum) sum=add(b=10,a=30) # = print(sum)Copy the code
  • Function call parameter passing memory analysis diagram
    • During a function call, the parameter is passed
      • If the table object is not implemented, changes made in the function body do not affect the value of the argument
      • In the case of a real mutable object, changes in the body of the function affect the value of the argument
def change(arg1,arg2): print('arg1',arg1) print('arg2',arg2) arg1=100 arg2.append(10) print('arg1', arg1) print('arg2', Arg2) return # - If the table object is not implemented, changes in the function body do not affect the value of the argument. N1 =11 n2=[12,53,46] print('n1',n1) print('n2',n2)Copy the code

The return value of the function

  • Some functions do not return a value, and return can be omitted
  • If the return value of the function is one, write the return type directly
  • If the function returns multiple values, the result is a tuple
Def fun(num): odd=[] # even=[] # for I in num: if I %2: odd. Append (I) else: Even. Append (I) return odd,even LST =[30,56,12,43,97,3] print(fun(LST)) Def fun2(): return 'python' print(fun2()) # def fun3(): return 'hello','python','world' print(fun3())Copy the code

The parameter definition of a function

Default value parameter

  • When a function is set, it sets default values for its arguments. Only those that do not match the default values need to be passed as arguments
Def fun1(a,b=10): print(a,b) fun1(20)Copy the code

A variable number of position parameters

  • Variable positional arguments are used when defining functions where the number of positional arguments passed may not be determined in advance
  • Use * to define mutable positional parameters
  • The result is a tuple
Def fun1 (* arg) : print (arg) fun1 (10, 30)Copy the code

A variable number of keyword arguments

  • Variable keyword arguments are used when defining functions where the number of keyword arguments passed may not be determined in advance
  • Use * * to define mutable positional parameters
  • The result is a dictionary
def fun2(**arg):
    print(arg)

fun2(a=10,b=20,c=30)
Copy the code
  • A variable number of positional arguments and a variable number of keyword arguments cannot be defined simultaneously in a function

Summary of function parameters

def fun1(a,b,c,d): Print (" a ", a) print (" b ", b) print (" c ", c) print (" d ", d) return fun1 (10,20,30,40) LST =,22,33,44 [11] fun1 (* LST) # function call, To each element in the list of arguments are converted to position the incoming fun1 (a = 1, b = 2, c = 3 d = 4) dic = {' a ': 111,' b ', 222, 'c' : 333, 'd' : 444} fun1 (dic) * * # function is invoked, Converts the each element in the dictionary to position the arguments passed in print (" -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- ") fun1 (20, 30, c = 50, d = 60) # the location of the first two USES the arguments passed, Def fun2(a,b,*,c,d): def fun2(a,b,*,c,d): print("a", a) print("b", b) print("c", c) print("d", d) return def fun2(a,b,*,c,d,**arg): print("a", a) print("b", b) print("c", c) print("d", d) print("arg", arg) return def fun3(*args,**arg): print("args", args) print("arg", arg) returnCopy the code

Scope of a variable

  • Variable scope
    • The area where program code can access the variable
    • According to the effective range of variables can be divided into
      • Local variable – a variable defined and used within a function, valid only within the function. A local variable is declared with global and becomes a global variable
      • The global variable
        • A variable defined outside of a function that can act both inside and outside the function
def fun1(a): Print (a) print(b) # print(a) def fun2() def fun2(): Print (name) fun2() print(name) # - def fun1() def fun1() def fun1(): global c c=20 print(c) print(c)Copy the code

Recursive function

What is a recursive function

  • A function is called recursive if it calls itself from within the function

Part of a recursive function

  • Recursive calls and recursive abort conditions

Recursive call process

  • Each time the function is recursively called, a stack frame is allocated within the stack
  • Each time the function is executed, the corresponding space is freed

Pros and cons of recursion

  • Advantages: simple ideas and code
  • Disadvantages: Occupy much memory, low efficiency
def fac(n):
    if n==1:
        return 1
    else:
        return n*fac(n-1)

print(fac(6))
Copy the code

Fibonacci numbers

  • The Fibonacci sequence is a sequence of numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34… Mathematically, the Fibonacci sequence is defined recursively as follows: F(0)=0, F(1)=1, F(n)=F(n-1)+F(n-2) (n ≥ 2, n ∈ N*)
def fib(n):
    if n==1:
        return 1
    elif n==2:
        return 1
    else:
        return fib(n-1)+fib(n-2)

print(fib(6))    
Copy the code

chap11 BUG

  • The origin and classification of bugs
  • How different exception types are handled
  • Exception handling mechanism
  • PyCharm debug mode

The origin and classification of bugs

  • Bug origin: omitted here
  • Types of bugs:

Input Is a string, often involving transformations

Exception handling mechanism

  • The structure of multiple except
    • Exceptions are caught in the order of subclass before superclass, and BaseException can be added at the end to avoid missing possible exceptions

Try: a = int(input(' input ')) b = int(input(' input ')) print(a/b) except ZeroDivisionError: Except BaseException: print(' error ')Copy the code
  • try… except.. The else structure
  • An else block is executed if no exception is thrown in the try block, and an except block is executed if an exception is thrown in the try block
Try: a = int(input(' please input first ')) b = int(input(' please input first ')) result= a/b except ZeroDivisionError: Print (' except BaseException ') except BaseException: print(' error ') else: print(result)Copy the code
  • Structure of the try – except – else – finally
    • The finally block is executed regardless of whether an exception has occurred and is often used to release resources requested in the try block

Try: a = int(input(' please input first ')) b = int(input(' please input first ')) result= a/b except ZeroDivisionError: Except BaseException: print(' error ') else: print(result) finally: print(" task completed ")Copy the code
  • Common abnormal

Use of the Traceback module

  • Use the Traceback module to print exception information
import traceback
try:
    print("---------------------------")
    print(2/0)
except :
    traceback.print_exc()
Copy the code

Pyhcharm Debugging of the development environment

  • Breakpoint: the program runs at this point, suspends temporarily, stops to start, at this time can observe the program in detail, but is convenient to make a step by step judgment

Chapter 12 Programming ideas

  • Two big programming ideas
  • Creation of classes and objects
  • Class objects and class attributes
  • Class methods versus static methods

Programming ideas

Classes and objects

  • class
    • Class is an umbrella term for groups of similar things. Can help us quickly understand and judge the nature of things
  • The data type
    • Different data types belong to different classes
    • You can view data types using built-in functions
  • object
    • 100,333,520 are all similar distinct cases contained under the int class, which are technically called instances or objects

The creation of a class

  • Syntax for creating classes:
    • class Student: pass

  • Class composition:
    • Class attribute
    • Instance methods
    • A static method
    • Class method
Def addMethod(self,name,age): Name =name self.age=age # self.name and self.age are called entity attributes and perform an assignment, Print (" I am an instance method ") @staticMethod def deleteMethod(): Print @staticMethod def updateMethod(CLS): Def selectMethod(): print(" out of class, I'm a function ")Copy the code

Object creation

  • Objects are created with instantiations called classes

  • Syntax: Instance name = class name ()

  • Meaning: With an instance, you can call a method in a class

Class Student: def __init__(self,name,age): Def addMethod(self): self.name=name self.age=age # self.name=name self.age=age # self.name=name self.age=age # self.name=name Print () @staticMethod def deleteMethod(): Print @staticMethod def updateMethod(CLS): Print (" @classMethod annotation, StudentA =Student(" bigfoot ",23) # method call -- method 1 studentA.addMethod() studentA.deletemethod () # method call -- method 2 Student. AddMethod (studentA)Copy the code

Class attributes, class methods, static methods

  • Class attributes: Variables outside the methods of a class are called class attributes and are shared by all objects of that class
  • Class methods: methods decorated with @classMethod can be accessed using the class name
  • Class methods: Methods decorated with @staticMethod can be accessed directly using the class name
Class Student: def __init__(self,name,age): Def addMethod(self): self.name=name self.age=age # self.name=name self.age=age # self.name=name self.age=age # self.name=name Print () @staticMethod def deleteMethod(): Print @staticMethod def updateMethod(CLS): Print (" @classMethod annotation, Print (studentA. Local) studentB=Student(" 大 学 ",23) print(studentA. Local) studentB=Student(" 大 学 ",23) Studentb. local=' studentb. local 'print(studentb. local) print(studentb. local) student. local=' studentb. local' print(studentA. # class method call student.updatemethod ()Copy the code

Dynamically bind properties and methods

  • Python is a dynamic language. After an object is created, properties and methods can be bound dynamically
Class Student: def __init__(self,name,age): Def eat(self): self.name=name self.age=age # self.name=name self.age=age # self.name=name self.age=age # self.name=name Print (self.name," eat ") studentA=Student(" 三",23) studentB=Student(" 三",23) studentA=Student(" 三",23) studentb. eat() # Gender =1 print(studentA. Gender) def drink(): print(" ) studentA.drink=drink studentA.drink()Copy the code

Chap13 Object Oriented

  • encapsulation
  • inheritance
  • Methods to rewrite
  • Object class
  • polymorphism
  • Special methods and special properties

Three characteristics of object orientation

  • Encapsulation: Improves program security
    • Wrap data (attributes) and behavior (methods) into class objects. Properties are manipulated inside methods and methods are called outside class objects. This eliminates the need to worry about internal implementation details, thereby isolating complexity
    • There are no special modifiers in PYTHON for the private property of a property. If the property is not intended to be accessed outside the class object, it is preceded by two ‘_’.
Class Car: def __init__(self,carName): self. CarName =carName def start(self): print("....") CarA=Car(" carName ") CarA. Start () # class Student: def __init__(self,name,age): self.name=name self.__age=age def introduce(self): Print (self. Name,self.__age) studentA=Student(" c ",20) studentA. Rule () print(studentA. AttributeError: 'Student' object has no attribute '__age' print(studentA._Student__age) # Access _Student__age outside the classCopy the code
  • Inheritance: Improves code reuse
class Person(object): def __init__(self,name,age): self.name=name self.age=age def introduce(self): Class Student(Person): def __init__(self,name,age,gender): print(self,name,age,gender) Super ().__init__(name,age) self. Gender =gender stu=Student(" bigfoot ",55,1) stu. Introduce () # class A(object): pass class B(object): pass class C(A,B): passCopy the code
  • Methods to rewrite
    • If a subclass is not happy with an attribute or method inherited from Frey, it can rewrite it (the method body) in the subclass
    • A method overridden by a subclass can call the overridden method in its parent class via super().xxx()
class Person(object): def __init__(self,name,age): self.name=name self.age=age def introduce(self): Class Student(Person): def __init__(self,name,age,gender): print(self,name,age,gender): super().__init__(name,age) self.gender=gender def introduce(self): Super ().introduce() print(' gender ',self. Gender) stu=Student(" foot ",55,1) stu.introduce()Copy the code
  • Object class
    • The Object class is the parent of all classes, so all classes have object properties and methods
    • The built-in function dir() can view all properties of a given object
    • Object has a __str__() method that returns a “trace of the Object.” For the built-in function STR () is often used in the print() method to help us see the information about the Object, so we often override __str__()
class Person(object): def __init__(self,name,age): self.name=name self.age=age def __str__(self): Format (self.name,self.age) stu=Person(" bigtoe ",55) print(dir(stu)) print(stu)Copy the code
  • Polymorphism: Improves the extensibility and maintainability of programs
    • To put it simply, polymorphism is to have multiple forms. It refers to: how many times do you not know what type the object referenced by a variable is, but you can still call a method through this variable. During the running process, you can dynamically decide which object method to call according to the type of the object referenced by the variable
  • Static and dynamic languages
    • The difference between static and dynamic languages in polymorphism
      • inheritance
      • Methods to rewrite
      • A superclass reference points to a subclass object
    • The polymorphisms of dynamic languages advocate the “duck type”, when a bird is seen to walk like a duck, swim like a duck, and tuck like a duck, it can be called a duck. In the duck type, you don’t care what the object is, whether it’s a duck or not, you just care what the object does, right
Class Animal(object): def eat(self): def eat(self): print(Animal) class Dog(Animal): def eat(self): print(Animal) Def eat(self): print(self) class Person(object): def eat(self): print(self) def fun(obj): obj.eat() fun(Cat()) fun(Dog()) fun(Person()) fun(Animal())Copy the code

Special methods and special properties

Special attributes

class A: pass class B: pass class C(A,B): def __init__(self,name): Print (c. __dict__) # print(x.__class__) # print(x.__class__) # print(x Print (c. __bases__) # Print (C.__base__) # Print (C.__mro__) # Class hierarchy Print (a.__subclasses__ ()) #Copy the code

Special methods

  • __add__and__len__
class Student: def __init__(self,name): self.name=name def __add__(self, other): return self.name+other.name def __len__(self): Return len(self.name) studentA=Student(" c ") studentB=Student(" C ") result=studentA+studentB print(result) print(len(studentA))Copy the code
  • __init__and__new__
class Student(object): def __init__(self,name,age): Format (id(self)) self.name=name self.age=age def __new__(CLS, *args, **kwargs): The print('new method is called, Format (id(CLS))) obj=super().__new__(CLS) print(' create object id is {0}'. Format (id(obj))) return obj Format (id(id)) print(id(Student)) print(id(Student)) Format (id(studentA)) print('studenA '=Student(" bigfoot ",52) print('studenA' =Student(" bigfoot ",52) print('studenA '=Student(" bigfoot ",52) print('studenA' =Student(" bigfoot ",52) print('studenA '=Student(" bigfoot ",52) print('studenA')) # object = 140705969040208 # Student = 1919483311136 # new method called, CLS id = 1919483311136 # create object ID = 1919513616448 # init Self = 1919513616448 # studenA = 1919513616448Copy the code
  • That figure

Shallow and deep copies of the class

  • Variable assignment – just two variables that actually refer to the same object
  • Shallow copy -Python copies are generally shallow copies. When copied, the contents of the object’s child objects are not copied. Therefore, both the source object and the copy object reference the same child object
  • Deepcopy – using the copy module’s deepcopy function, recursively copy the child objects contained in the object, and all the child objects of the source and copy object are also different
class CPU: pass class Disk: pass class Computer: def __init__(self,cpu,disk): Self. CPU = CPU self.disk=disk # CpuA =CPU() cpuB=cpuA print(ID (CPU)) print(id(cpuB)) print(cpuA) print(cpuB) # Print (" -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- a shallow copy of a class -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- ') diskA = Disk () computerA = Computer (cpuA, diskA) import copy computerB=copy.copy(computerA) print(computerA,computerA.cpu,computerA.disk) Print (computerB computerB. CPU, computerB. Disk) # deep copy print (" -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- deep copy -- -- -- -- -- -- -- -- -- -- -- -- -- -- - ') computerC=copy.deepcopy(computerA) print(computerA,computerA.cpu,computerA.disk) print(computerC,computerC.cpu,computerC.disk)Copy the code
  • That figure

Chap module

  • What is a module
  • Custom modules
  • Execute in the form of a main program
  • In python package
  • Third party module installation and use

What is a module

  • The module is modules
  • The relationship between functions and modules
    • A module can contain more than N functions
  • In Python, a file with the extension.py is a module
  • Benefits of using modules
    • Facilitate the import of other programs and scripts
    • Avoid conflicts between function and variable names
    • Improve code maintainability
    • Improve code reusability

Custom modules

  • Create a module
    • Create a.py file with a name that is as different as possible from the standard python module
  • The import module
    • Import module name [AS alias]
    • From module name import function/variable/class
Import math print(id(math)) print(type(math)) print(dir(math)) print(math.ceil(3.6)) print(math.floor(2.3)) Print (math. Tan (1/2)) print (math.h pow (2, 3))Copy the code
From math import PI print(PI) from math import pow print(pow(2,3))Copy the code

Execute in the form of a main program