Artificial intelligence general catalog page link
1. Linux basic
Day01 notes
1.1 introduction to development
1. Three operating systems
1,Unix Mac OS ,Solaris 2,Linux RedHat,CentOS,Ubuntu 16.04(Teaching environment version) 3,Windows win7,win8,win 10
2. VMware Workstation (testing, learning)
1,Powerful desktop virtual computer software 2,A powerful tool for developing, testing and deploying applications 3,teaching(Development, test and deployment)Environmental installation 1,download VMware Workstation Install package and install 2,download Linux Operating system image file.iso(Pure version) : Ubuntu 16.04 3,open VMware Workstation,file -> New virtual machine(Assemble the computer) 4,CD/DVD -> Insert disc(.iso file) 5,Turn on this virtual machine -> Power on 6,After installation, install a series of software and modules
2.1 Linux basic commands
3. Linux foundation
1,Terminal: used to input Linux command 1,Click on the picture 2,click "Search computer" -> gnome-terminal 2,Directory tree 1,root / : Represents the starting location of the file system 2,Path: represents a file/String for directory /home/tarena/AID09 3,Linux Basic format of command Command name [option] [parameter] #[] means the content is optional
4. Linux commands
1,pwd : Displays the current path 2,ls : Displays the details of the directory(Files, subdirectories) 1,Common options ls -l : To list(Long format)Display file and directory details ls -a : Show all(Include hidden) with . Start with hidden ls -la ls -al 3,route 1,Absolute path: with / Start path 2,Relative path: Not to / Start path . current directory .. Upper level directory ~ User home directory/Home directory(/home/tarena) 3,home directory/Home directory 1,Super user: root 2,When you create a user, you automatically/home Create a directory with the same name as the user name under,Home directory for this user user name: tarena Home directory:/home/tarena user name: zhanshen Home directory:/home/zhanshen
4,cd : Switch directory(route) 1,usage cd route(Both absolute and relative paths are OK) cd /home/tarena ,cd /home/tarena/aid1809 cd aid1809 #The premise is that the current home directory 2,cd Enter directly: return to the user's home directory/home/tarena cd ~ : Return to user home directory cd - : Switch back and forth from the two most recently accessed directories 3,TAB Key auto fill command/route(Skilled use!!!!!) 1,Fast speed 2,The path cannot be wrong,TAB If it doesn't come out, there is a problem with the path 4,practice 1,Switch to directory:/home/tarena/anaconda3/bin cd /home/tarena/anaconda3/bin/ 2,View the current path pwd 3,List all contents of the current directory in list form(Include hidden) ls -la 4,Switch to the directory above the current directory,Namely : /home/tarena/anaconda3 cd .. 5,Switch to/etc catalogue,see/etc What's in the next section cd /etc/ 6,Switch directly to the user's home directory cd 5,mkdir : Create 1 or n Directories(folder) 1,Format: mkdir Directory name 1 directory name 2 ... 2,Common options -p : Create directory layer by layer mkdir -p One/Two/Three/Go # If the intermediate directory does not exist, create it directly
6,touch 1,effect 1,file does not exist -> establish 2,File exists -> Update file modification time with system time 2,Format: touch File name 1 file name 2 file name 3 ... 3,practice 1,Create directory under user home directory A1/B1/C1/D1 cd mkdir -p A1/B1/C1/D1 2,stay D1 Create file under file1.txt file2.txt cd A1/B1/C1/D1 touch file1.txt file2.txt 3,stay C1 Create file under file3.txt file4.txt cd .. touch file3.txt file4.txt 4,Switch to A1 catalogue,View the current path cd ../../ pwd 5,Switch directly to the user's home directory cd 7,Skill class 1,Automatic replenishment: TAB key 2,Turn up the history and execute the command: press the up and down keys on the keyboard 3,Clear screen: Ctrl + l perhaps clear 4,Terminate command execution: Ctrl + c 5,Terminal font enlargement: Ctrl + Shift + "+" 6,Terminal font reduction: Ctrl + "-" 8,practice 1,Create a command: /home/tarena/Create directory under Directory: Guangdong Province Create directory under Guangdong Province: Shenzhen Create directory in Shenzhen: Bao'an District 2,Create a file under Bao'an District: Fuyong little sister 3,Create the following structure under the user's home directory: Python | +-------+-------+------+ | | | | Shanghai Wuchang Chengdu Shijiazhuang catalogue catalogue Directory directory 9,rm : Delete file/catalogue 1,rm Options file/catalogue -r : Delete all files/catalogue -f : Force deletion,No hint -i : Prompt before deleting(y representative yes,n representative no) rm -rf file name/Directory name
5,text editor vi/vim 1,Format: vi file name 2,vi Three working modes of 1,Browse mode: enter at startup,Text cannot be edited 2,Insert mode(a/i/o) : Edit text 3,Command line mode(ESC -> shift + :) : Save exit.. 3,Text writing steps 1,vi file name 2,Press a/i/o : Edit text 3,Press ESC 4,Press shift + : --> Command line mode 5,wq : Save exit q! : Exit without saving w : preservation
6,Assignment 1 1,Create a file in the user's home directory: tarena.txt 2,stay tarena.txt Write the following contents to save and exit: Laugh up and go out,Are we Penghao people rm -rf Irrecoverable after deletion,Be careful when using Commonly used Linux Operating system: Ubuntu,CentOS,RedHat Linux Folders are called directories in mkdir -p Create a directory for recursion 3,see tarena.txt Content of cat tarena.txt 4,Switch to the directory above the current path 5,View the current path 6,Switch directly to the user's home directory 7,Assignment 2 1,Create a directory under the user's home directory: AID09 2,stay AID09 Create three directories: Linux Pbase AI 3,stay Linux Create 2 directories under Directory: day01,day02 4,stay day01 Create file under: day01.txt 5,stay Pbase Create 3 folders under: day01,day02,day03 6,stay day03 Create under directory day03.txt 7,delete Pbase Catalogue and Linux Lower day01 catalogue 8,Switch to user home directory
http://code.tarena.com.cn user name: tarenacode password: code_2013 route:/AIDCode/aid1809/
Day01 review
1,Test environment installation 1,Download materials: VMware,Ubuntu 16.04 iso Mirror file 2,Assembling a computer: files -> New virtual machine 3,Insert disc: CD/DVD -> Ubuntu 16.04***.iso 4,Power on: start this virtual machine 5,Installation software: Sogou input method Chrome browser ... ... 2,Linux 1,route 1,Absolute path: / start 2,Relative path:. .. ~ Directory name/...... 2,pwd : Displays the current path 3,ls -la : View the contents of the directory 4,cd : Switch directory 1,cd /home/tarena/AID09 2,cd AID09/Linux 3,cd ~ 4,cd 5,cd - 5,mkdir : Create directory 1,mkdir dir1 dir2 dir3 2,mkdir -p dir1/dir2/dir3 6,touch : create a file touch file1 file2 file3 7,skill 1,Automatic replenishment: TAB key 2,Historical commands: keyboard up and down keys 3,Clean screen: Ctrl + l / clear 4,Terminal amplification: Ctrl + Shift + "+" 5,Terminal zoom out: Ctrl + "-" 8,rm -rf : Delete file/catalogue 9,text editor vi/vim 1,Three modes: browse mode, insert mode and command line mode 2,Operation steps 1,vim file name 2,Browse mode->Insert mode: a/i/o 3,Insert mode->Browse mode: ESC 4,Browse mode->Command line mode: Shift + : 5,Exit operation wq! q!
2. Python Basics
Day01 notes
2.1 Linux foundation
1. Linux commands
1,cp : Copy file/catalogue 1,Copy file: cp Source file path 2,Copy directory: cp -r Source directory path 3,cp *.txt /home/tarena/AID09 2,mv : shear/rename 1,Cut: mv File name path mv Directory name path 2,Rename: mv File name 1 file name 2 mv Directory name 1 directory name 2 3,practice 1,Create a file in the user's home directory: game.txt 2,use vim stay game.txt Write the following contents in: My big knife is already thirsty cp Command copy directory to add-r option mv There are two command functions,Cut and rename 3,take game.txt Cut to home directory AID09(If not, please create) 4,to game.txt Rename to: Dota.txt 5,hold AID09 Copy directory to /tmp 3,cat : view file contents(Output at terminal) cat file name 4,tar : Pack and compress 1,format tar -zcvf Compressed package name.tar.gz Compressed file required/catalogue -z : use gzip Compress the package -c : create package(create) -v : show details (verbose) -f : file 2,decompression tar -zxvf Compressed package name.tar.gz -C route -C : Specify the decompression path,Do not write. Extract to the current directory by default
3,practice 1,Create a directory under the user's home directory cd mkdir you and me 2,Create a file under the directory: file1 file2 file3 cd you touch file1 file2 file3 3,use vi stay file1 Write in: vi file1 Life is short,I use Python Wild road: ll tar xf ... 4,Pack and compress the directory into your.tar.gz cd tar -zcvf you.tar.gz you/ 5,Will you.tar.gz Cut to my directory mv you.tar.gz I/ 6,Will you.tar.gz Extract to current directory cd I/ tar -zxvf you.tar.gz
5,file right 1,see: ls -l file name -rw-rw-r-- tarena tarena 2 A.txt 2,Leftmost column:-Representative type 1,d : catalogue 2,- : file 3,l : link(link) 3,jurisdiction r : read w : write(edit) x : Executable 4,rwx Permission grouping Group 1: file owner permissions Group 2: file permissions of users in the same group Group 3: other group users' permissions on files scene(3 Users) User 1: tarena Group: tarena : rw- User 2: tarena2 Group: tarena : rw- User 3: cloud Group: cloud : r-- 6,chmod : Modify file permissions 1,Mode 1 1,Add relevant permissions to all users chmod +x/-w/+rwx/-wx A.txt 2,Modify permissions for the specified group user chmod u+x A.txt chmod o+rwx A.txt a : All users(all) u : owner(user) g : Same group user(group) o : Other users(other) 2,Mode 2(Modify numerically) chmod 644 A.txt : rw-r--r-- chmod 666 A.txt : rw-rw-rw- r : 4 w : 2 x : 1 chmod 777 A.txt : rwxrwxrwx 3,practice 1,Create a file in the user's home directory: secret letter.txt touch secret letter.txt 2,use vi Write to file: My secret letter When I look back, I smile and smile,Six palace pink without color Spring nights are bitter and short, and the sun rises high,From then on, the king didn't come early 3,View secret letter.txt jurisdiction ls -l secret letter.txt 4,Set file permissions to be readable, writable, and executable,Others have no authority chmod 700 secret letter.txt 5,On the basis of 4, set the permission to be read-only for the same group of users chmod 740 secret letter.txt chmod g+r secret letter.txt 6,Remove the executable permission of the file chmod -x secret letter.txt 7,Secret letter.txt Copy to under user's home directory AID09 in cp secret letter.txt AID09/
2. Linux Advanced command
1,sudo : obtain root User's permission execution Linux command cd / touch A : Insufficient prompt permission sudo touch A ## As long as the prompt permission is not enough, you can add it sudo ## 2,df -h : View disk usage /dev/sda1 216G 16G 189G 8% / 3,top : Task Manager,see%CPU 4,ps -aux : View the of an application PID number ps -aux | grep "firefox" cat Fuyong little sister.doc | grep "hello" 5,kill -9 PID number
2.2 Python introduction
3. Python
1,Python brief introduction 1,application area 1,System operation and maintenance 2,Network programming 3,Artificial intelligence, robot 4,Web development 5,Cloud computing, big data 6,Crawlers, games, images ... ... 2,advantage 1,object-oriented 2,Open source and portable 3,Easy to learn and use, high development efficiency 3,shortcoming Low execution efficiency 2,edition 1,Python2(2020 Stop maintenance in) Python2.7 2,Python3 Python3.5(Teaching environment) Python3.8(newest)
2.3 first Python program
4. My first Python program
1,File: hello.py Function: output at terminal hello world 2,function: python3 hello.py
5. Sublime code editor
1,multiline comment /Uncomment: Ctrl + / 2,preservation: Ctrl + s 3,Fallback: Ctrl + z 4,Select multiple cursors at the same time: Ctrl + Left click
6. Python interactive interpreter
1,get into: python3 2,sign out: exit() ,quit() ,Ctrl + d
2.4 Python Basics
7. Python data type
1,Number type 1,classification 1,integer int : 100 5 20 2,float float : 6.66 8.88 3.0 2,Representation of integers 1,decimal system 35 3*10**1 + 5*10**0= 35 50 666 2,Binary(0b start) 0b0000 # 0 0b0001 # 1 0b0010 # 2 0b01001000 # 1*2**6 + 1*2**3 = 72 3,hexadecimal(With 0 x start) 0 1 2 3 4 5 6 7 8 9 a b c d e f 0x11 # 1*16**1 + 1*16**0 = 17 0xFF # 15*16**1 + 15*16**0 = 255 0xA0 # 10*16**1 + 0*16**0 = 160 4,octal number system(With 0 o start) 0o177 # 1*8**2 + 7*8**1 + 7 = 12 7 0o11 # 1*8**1 + 1 = 9 2,character string 3,List, tuple ... ... 4,Boolean type bool : True ,False 5,Null value: None
8. Arithmetic operators
1,classification + - * / % : Remainder ** : exponentiation // : divide by, as long as an integer 2,priority(plus()control) ** * / % // + - 3,Examples The graduation salary of students is 10000.00 element,Up 20% a year%,What's your salary in ten years? 4,practice The watermelon in the supermarket is 7 yuan a piece,You have 100 yuan,How many watermelons can I buy,How much change? % //
9. Placeholder (string formatting)
1,format string % Variable name format string % (Variable 1,Variable 2) 2,%s Placeholder: String %d Placeholder: integer %f Placeholder: floating point number %.2f(Keep 2 decimal places)
3,practice 1,Define 2 variables,computer you,The values are: stone and cloth,Terminal output: Computer punch:Stone, you punch:Congratulations,You win! 2,Define 3 variables,name,gongsi,salary,Terminal output: ...Induction...company,Salary is...element 3,A circle has a radius of 3cm,Calculate the circumference and area of a circle pi : 3.14 The circumference of a circle with a radius of 3cm is:? centimeter The area of a circle with a radius of 3 cm is:? square centimetre Perimeter: 2 * 3.14 * 3 Area: 3.14 * 3 ** 2 4,Apples in the supermarket are 9 yuan a kilo,You have 100 yuan,How many kilograms of apples can I buy,How much money is left?(placeholder ) 5,If you're 23 now,365 days per year,How many Sundays have you spent?(placeholder ) 6,From 0 a.m:0:0 time,66666 seconds have passed,What time is it, please(placeholder )
10. Homework
1,Output graphics at terminal * *** ***** *** * 2,The scale in ancient China was 16 Liang and 1 jin,How many kilos is the current 216 liang,Write a program and print it out 3,Temperature conversion Centigrade temperature = 5.0/9.0*(fahrenheit-32) Kelvin temperature = Centigrade temperature + 273.15 Excuse me: what is the temperature from 100 Fahrenheit to Celsius? What is the Kelvin temperature?
python_day01 review
command: cp / cp -r Copy file/folder mv move file/folder(Change name) cat display the contents of a text file tar Pack and compress $ tar -czvf folder Unpack and compress $ tar -xzvf a.tar.gz mkdir create folder rmdir remove folders touch create a file/Update the modification time of the file chmod Modify file permissions (read/write/implement) rwx rwx rwx sudo obtain root User authority, which is used to execute commands df View disk top Task Manager ps see pid process
python application area python edition python V3 python V2 python Implementation of: $ python3 xxxxx.py $ python3 <enter> # Interactive mode >>> >>> exit() / quit() / ctrl + d python Data type of: String, number, list.... Number type: integer int decimal system : -100 0 99 9999999 11 hexadecimal: 0x1234 0xABCD 0xabcd 0x11 octal number system : 0o12345670 0o11 Binary : 0b11 Floating point number float 3.14 .14 0.14 3. 3.0 314e-2 0.314e1 3.14E0 complex complex (1 + 2j) Boolean number bool True/False 1 / 0 character string: '' "" Arithmetic operator: + - * / // % ** % Formatting of strings
Day02 notes
vscode (Visual Studio Code / Microsoft) zoom ctrl + + / ctrl + - notes ctrl + / preservation ctrl + s (important) start-up vscode Command of: $ code <enter> $ code file name<enter> $ code Folder name<enter>
1. Variables
What are variables: A variable is an identifier associated with an object Variables can be bound to an object,And you can use this object by variable name Naming method of identifier: Start with a letter or underscore followed by a letter or number explain: Identifiers are case sensitive
Examples: a A a1 bbbb set_age _ _abcd __abcde a1b2 Illegal identifier: 1a 123 $ABC python The keyword cannot be used as a variable name: True, False, None, is, del, if,......
2. Assignment statements
Symbol = grammar: Variable name = expression or Variable name 1 = Variable name 2 = expression or Variable name 1, Variable name 2, ... = sequence effect: Create a variable and bind the data object Change the bound data object of a variable Examples: a = 10 b = 20 c = a + b # c binding 30 a = b = c = 10000 # Change the binding relationship of three variables at the same time # Bind to 10000 at the same time x, y = 100, 200 # Bind 100 with x and 200 with y
practice: Specify a rectangle with a long side length of 6(centimeter) Short side length 4(centimeter) Print out the perimeter and area of the rectangle
Description of assignment statement: 1. When the variable does not exist, the assignment statement creates the variable,At the same time, the variable Bound to the object to the right of the assignment operator 2. When a variable exists, change the binding relationship of this variable 3. Only one object can be bound to a variable 4. Multiple variables can be bound to an object at the same time as: a = 100 b = a # b is also bound to the 100 bound by a
3. del statement
effect: Used to delete variables and disassociate with objects. If possible, the Release object grammar: del Variable name 1, Variable name 2, ... View all variables in the current scope in interactive mode: >>> help('__main__') Examples: a = 100 b = 200 x, y = 123, 456 del a del b, x, y # Delete 3 variables at the same time
4. Automated memory management and reference counting:
Automated memory management and reference counting:Each object records several variable references(binding)oneself,When the number of references is 0, the object is destroyed. This automatic memory management method is called"Reference count"
5. is and is not operators
effect: Judge whether two objects are the same object. When they are the same object return True,Otherwise return False is not And is The return value of is opposite grammar: x is y x is not y
6. id function:
effect: Returns the address of an object in memory explain: is Operator is based on id To judge format: id(object)
7. Small integer object pool:
CPython Medium, integer-5 To 256 always exist in the small integer object pool, will not be released, and can be reused
8. Compound assignment arithmetic operator
operator explain y += x Equivalent to y = y + x y -= x Equivalent to y = y - x y *= x Equivalent to y = y * x y /= x Equivalent to y = y / x y //=x equals y = y // x y %= x Equivalent to y = y % x y **= x Equivalent to y = y ** x
9. Comparison operator
< less than <= Less than or equal to > greater than >= Greater than or equal to == be equal to != Not equal to grammar: Left expression < Right expression explain: The comparison operator returns a Boolean value Examples: 100 < 200 1 + 5 == 2 + 4 0 <= 60 <= 100
10. Constructor (creation) function of numeric object
Constructor of numeric object(establish) function float(obj) Convert a string or number to a floating point number, if If no parameters are given, 0 is returned.0 int(x, base=10) or int(x=0) Convert with number or string Replace with an integer. If no parameters are given, 0 is returned complex(r=0.0, i=0.0) Create a complex number with numbers( The real part is r, Imaginary part is i) bool(x) use x Create a Boolean value(True/False) Syntax of function call: Function name(Pass parameter list) explain: A function call is an expression that must return a reference to an object Use relation(Or return None)
11. bool(x) returns a false value
value explain None Null value False Boolean false value 0 0.0 0j Number 0 ------- Learn later------ '' character string [] Empty list () Empty tuple {} Empty dictionary ....
practice:
Put the number 3.14 Use variable pi binding take pi Variable to integer i binding take pi Variables and i Variables are subtracted, and the result is variable f binding 1. judge f Is it equal to 0.14 2. Delete all variables (Do it in interactive mode)
12. Preset (built-in) numerical function
abs(x) take x Absolute value of round(number[, ndigit]) Numerical"rounding", ndigit Is the number of decimal places rounded to the right, and a negative number indicates to the left Rounding pow(x, y, z=None) amount to x**y or x**y%z
Examples: abs(-100) # 100 round(1234.56789) # 1235 round(1234.56789, 2) # 1234.57 round(1234.56789, 4) # 1234.5679 round(1234.56789, -2) # 1200.0 pow(5, 2) # 25 pow(5, 2, 10) # 5
13. help() function view the help of the function
>>> help(Function name) # View the help for the corresponding function
14. statement
A statement consists of some expressions. Usually, a statement can be executed independently Complete some things and form results Semicolons should be used when multiple statements are written in one line(;) separate See for example: code/statement.py
15. Explicit line Wrap:
When the sentence is too long, a line cannot be placed. Use \(Backslash)Perform an explicit line break See for example: statement2.py
16. Implicit line folding
The contents of all parentheses wrap, which is called implicit line break Parentheses that can be used for implicit line breaks are: () [] {}
17. Basic input and output functions
Basic input function input
effect: Reads a string from a standard input setting(Does not contain line breaks) format: input('Prompt string') explain: Returns the string entered by the user 'Prompt string'Can be empty See for example: input.py
Basic output function print
format: print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False) Outputs a series of values as strings to a standard output device upper(Default to terminal) Parameter options: sep: Separator between two values(The default is a space' ') end: Automatically append a string at the end after output(default Line feed'\n') file: Stream object(Default to sys.stdout) flush: Output stream now
practice:
1. Enter two integers and use variables respectively x,y binding 1) Calculate the sum of these two numbers,And print the results 2) Calculate the product of these two numbers,And print the results 3) calculation x of y What is the power? And print 2. Enter the hours, minutes and seconds of the current time in three times Then calculate the distance 0 a.m:0:0 How many seconds have passed 3. Calculation of three insurances and one fund: What is the known contribution rate of social security: project Individual payment proportion unit payment proportion endowment insurance 8% 19% employment injury insurance 0% 0.5% medical insurance 2%+3 Yuan 10% housing fund 12% 12% Enter your social security base in Beijing(like: 5000) Print individual payment details for you and the company,Total amount paid by individuals, What is the amount paid by the unit and the money received by the state?
day02 review
python version of python V2 python V3 python run: 1. at the command line prompt $ python3 xxxx.py 2. Execute in interactive mode: $ python3 <Enter> >>> >>> quit() / exit() / ctrl+d # quit python Notes: by # start to end of line python Common data types: Number type: int 0, 999999999, -2, 0b1001, 0o11, 0x9 float 3.14, 0.314e1 314.0e-2 complex 1+2j bool True, False string list .... null value object None, Representative does not exist(nothing) operator: arithmetic operators: + - * / //(floor division) % (remainder) **(exponentiation) comparison operator: < <= > >= ==(equal) !=(not equal to) assignment statement: variable = expression variable 1 = variable 2 = variable 3 = expression variable 1, variable 2, variable 3 = sequence The role is to create a variable to bind the result of the execution of the expression del statement del variable name The effect is to delete the variable is,is not operator judge two objects id Is it the same Compound assignment arithmetic operators: += -= *= /= //= %= **= y +=x The effect is equivalent to y = y + x function: type conversion function: float(obj) int(x, base=10), int(x=0) complex(r=0.0, i=0.0) bool(x) Syntax rules for function calls Function name(parameter list) A function call is an expression and must return a result(the result may be None) Numeric function: abs(x) Pick x the absolute value of round(number[,ndigit]) Pick number approximation of pow(x, y, z=None) # Find the remainder of x to the y power or x to the y power to z Functions to view help: >>> help('string') >>> help(Function name) Basic input and output functions: input("prompt string") # Get the string entered by the user print(value1, value2,..., sep=' ', end='\n')) The function is to form a string into a number and print it on the screen terminal
Day03 Notes
1. if statement
if statement question: There are two statements: print("this number is even") print("this number is odd") How to make only one of them execute??? if The role of sentences: Let the program execute a certain statement or some statements selectively according to the conditions grammar: if truth expression 1: statement block 1... elif truth expression 2: statement block 2... elif truth expression 3: statement block 3.... ... else: statement block 4 illustrate: elif Clause can have 0,1 one or more else Clause can have 0 or 1 and can only be placed in if the end of the sentence For example see: if.py practise: Enter any integer 1) Determine if the number is greater than 100 2) Check if the number is less than 0 3) Determine if the number is within 50~150 between (It is recommended to use one for each step if statement to implement)
if-elif-else For example see: if_elif.py practise: 1.Enter a quarter 1 ~ 4 Output which months in this quarter. If the input is not 1~4 integer, prompting the user that you made a typo 2. Enter the month of the year(1~12),Output which quarter this month is in. If you enter another number, it will prompt you to enter a wrong number
2. Nested if statements
if statement nesting if The statement itself is a compound statement consisting of multiple clauses if Statements can be nested as statements inside another compound statement For example see: if_embed.py conditional expression grammar: expression 1 if truth expression else expression 2 effect: According to the value of the truth expression(True/False) to decide to execute expression 1 or expression 2 and return the result For example see: if_express.py practise: 1. Write a program that takes a number and uses if The statement calculates the number of absolute value and print it 2. Write a program that inputs a number and uses a conditional expression to calculate the number the absolute value of and print the result
3. pass statement
pass statement effect: Often used to fill in grammatical blanks pass aka empty statement grammar: pass For example see: pass.py
4. Boolean operations
Boolean operations: operator: not and or No and or 1.boolean not operation not grammar not x effect: right x perform boolean negation, such as bool(x) for True,then return False, otherwise True Example: 2.Boolean and operation and grammar: x and y Note: x,y representative expression effect: Prefer to return false value objects,when x The boolean value of False , return x otherwise return y Example: True and True # True True and False # False False and True # False False and False # False 100 and 0.0 # 0.0 0 and 0.0 # 0 3.boolean or operation or grammar: x or y effect: Returns a truth value object first, when x for True return when x,otherwise return y Example: True or True # True True or False # True False or True # True False or False # False 3.14 or 100 # 3.14 0 or 0.0 # 0.0
5. Sign operator
plus and minus operator +(Positive sign) -negative Note: unary operator(An element participates in the operation) grammar: + expression - expression Example: a = 5 b = -a # -negative c = +a # Positive sign print(a, b, c) # 5 -5 5
6. String str
string str effect: to record text(text)information display method: Anything enclosed in quotation marks in a non-comment is a string ' apostrophe " Double quotes ''' triple single quotes """ triple double quotation marks A literal representation of the empty string '' "" '''''' """""" Expression method for literal value of non-empty string 'hello' "hello" '''hello''' """hello"""
7. The difference between single and double quotes
Double quotes within single quotes do not count as terminators Single quotes within double quotes do not count as terminators For example see: str.py
8. The role of triple-quoted strings
Triple-quoted strings can contain single and double quotes Newlines in triple-quoted strings are automatically converted to newlines'\n' For example see: str2.py
9. Implicit string literal concatenation
Implicit string literal concatenation Example: s = "I'm a teacher" 'my name is "Tarena"' print(s) #
10. Use escape sequences to represent special characters
Use escape sequences to represent special characters Use the character backslash in string literals \ followed by some characters representing a special character such as: Convert word format Meaning \' represents a single quote \" represents a double quote \\ represents a backslash \n newline \r Return the cursor to the beginning of the line \f form feed \t horizontal tab \v vertical tab \b fall back \0 null character(character value is 0) \0oo oo character in two-digit octal \xXX XX character in two-digit hexadecimal representation \uXXXX Four-digit hexadecimal representation Unicode 16 character \UXXXXXXXX eight-digit hexadecimal representation Unicode 32 character
11.ASCII encoding table
ASCII code table $ man ascii<Enter> common ASCII coding character decimal hex '0' 48 0x30 'A' 65 0x41 'a' 97 0x61
12. The concept of sequence
sequence concept Strings are sequences(orderly arrangement) All sequences are available len(x) function to find its length len(x) function Returns the number of characters in a string practise: Use interactive mode to verify how many characters the following string has 1. '1234abcd' # 8 2. '5\'4"' # 4 3. '\"A\x34\056'# 4 4. '\a\bc\td\n' # 6
13.raw string (raw string)
raw string(raw string) Format: r'string content' r"string content" r'''string content''' r"""string content""" effect: let escape character backslash \ invalid Example: a = 'C:\newfile\test.py' print(a) print(len(a)) a = r'C:\newfile\test.py' print(a) print(len(a))
14. String operations:
String operations: operator: + += * *= + The plus operator is used to concatenate strings x = "ABCD" y = "123" z = x + y print(z) # ABCD123 += Used to concatenate the original string and the right string, and then use the variable to bind the new one string x = 'ABC' y = '123' x += y print(x) # ABC123 * operator produces duplicate strings x = "ABC" * 3 print(x) # ABCABCABC Note: Strings can only be multiplied by integers *= Generate repeated strings, and then use the original variable binding x = '123' x *= 2 print(x) # 123123
14. String comparison operations
String comparison operations operator: < <= > >= == != comparison rules: Compare the two characters according to the encoding value in turn, if they are different, the comparison ends. And return the comparison result, when the encoded value and length are exactly the same, the two characters String the same Example: 'A' < 'B' # True 'ABC' > 'ABB' # True 'ADC' < 'ABC' # False 'ABC' >= '123' # True 'AB' < 'ABC' # True 'abc' == 'ABC' # False
15.in, not in operator
in, not in operator effect: in Used in sequences, dictionaries, and sets to determine whether a value exists in a container,return if exists True,then return False not in and in operator returns the opposite Format: object in sequence Example: x = 'welcome to tarena!' 'to' in x # True 'hello' in x # False 'e t' in x # True 'abc' not in x # True
practise:
practise: 1. Beijing taxi meter: Charges: 3 CNY 13 within a kilometer Basic unit price 2.3 Yuan/kilometer(beyond 3 km) empty driving fee: After more than 15 kilometers, 50 per kilometer will be charged for the unit price%of empty driving fee(3.45 Yuan/kilometer) Require: Enter the number of kilometers and print out the fee amount 2. Enter a student's grades for three subjects: 1) print out the highest score? 2) print out the minimum score? 3) print out the average score? 3. calculate BMI index(Body Mass Index) body mass index Calculation formula: BMI = weight(Kilogram)/height squared(Meter) like:A 69 kg person and 173 cm tall, then BMI = 69 / 1.73 ** 2 # got 23.05 Standard table: BMI < 18.5 underweight 18.5 <= BMI < 24 normal weight BMI >= 24 overweight Require: Enter height and weight, print BMI value, and print the weight status 4. write a program.Print a rectangular box with a height of 4 lines To display an integer, the integer represents the width of the rectangle, enter this rectangle like: Please enter rectangle width: 10 print as follows: ########## # # # # ########## If you enter a larger number, the rectangle will be wider
day03 review:
if statement Selectively execute one or some statements based on conditions grammar: if truth expression: statement block 1 elif truth expression 2: .... elif ....: .... else: statement block first compound statement if nesting of statements if xxx: if yyy: if zzzz: ... else: .... else: .... pass statement Fill in syntax blanks conditional expression x + 1 if y > x else x + 2 Boolean operations: and or not unary operator: +(Positive sign) -(negative) -100 string str "hello" 'ABC Chinese' 'A B C' '\n\t' ' " ''' """ beginning and end The boolean value of an empty string is False escape character: '\n' '\r' '\\' '\'' '\"' '\t' '\xXX' '\uXXXX' '\UXXXXXXXX' ascii coding len(x) find the length of the string raw string r'abc' r"ab\n\rcd" r'''abc''' r"""abc""" r'''ab cd''' # Equivalent to 'ab\ncd' String operations: + splicing * repeat n Second-rate += *= < <= > >= == != "ABC" == "ABC" "ABC" == "CBA" # False in , not in
Day04 Notes:
1. Basic operations of strings
index index python A string is an immutable sequence of characters index value syntax: string[integer expression] illustrate: python Sequences can be indexed(index) to access the objects in the sequence python The forward index of the sequence starts at 0, and the second index is 1,at last An index is len(s)-1 python The reverse index of the sequence is from-1 started,-1 represents the last, -2 represents the second to last, and so on. the first is-len(s) Example: s = "ABCDE" print(s[1]) # B print(s[4]) # E print(s[-1]) # E print(s[-5]) # A print(s[100]) # IndexError out of bounds
practise: Write a program to input a string,print the following in the string 1. print the first character of this string 2. print the last character of this string 3. If the length of the string is odd, print the middle character Note: The function to find the length of a string is len(s)
2. Slice slice
slice slice effect: Take the corresponding elements from the string sequence and reconstitute a new string grammar: string[(start index b):(end index e)(:(step size s))] Note: Parentheses() The enclosed part means that it can be omitted illustrate: The start index is the position where the slice starts to be cut, and 0 represents the first element,1 represent the second element,-1 represents the last.... end index is the end index of the slice(but not the end point) The step size is the direction and offset that the slice moves after each time it gets the current element 1. No step size, equivalent to a step size of 1(Default is 1) 2. When the step size is a positive integer, take the forward slice: The start index defaults to 0,The end index defaults to the last element next position 3. Take the reverse slice when the step size is a negative integer: When reverse slicing, the default starting position is the last element, ending position is the previous position of the first element Example: s = "ABCDE" a = s[1:4] # a---> "BCD" a = s[:4] # 'ABCD' a = s[1:] # 'BCDE' # Equivalent to s[1:5] a = s[:] # 'ABCDE' # Equivalent to s[0:5] a = s[1:1] # '' empty string a = s[4:2] # '' null a = s[0:5:2] # 'ACE' a = s[4:0:-2] # 'EC' a = s[4::-2] # 'ECA' a = s[::-1] # 'EDCBA'
practise: 1. Write a program that takes a string and takes the first character of the string and After the last character is removed, print out the processed string 2. Write a program, enter any string, and determine whether the string is a palindrome A palindrome refers to a centrally symmetric text, such as: Shanghai tap water comes from the sea ABCCBA
3.Python operator precedence
Documentation see: python_base_docs_html/Python operator precedence.html
Documentation see:
python_base_docs_html/Python operator precedence.html
4. Functions that can be used for strings in python3
python3 functions that can be used with strings in: len(x) return string length max(x) Returns the character with the largest string encoding value min(x) Returns the character with the smallest encoded value in the string String encoding conversion function: ord(c) return a character c of unicode encoded value chr(i) return i the character corresponding to this value Example: x = ord('A') # x = 65 c = chr(66) # c = 'B'
practise: 1. Write a program, input a string, if the string is not empty, put the first The encoded value of a character is printed out 2. Write a program that takes an integer(0~65535),print this value corresponding character
5. Functions for converting integers to strings
Integer to String function: bin(i) convert integer to binary string oct(i) Convert integer to octal string hex(i) Convert integer to hex string String construction(create)function: str(obj) convert object to string Example: '123' + 456 # error '123' + str(456) # result '123456'
6. String methods commonly used in python3 (method)
python3 String methods commonly used in(method) method call syntax: object.method name(method parameter) Example: 'abc'.isalpha() # return True '123'.isalpha() # return False 123.isalpha() # error See the documentation for the method: python_base_docs_html/str.html python_base_docs_html/str.html
practise: enter a string: 1. Determine how many spaces there are in the character you entered 2. Remove the left and right blank characters of the original string and print out valid characters number 3. Determine if your input is a number, If it is a number, determine whether the number entered by the user is greater than 100
7. String formatting expressions
1.string formatting expression effect: Generate a string in a certain format operator: % syntax format: format string % parameter value format string % (parameter value 1, parameter value 2, parameter value 3, ...) illustrate: The format string starts with%The character at the beginning is a placeholder, and the position of the placeholder will be replace with parameter value Example: fmt = "name: %s, age: %d" s2 = fmt % ("Tarena", 15) fmt2 = "age: %d" s3 = fmt2 % 35 2.placeholder type code in format string Placeholders and Typecodes meaning %s string, use str(x) function transformation %r string, use repr(x) function transformation %c Integer to single character %d decimal integer %o octal integer %x hex integer(character a-f lower case) %X hex integer(character A-F capital) %e Exponential floating point number(e lower case) like: 2.9e8 %E Exponential floating point number(E capital) like: 2.9E8 %f,%F floating point decimal %g,%G Automatic conversion of decimal form floating point or exponential floating point %% equivalent to a%character 3.Format syntax between placeholders and type codes % [ - + 0 width.precision ] type code - Align left(The default is right-aligned) + Show positive sign 0 Zero padding in the left blank width The width of the entire data input Precision How many digits after the decimal point are retained(Default is 6 bits) Example: "%10d" % 123 # ' 123' "%-10d" % 123 # '123 ' "%10s" % "abc" # ' abc' '%-5s' % 'abc' # 'abc ' '%05d' % 123 # '00123' '%+05d' % 123 # '+0123' '%7.3f' % 3.1415926535 # ' 3.142'
practise: Enter three lines of text, and align the three lines of text to the right with a width of 20 characters show like: Please enter line 1: hello world Please enter line 2: abcd Please enter line 3: aaaaaaa The print result is as follows: hello world abcd aaaaaaa Think after you have finished: Can the display be right-aligned by the length of the longest string?(left padding space)
8. Loop statement:
loop statement: while statement for statement question: enter an integer n,Write the program to print as follows n line text: This is line 1 This is line 2 This is line 3 ... This is the first n Row while statement: effect: Execute a statement or multiple statements repeatedly based on certain conditions grammar: while truth expression: statement block 1(This part of the statement may be repeated many times) else: statement block 2 illustrate: 1. Execute the truth expression first,get boolean value True or False 2. If the value of the truth expression is True,then execute block 1,after that Return to step 1 and repeat the test for the value of the truth expression 3. If the value of the truth expression is False,then execute else clause part statement block 2,then end this while execution of the statement Note: else clause part can be omitted(same if Statements like) For example see: while.py
practise: 1. Enter three lines of text to center them in a box as input: hello! I'm studing python! I like python! Shows as follows: +---------------------+ | hello! | | I'm studing python! | | I like python! | +---------------------+ 2. use while loop print 1 ~ 20 the integer(Can print multiple lines) 3. use while loop print 1 ~ 20 Integer, printed on one line Separate each number with a space 1 2 3 4 5 6 .... 18 19 20 4. use while loop print 1 ~ 20 The integers, 5 are printed per line, print 4 lines,like: 1 2 3 4 5 6 7 8 9 10 ... 5. enter an integer n,prints a width and height of n character rectangle like: please enter: 4 Print: #### # # # # #### like: please enter: 6 Print: ###### # # # # # # # # ######
day04 review:
string index, slice index take out a character slice: Take out some characters and reconstitute a string index syntax: string[integer expression] Slice syntax: string[start index:end index:step size] function: chr(integer) # Convert to string (contains only one character) ord(a character) # Convert to integer encoded value bin(i) oct(i) hex(i) str(obj) convert object to string Common methods for strings: S.isdigit() S.isalpha() S.islower() S.isupper() S.isspace() S.center(width, fill=' ') S.count(sub, start, end) S.find(...) S.strip([char]) / S.lstrip() S.rstrip() S.upper() / S.lower() S.replace(old, new) S.startswith(string) / S.endswith(string) >>> help(str) string format expression "Name: %s, gender:%s, age:%d" % ("Xiao Zhang", "male",20) Common placeholders and type codes: %s %d %f %7.2f %-7.2f %+7.2f %07.2f while statement (loop statement) grammar: while truth expression: block of statements that may be executed repeatedly else: statement block 2 practise: 1. enter an integer n value representing the end,find the sum of the following expressions 1 + 2 + 3 + 4 + .... + (n-1) + n the sum like: please enter: 100 Print: 5050
Day05 Notes:
1. Notes on while statement:
while Statement Notes: 1. To control the value of the truth expression of the loop to prevent infinite loops 2. Often loop conditions are controlled by loop variables inside truth expressions 3. Usually changing the loop variable inside the statement
1. To control the value of the truth expression of the loop to prevent an infinite loop
2. Loop variables are usually used in truth expressions to control loop conditions
3. Usually change the loop variable inside the statement
2. Nested while statements:
while statement nesting: while sentences are sentences,Like other statements, it can be nested into in any compound statement signal: while truth expression: .... while truth expression 2: .... else: ... ... else: ... For example see: while_embed.py practise: enter an integer n,Print a square of the specified width like: please enter: 5 Print: 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 like: please enter: 3 Print: 1 2 3 1 2 3 1 2 3
3.break statement
break statement question: If you do not want to continue the execution of the loop statement during the loop,How to do? effect: for loop statement(while,for statement)middle,Used to terminate the current loop statement execution. illustrate: when break After the statement is executed,this loop statement break Statements after that will no longer be executed break Statements are usually if Combination of statements break statement terminates the loop,loop statement else clause's statement will not execute break statement can only terminate the execution of the current loop statement,If there are loops nested Time,Does not break out of nested outer loops break statement can only be used in a loop statement(while,for statement)internal use of For example see: break.py
9. Infinite loop
infinite loop An infinite loop is a loop in which the loop condition is always established Infinite loop can usually be used break statement to terminate the loop infinite loop else clause never executes
Let the user enter some arbitrary integer,End input when negative number is entered When the input is complete,print the sum of these numbers you entered like: please enter: 1 please enter: 2 please enter: 3 please enter: 4 please enter: -1 Print: 10
10. Loop Statement
loop statement: while statement for statement for statement effect: The data elements used to iterate over the iterable object Iterable objects are objects that can sequentially obtain data elements like: string,list,tuple,range Objects returned by functions, etc. grammar: for variable list in iterable object: statement block 1(Here is a block of statements that may be executed repeatedly) else: statement block 2 illustrate: when used in circulation break when the loop is terminated,else clause part sentence will not execute else clause part can be omitted For example see: for.py
practise:
practise: Enter any string 1) Count the number of spaces in a string 2) Calculate the number of Chinese characters in a string (Note: The encoding value of Chinese characters must be greater than 128,available ord judge)
11.range() function
range() function: range(stop) used to generate 0~stop integer in range,until stop for end(does not contain stop) range(start, stop[,step]) used to generate start~stop Area integer in the interval,until stop until(does not contain stop), every integer interval step See the format for details: >>> help(range) effect: Used to create an iterable that yields a sequence of integers(Also called a sequence of integers Builder) signal: range(4) generate 0, 1, 2, 3 range(3, 6) Build 3, 4, 5 range(1, 10, 2) Generate 1, 3, 5, 7, 9 range(5, 0, -1) Build 5, 4, 3, 2, 1 range(5, 0, -2) Build 5, 3, 1 range(4, 0) generate empty For example see: range.py
practise: 1. print 1 ~ 20 integers, printed on one line(use for Statement implementation) 2. Calculate 1 + 2 + 3 + 4 + ..... + 99 + 100 the sum (use for and range accomplish) 3. Calculate 1 + 3 + 5 + 7 + .... + 97 + 99 the sum (use for Statement implementation)
for statement nesting: Example: for x in "ABC": for y in "123": print(x + y)
12.continue statement
continue statement question: How to stop the program from going down and start a new loop again? effect: for loop statement(while,for), no longer execute this loop continue After the statement, start a new loop again illustrate: 1. exist while execute in statement continue statement, will jump directly to while At the truth expression of the statement, re-evaluate the loop condition 2. exist for execute in statement continue statement, which will start from the iterable object loop again after taking the next data-bound variable in For example see: continue.py
practise: beg:1 ~ 100 All in between cannot be 2, 3, 5, 7 sum of divisible numbers
Loop summary: while statement for statement string str range() the object returned by the function break statement continue statement
question: container How to temporarily store the data calculated by the computer in one place, and at the same time Easy to add, delete, modify, view and other operations
13. List list
1. List creation and constructor
list list A list is a container Lists are sequence containers that can be changed Create an empty list literal L = [] # L binds a newly created empty list A literal that creates a non-empty list: L = [1, 2, 3, 4] L = ["Beijing", "Shanghai", "Shenzhen"] L = [1, "two", 3.14, "Four"] L = [1, 2, [3.1, 3.2, 3.3], 4] List construction(create)function list list() Creates an empty list, equivalent to[] list(iterable) Create a list with iterable objects Example: L = list() # L bind empty list L = list("hello") #L binding['h','e','l','l','o'] L = list(range(10)) # L binding [0,1,2,3...9]
2. Operations on lists
Operations on lists: arithmetic operators + += * *= Example: + plus sign for concatenating lists x = [1, 2, 3] y = [4, 5, 6] z = x + y # z = [1, 2, 3, 4, 5, 6] += Used for splicing the original list with the iterable object on the right,bind list with variable grammar: x += iterable object like: x = [1, 2, 3] y = [4, 5, 6] x += y # x bind [1, 2, 3, 4, 5, 6] x = * generate duplicate lists *= repeat the original list n use the original variable binding again x = [1, 2] * 3 # x =[1, 2, 1, 2, 1, 2] x = [1, 2] x *= 2 # x = [1, 2, 1, 2]
practise: 1.enter an integer n,This integer represents the length of the right-angled sides of the triangle according to integer n Print the following four triangles please enter: 3 print as follows: 1) * ** *** 2) * ** *** 3) *** ** * 4) *** ** *
2. write a program,Enter any integer,Check if this integer is a prime number(prime) Prime number(also called prime numbers), positive integer only divisible by 1 and itself like: 2 3 5 7 11 13 17 19 hint: by exclusion,when judging x Whether it is a prime number,just let x divided by 2, 3, 4, ... x-1 ,as long as there is one divisible,but x no Prime number,otherwise x is a prime number 3. Enter a positive integer representing the width and height of the square,print the following square like please enter: 5 Print: 1 2 3 4 5 2 3 4 5 6 3 4 5 6 7 4 5 6 7 8 5 6 7 8 9 like please enter: 3 Print: 1 2 3 2 3 4 3 4 5
day05 review
loop statement while statement for statement while grammar: while truth expression: statement block 1 else: statement block 2 for grammar for variable name in iterable object: statement block 1 else: statement block 2 iterable object: str range() the returned object list list range(start integer,end integer,step size) range(start integer,end integer) range(end integer) break statement terminate the current loop break after execution,loop statement else The statement in the clause will not be executed continue statement start a new cycle for while and for Statement jump position is different list list How to create a list [] [1, 2, 3, 4] [1, 2, [3, [4, 5]], 6] Constructor list() list(iterable object) Operations on lists: + += * *= += operator is equivalent to appending data to the end of the original list L = [1, 2] print(id(L)) L += [3] # is not equivalent to L = L + [3] print(id(L)) # id does not change
Day06 Notes:
3. List comparison operations
List comparison operations: operator: < <= > >= == != illustrate: The comparison rules for lists are the same as for strings Lists require that every two elements be compared in turn,Otherwise there will be a type error Example: [1, 2, 3] < [1, 2, 4] # True [1, 2, 3] != [1, 2, 4] # True ["One", "Two"] < ["1", "2"] # False [1, 'Two'] > ['Two', 1] # TypeError [1, "two", 3.14] < [2, "2", 1] # True
4. The in / not in operator for lists
list in / not in operator Check if a value exists in the list, and return if it exists True, otherwise return False the same string in operator like Example: x = [1, 'Two', 3, "Four"] 3 in x # True "3" in x # False 10 not in x # True
5. Indexing operations on lists
Indexing operations on lists: 1.index value grammar: x = list[integer expression] usage: equivalent to the index of the string(Also divided into forward index and reverse index) 2.index assignment Lists are mutable sequences,Elements in a list can be changed by index assignment grammar: list[integer expression] = expression Example: x = [1, 2, 3, 4] x[2] = 1 + 2.14 # Changed the value of the third element print(x)
6. List slice operation
Slicing operations for lists 1.slice value list[start index:end index:step size] The value of the slice of the list is to take the desired elements from the original list and form a new one new list Example: L = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] y = L[1:10:2] # y = [1, 3, 5, 7, 9] 2.Slice assignment operation effect: You can change the arrangement of the original list,can be inserted,and modify data grammar: list[slice] = iterable object illustrate: assignment operator for slice assignment(=)The right side of must be an iterable Example: L = [2, 3, 4] L[0:1] = [1.1, 2.2] # L=[1.1, 2.2, 3, 4] L[0:2] = [2] # L = [2, 3, 4] L[1:2] = [3.1, 3.2] # L = [2, 3.1, 3.2, 4] L = [2, 3, 4] L[1:1] = [2.1, 2.2] # L = [2, 2.1, 2.2, 3, 4] L[0:0] = [0, 1] # L = [0, 1, 2, 2.1 ....] L = [2, 3, 4] L[3:3] = [5, 6] # L = [2, 3, 4, 5, 6] L = [2, 3, 4] L[1:2] = "AB" # L = [2, 'A', 'B', 4] L[1:3] = range(7, 10) # L = [2, 7, 8, 9, 4] 3.Notes on Slicing: Assignment to slices with stride not equal to 1,the iterable on the right-hand side of the assignment operator number of elements provided,Must be equal to the number of segments cut out by the slice L = [1, 2, 3, 4, 5, 6] L[::2] = "ABC" # correct L[::2] = "abcd" # Incorrect
1.del statement
del statement Can be used to delete elements of a list grammar: del list[integer expression] del list[slice] Example: L = [1, 2, 3, 4, 5, 6, 7, 8] del L[-1] # L = [1, 2, 3, 4, 5, 6, 7] del L[1::2] # L = [1, 3, 5, 7] practise: already has a list: L = [3, 5] Working with indexing and slicing,Change the original list to: L = [1, 2, 3, 4, 5, 6] reverse the list,The result is as follows: L = [6, 5, 4, 3, 2, 1] then remove the last element,The result is as follows : L = [6, 5, 4, 3, 2]
practise:
practise: write a program.Let the user enter many positive integers,End input when negative number is entered Store the numbers entered by the user in a list 1. print a list of numbers 2. find the average of these numbers 3. find the largest of the numbers like: please enter: 1 please enter: 2 please enter: 99 please enter: 100 please enter: -1 print as follows : list is: [1, 2, 99, 100] The average is: 55.5 The maximum number is: 100
2. Functions of sequences commonly used in python3
len(x) Returns the length of the sequence max(x) Returns the maximum element of the sequence min(x) Returns the smallest element in the sequence sum(x) Returns the sum of all elements in the sequence(Elements must be of numeric type) any(x) truth test.Returns if one of the values in the list is true True all(x) truth test.Returns if all values in the list are true True Example: L = ["Beijing", 1, 123] print(len(L)) # 3 L = [8, 3, 6, 2] print(max(L)) # 8 print(min(L)) # 2 print(sum(L)) # 19
3. List methods commonly used in python3 (method)
Documentation see: python_base_docs_html/list.html >>> help(list)
practise: write a program,Let the user enter many positive integers,When entering a number less than zero end input 1) print the largest of these numbers 2) print the second largest of these numbers 3) delete the smallest number
4. shallow copy and deep copy deep copy
1. Shallow copy
shallow copy Shallow copy refers to the process of copying,Copy only one level of variables,will not copy deep The copy process of the object bound by the variable like: L = [3.1, 3.2] L1 = [1, 2, L] L2 = L1.copy() # shallow copy print(L1) # [1, 2, [3.1, 3.2]] print(L2) # [1, 2, [3.1, 3.2]] L2[2][0] = 3.14 print(L1) # [1, 2, [3.14, 3.2]] print(L2) # [1, 2, [3.14, 3.2]]
2. Deep copy
deep copy deep copy like: import copy # import copy module L = [3.1, 3.2] L1 = [1, 2, L] L2 = copy.deepcopy(L1) # deep copy print(L1) # [1, 2, [3.1, 3.2]] print(L2) # [1, 2, [3.1, 3.2]] L2[2][0] = 3.14 print(L1) # [1, 2, [3.1, 3.2]] print(L2) # [1, 2, [3.14, 3.2]]
3. The difference between shallow copy and deep copy
1.Shallow copy only copies the reference address to an object, not the object itself, the old and new objects still share the same memory. 2.But deep copying will create another identical object, the new object does not share memory with the original object, and modifying the new object will not change the original object. Shallow copy only copies the properties of one level of object, while deep copy recursively copies all levels. import copy as cp L=[1,[2,3]] L1=cp.copy(L) #Shallow copy: just reference, and will not open up new memory space, L1 and L point to the same memory space. L Change,L1 also locks in changes. L2=cp.deepcopy(L) #Deep copy: It will re-create a memory space for data, and changes in L will not affect L2.
5. List and String Comparison
list to string comparison: 1. Both lists and strings are sequences,There is a sequence relationship between elements 2. Lists and strings have the same operations: + += * *= < > in ... 3. Strings are immutable sequences, lists are mutable sequences 4. Each element of a string can only store characters, while a list can store any type Elements 5. Both lists and strings are iterable objects
6. String text parsing methods split and join
Text parsing methods for strings split and join S.split(sep=None) use string sep split as delimiter s String, returns a list of split strings;When no parameters are given When counting, use a whitespace character as a delimiter S.join(iterable) Generates a medium from the strings in the iterable object Room use S delimited string Example: s = 'Beijing is Capital' L = s.split(' ') # L = ['Beijing', 'is', 'Capital'] s2 = "##".join(L) # s2 = "Beijing##is##Capital"
practise: has string "hello" generate new string: 'h e l l o' and 'h-e-l-l-o' s1 = ' '.join('hello') s2 = '-'.join('hello')
7. List comprehension
1.list comprehension list comprehesion List comprehensions are expressions that create lists from iterable objects effect: Create a list grammar: [ expression for variable in iterable object] or [ expression for variable in iterable object if truth expression] Example: generates a value of 1~9 list of squares L = [x**2 for x in range(1, 10)] # L = [1, 4, 9, 16 .... 64, 81] # Generate a list of squares of values 1 to 9 (as long as there are odd squares) L = [x**2 for x in range(1, 10) if x % 2 == 1] # L = [1, 9, 25, 49, 81] # The above list comprehension can be rewritten as: L = [] for x in range(1, 10): if x % 2 == 1: L.append(x**2) 2.List Comprehension Nested Syntax: [ expression for variable 1 in iterable object 1 if truth expression 1 for variable 2 in iterable object 2 if truth expression 2 .....] like: L = [x + y for x in "ABC" for y in "123"] # L = ['A1', 'A2', 'A3', 'B1', 'B2', 'B3', 'C1', 'C2', 'C3']
practise: 1. There are some numbers in the list,like: L = [1, 3, 2, 1, 6, 4, 2, ..... 98, 82] 1) Store numbers that appear in a list into another list L2 middle Require: Numbers that appear multiple times can only be found in L2 keep a copy(deduplication) 2) Store numbers that appear twice in a list in L3 List,exist L3 List keep only one 2.generate a list,beg x squared+1 list of,Skip results divisible by 5 number, (Note: 0 <= x <= 100) 3. put 0 ~ 100 All prime numbers between are stored in a list which is: L = [2, 3, 5, 7, 11, ..... 97]
day06 review:
list list How the list is created: literal value [], [1,2,3,4] Constructor: list() list("ABCD") derivation: [x**2+1 for x in range(10)] Operations on lists: + += * *= < <= > >= == != in, not in The index value and slice value rules are equivalent to the rules for strings Index assignment and slice assignment list[integer expression] = expression list[slice] = iterable object L[1:2] = range(10) serial correlation function: len(x) --> len(iterable object) max(x) --> max(iterable object), max(value 1,Numeric 2,...) min(x) sum(x) --> sum(iterable object) any(x) --> any(iterable object) all(x) --> all(iterable object) List of commonly used methods: L.append(x) append L.insert(index, data object) L.extend(iterable object) L.remove(data object) L.pop([integer index]) L.clear() L.count(data object) L.index(data object) Returns the position of the first occurrence L.sort(reverse=False) sort L.reverse() reverse String parsing method: S.split(sep=None) S.join(iterable object) list comprehension: [x**2 for x in range(10)] [x**2 for x in range(10) if x > 5] [x*y+2 for x in range(10) for y in range(20)] deep copy and shallow copy L = [1, 2, 3, [4, 5, 6]] L2 = L # Do not copy, give L's reference to L2 L3 = L.copy() # shallow copy import copy L4 = copy.deepcopy(L) # deep copy
Day07 Notes:
1. Tuple tuple
tuple tuple Tuples are immutable sequences,same list Same,Tuples can store any type data container Tabular methods for tuples: with parentheses() bracket,Surround individual elements with a comma(,)distinguish a single object or tuple Creates a literal value of an empty tuple: t = () # Create an empty tuple bound with t A literal that creates a non-empty tuple t = 200, # Create a tuple with only one number 200 with binding t = (20,) t = (1, 2, 3) t = 100, 200, 300 Bad example of created tuple: t = (20) t bind integer 20,not a tuple x, y, z = (100, 200, 300) # sequence assignment x, y, z = 100, 200, 300 x, y, z = [100, 200, 300] x, y, z = "ABC" # Sequence assignment, not tuple x, y = y, x # Swap the bindings of two variables type(x) function return x type tuple constructor tuple tuple() generates an empty tuple,Equivalent to() tuple(iterable) Generate a new tuple with an iterable object Example: t = tuple() t = tuple("ABC") t = tuple(range(1, 10, 3)) operations on tuples: + += * *= t = (1, 2, 3) + (4, 5, 6) # t=(1,2,3,4,5,6) t = (1,2,3) t += (4,5,6) # t = (1,2,3,4,5,6) t = (1,2) * 3 # t =(1,2,1,2,1,2) t = (1,2) t *= 3 comparison operation: < <= > >= == != The comparison rules are exactly the same as the comparison rules for lists in / not in operator equivalent to a list in / not in operator Indexing and Slicing The rules for indexing and slicing are exactly the same as for lists Note: Tuples do not support index assignment and slice assignment tuple methods see documentation: python_base_docs_html/tuple.html Sequence-related functions can also be used in tuples len(x), max(x), min(x), sum(x), any(x), all(x)
2. Dictionary dict
1. Dictionary dict (create)
dictionary dict what is a dictionary 1. A dictionary is a mutable container,Can store any type of data 2. Each data in the dictionary is represented by"key"(key) indexed,instead of like sequence(str,list,tuple)can be indexed with integers 3. The data in the dictionary has no sequence relationship,Dictionary storage is unordered 4. The data in the dictionary starts with the key(key)-value(value)store the form 5. Dictionary keys cannot be repeated,and can only use immutable types as dictionary keys The literal way of creating a dictionary: The dictionary is represented by{} bracket,with a colon(:) Delimited key-value pairs,each key Separate value pairs with commas Create empty dictionary: d = {} Create a non-empty dictionary: d = {"Name": "tarena", "age": 15} d = {"one": 1, "two": 2} d = {1: "One", 2: "two", 3: [1,2,3]} d = {"a": list(range(10))} d = {"a": {"b": 100, "c":[1, 2, 3]}} constructor that creates a dictionary dict: dict() # produces an empty dictionary equivalent to {} dict(iterable) Create a list with iterable objects dict(**kwargs) Generate a dictionary in the form of keyword arguments Example: d = dict() L = [ (1, 2), [3, 4], "AB" ] d = dict(L) # {1: 2, 3: 4, 'A': 'B'} d = dict(name="tarena", age=15) # d = {'age': 15, 'name': 'tarena'} Dictionary keys must be immutable values There are four types of variable: list(list), dict(dictionary), set(gather), bytearray(byte array) (In addition to the above four others are immutable types)
2. Basic dictionary operations
Basic dictionary operations 1.dictionary key index grammar: dictionary[key] effect: Get the value corresponding to the key of the dictionary with the key Example: d = {'name': 'tarena', 'age': 16} print(d['name'], "age is", d['age']) 2.Add and modify elements of a dictionary grammar: dictionary[key] = value illustrate: When the key does not exist,Create key,and let the key bind the corresponding value key exists,Modify the value of a key binding Example: d = {} d['name'] = "Xiao Zhang" # Add a key-value pair d['age'] = 20 # Add a key-value pair d['age'] += 1 # Modify the value corresponding to the 'age' key practise: write a program,Let the user enter a person's information twice: Information contains: name and phone number Let users have multiple personal information,End input when input name is empty Store the data entered by the user in a dictionary name as key, phone number as value Finally print the dictionary storing the data like: Please type in your name: Xiao Zhang Please enter phone: 13888888888 Please type in your name: Xiao Li Please enter phone: 13999999999 Please type in your name: <Enter> Print: {"Xiao Zhang": 13888888888, "Xiao Li": 13999999999} 3.remove dictionary element del statement grammar: del dictionary[key] Example: d = dict(name="Xiao Zhang", age=20) del d['age'] print(d) # {'name': 'Xiao Zhang'} 4.Dictionary key judgment in , not in operator Can use in operator to determine if a key exists in the dictionary,if it exists then return True, otherwise return False not in return value with in on the contrary E.g: d = {'name' : 'tarena', 'age': 15} 'name' in d # True 15 in d # False 'age' not in d # False practise: programming,fulfill the following requirements: 1. Form the following data into a dictionary seasons key value 1 ====> 'Spring has 1,2,3 moon' 2 ====> 'There are 4 in summer,5,6 moon' 3 ====> 'Fall has 7,8,9 moon' 4 ====> '10 in winter,11,12 moon' 2. Let the user enter an integer representing the quarter,print the corresponding quarter information,If the information entered by the user does not exist in the dictionary,prompt the user 'information does not exist'
3. Iterative access to the dictionary
iterative access to the dictionary Dictionaries are iterable objects,Dictionaries can only have iterative access to keys Example: d = {0:'zero', 5:'Wu', 1:'one', 2:'two'} for n in d: print(n) # 0, 1, 2, 5 functions that can be used with dictionaries: len(x) Returns the number of key-value pairs in the dictionary max(x) Returns the maximum value of the keys of the dictionary min(x) Returns the minimum value of the keys of the dictionary sum(x) Returns the sum of all keys of the dictionary any(x) truth test,Test only on keys,As long as there is a key with a true value the result is True all(x) truth test,The truth-valued result for all keys is True Example: d = {0:'zero', 5:'Wu', 1:'one', 2:'two'} len(x) ...
4. The dictionary method
dictionary method Documentation see: python_base_docs_html/dict.html Example: d = {0:'zero', 5:'Wu', 1:'one', 2:'two'} for t in d.items(): print(t) # (0, 'zero'), (1, 'one'), (2, 'two'), (5, 'wu') for k, v in d.items(): print("key is", k, 'value is', v) practise: Enter a string, print out the characters that have appeared in the string and the characters that have appeared in the string the number of times like: enter: abcdabcaba print as follows: a: 4 Second-rate b: 3 Second-rate d: 1 Second-rate c: 2 Second-rate Note: Print order is not required
5. Dictionary comprehension
dictionary comprehension Dictionary comprehensions are expressions that use iterable objects to create dictionaries grammar: {key expression: value expression for variable in iterable object [if truth expression]} Note: []The content of the representative can be omitted Example: generate a dictionary: key is number 0~9, value is the square of the key as generated {0: 0, 1:1, 2:4, 3: 9, ... 9:81} d = {x: x**2 for x in range(10)} print(d) dictionary comprehension nesting The syntax is the same as list comprehension nesting practise: A list of known strings like: L = ['Tarena', 'XiaoZhang', 'xiaowang'] Generate the following dictionary: d = {'Tarena':6, 'XiaoZhang':9, 'xiaowang':8} practise: Nos = [1001, 1002, 1005, 1006] names = ['Tom', 'Jerry', 'Spike', 'Tyke'] Try to generate the following dictionary: d = {1001: 'Tom', 1002: 'Jerry', 1005: 'Spike', 1006: 'Tyke'} Answer: d = {Nos[i]: names[i] for i in range(4)}
6. Dictionary VS List
dictionary VS list 1. are mutable containers 2. The indexing method is different, the list is indexed by integer, and the dictionary is indexed by key 3. The storage of lists is ordered, and the storage of dictionaries is unordered 4. Insertion, deletion, modification of dictionaries may be faster than lists(important) question: L = [1, 3, 5, 8, 10] for x in L: L.remove(x) print(L) # [3, 8]
practise: 1. Generate the first 40 Fibonacci numbers (Fibonacci sequence) 1 1 2 3 5 8 13 21 .... Require: store these numbers in a list Finally print out these numbers 2. There is a little monkey who picks a lot of peaches, I ate half of all the peaches on the first day, I didn't feel full and ate another one I ate the remaining half the next day and I didn’t feel full and ate another one and so on... By day 10, only one was left ask: How many peaches were picked on the first day? 3. print the nine-nine multiplication table: 1x1=1 1x2=2 2x2=4 1x3=3 2x3=6 3x3=9 .... ......................9x9=81 4. Enter as many student names as you want,age, grades,Information for each student Store it in a dictionary, then put it in a list. Information for each student needs to be entered manually: like: Please type in your name: tarena Please enter age: 15 Please enter grade: 99 Please type in your name: china Please enter age: 70 Please enter grade: 98 Please type in your name: <Enter> end input The internal storage format is as follows: infos = [{'name':'tarena', 'age':15, 'score':99}, {'name':'china', 'age':70, 'score':98}] 1. print the list above 2. Print student information in the form below +---------------+-----------+----------+ | Name | age | score | +---------------+-----------+----------+ | tarena | 15 | 99 | | china | 70 | 98 | +---------------+-----------+----------+
day07 review
two container classes tuple tuple dictionary dict tuple Can be understood as an immutable list(sequence container) How to create a literal value () 20, (20,) 100,200,300 (1,2,3) How to create a constructor: tuple() , tuple(iterable object) operations on tuples: + += * *= < <= > >= == != in / not in operator index/slice value(Assignment is not supported) dictionary dict Variable, can store any type of,unordered container key-value pair(key-value) Dictionary keys are immutable and non-repeatable How to create a literal value {} {1:"one"} {1:"one", 2:'two'} derivation: {key expression : value expression for variable in iterable object if...} Constructor way: dict() dict(iterable object) dict(keyword argument) dict(iterable) dict(**kwargs) operation: variable = dictionary[key] # value dictionary[key] = expression # Add/modify the value corresponding to the key del statement to delete the key-value pair from the dictionary del dictionary[key] in , not in operator method in dictionary D.clear() D.pop(key) remove D.get() D.copy D.keys() D.values() D.items() ...
Day08 Notes:
1. Collection set
1. Collection set (create)
gather set Collections are mutable containers Data objects within a collection are unique(cannot be repeated many times) Collections are unordered storage structures,The data in the collection is not sequential The elements inside the collection must be immutable objects Collections are iterable(Can use for statement traversal) A collection is equivalent to a dictionary with only keys and no values(The key is the collection's data) The constructor that creates the collection set() Create an empty collection object(The ____ does not work{}to create an empty collection) set(iterable) Use iterable objects to create new collection objects Example: s = set() # s bind empty collection set() s = set(range(1, 5)) # s = {1, 2, 3, 4} s = set("hello") # s = {'e', 'o', 'h', 'l'} Note: For non-empty collections {} bracket,Use commas for each element inside(,)separated Literal way to create a non-empty collection s = {1, 2, 3, 4} s = set("ABCCBA") s = set({1:"one", 3:"three", 8:"Eight"}) s = set([1, 3.14, "ABC"]) s = {True, None, "ABC", (1, 2, 3)} s = {True, None, "ABC", [1, 2, 3]} # error
2. Operations on sets
set operations: intersection & union| Complement- Symmetric complement^ Subset< superset> 1. & Generate the intersection of two sets s1 = {1, 2, 3} s2 = {2, 3, 4} s3 = s1 & s2 # s3 = {2, 3} 2. | Generate the union of two sets s1 = {1, 2, 3} s2 = {2, 3, 4} s3 = s1 | s2 # s3 = {1, 2, 3, 4} 3. - generate the complement of two sets s1 = {1, 2, 3} s2 = {2, 3, 4} # Generates the set of all elements with attribute s1 but not in s2 s3 = s1 - s2 # s3 = {1} s3 = s2 - s1 # s3 = {4} 4. ^ generate the symmetric complement of two sets s1 = {1, 2, 3} s2 = {2, 3, 4} s3 = s1 ^ s2 # {1, 4} 5. < Determine if a set is a subset of another set > Determine if a set is a superset of another set s1 = {1, 2, 3} s2 = {2, 3} s2 < s1 # True s1 > s2 # True s3 = {3, 4, 5} s1 > s3 # False s1 < s3 # False s1 == s3 # False 6. == != Determine whether the sets are the same or different {1, 2, 3} != {3, 2, 1} # False 7. >= <= 8. in , not in operator equivalent to a list in operator s1 = {1, 2, 3} 3 in s1 # True
Advantages of sets and dictionaries: in / not in Operators operate faster Built-ins that can be used for collections(built-in)function: len(x) max(x) min(x) sum(x) any(x) all(x) practise: manager has: Cao Cao, Liu Bei, Sun Quan technicians have: Cao Cao,Sun Quan,Zhang Fei,Guan Yu use set: 1. Who is the manager and the technician?? 2. is the manager,but anyone who is not a technician? 3. is a technician,but anyone who is not a manager? 4. Is Zhang Fei the manager?? 5. Who is the person who holds the job? 6. How many managers and technicians are there in total?
3. Commonly used collection methods in python3
python3 Commonly used collection methods in: Documentation see: python_base_docs_html/set.html Collections are iterable objects
4. Set comprehension
set comprehension Collection comprehensions are expressions that create collections from iterable objects grammar: { expression for variable in iterable object [if truth expression]} Note:[] Represents the contents of which can be omitted Example: L = [1, 1, 2, 2, 3, 3, 4, 5, 6, 7, 7] s = {x ** 2 for x in L} Nesting of set comprehensions is equivalent to nesting of list comprehensions
2. Fixed set frozenset
Fixed collection frozenset Fixed collections are immutable,disordered,A collection with unique elements effect: Fixed collections can be used as dictionary keys,Can also be used as a set value Fixed collection constructor frozenset frozenset() Create an empty fixed collection frozenset(iterable) Create a new fixed with an iterable object gather Example: fz = frozenset() fz = frozenset("hello") fz = frozenset([1,2,3,4,3,4,5])
1. Operations on fixed sets
Operations on Fixed Sets: intersection & union | Complement - Symmetric complement ^ in / not operator < <= > >= == != (The above operator usage is equivalent to set usage in) Ways to fix a collection,Equivalent to all methods of collections, except methods that modify collections
3. Staged summary
Staged summary: type of data immutable data type bool, int, float, complex, str, tuple frozenset, bytes(byte string,learn later) mutable data type list, dict, set, bytearray(byte array,I'll talk about it later) value: None, False, True operator: + - * / // % ** > >= < <= == != in / not in is / is not not and or & | ^ +(Positive sign) -(negative) [] # Indexing and Slicing expression: 1 True 1 + 2 * 3 print("hello") # function call L.pop(2) # Method calls are also expressions sum([1, 2, 5, 10]) conditional expression: x if x > y else y all derivations: list,dictionary,set comprehension(three) statement: expression statement(Expressions can form expression statements on a single line) print("hello") "this is a text" assignment statement: a = 100 a = b = c = 200 x, y, z = 1, 2, 3 del statement if statement while statement for statement break statement continue statement pass statement built-in function: len(x) max(x) min(x) sum(x) any(x) all(x) --------- Constructor ------- bool(x) int(x) float(x) complex(x) str(x) list(x) tuple(x) dict(x) set(x) frozenset(x) ------------------- abs(x) round(x, y) pow(x, y, z=None) -------------------- bin(x) oct(x) hex(x) chr(x) ord(x) -------------------- range(start, stop, step) ----Basic input and output functions-- input(x) print(....) -------------------- id(x) return memory address type(x) return type
2.5 Python functions
4. function function
1.function function what is a function A function is a block of statements that can be executed repeatedly,Can be called and executed repeatedly A function is the smallest unit of procedural programming effect: Used to encapsulate statement blocks,Improve code reusability Define user-level functions Improve code readability and maintainability 2.def statement: grammar: def Function name(parameter list): statement block effect: create a function,pack statement blocks,bind with function name,used to call illustrate: 1. The naming rules for function names are the same as for variable names(must be an identifier) 2. function name is a variable,it is used to bind functions 3. Functions have their own namespace,Can't access inside a function from outside the function Department variables,Variables outside the function can be accessed inside the function,but not right external variable assignment 4. Statement part cannot be empty.If it is empty, it needs to be filled in pass statement 5. If the function does not need to pass in parameters,The parameter list can be empty 3.function call: grammar: Function name(The actual call passes the parameters) illustrate: A function call is an expression If there is no inside the function return statement,Return after the function has finished executing None object reference For example see: def.py mymax.py
practise: 1. write a function myadd, There are two parameters in the parameter list in this function number x, y The function of this function is to print x + y the sum def myadd(...): ... myadd(100, 200) # 300 myadd("ABC", "123") # ABC123 2. write a function print_even,pass in a parameter n Represents a terminating integer print 2 4 6 8 .... n all even numbers between(Include n) The function is defined as follows: def print_even(n): .... # Do it yourself here print_even(8) # Print: 2 4 6 8
5.return statement
return statement grammar: return [expression] Note: [] Represents the contents of which can be omitted effect: used in function,end the execution of the current function,return to the caller of the function place,Also returns a reference to an object illustrate: 1. return The expression following the statement can be omitted,equivalent after omission At return None 2. There is no inside the function return statement,the function executes the last return after statement None(It is equivalent to adding a line at the end return None statement) For example see: return.py
practise: 1. write a function mymax, The implementation returns the maximum value of three numbers: like: def mymax(a, b, c): ... print(mymax(100, 200, 300)) # 300 print(mymax("ABC", 'abc', '123')) # abc 2. write a function myadd()Implementation gives two numbers,returns the sum of these two numbers like: def myadd(x, y): .... a = int(input("Please enter the first number: ")) b = int(input("Please enter a second number: ")) print("The sum of the two numbers you entered is:", myadd(x, y)) 3. write a function input_number def input_number(): .... # Do it yourself here This function is used to get the integer input by the user loop,End input when negative number is entered Return the numbers entered by the user as a list,Reuse built-in functions max,min, sum Find the maximum value of the number entered by the user,min and sum,like: L = input_number() print("The maximum number is:", max(L)) print("The minimum number is:", min(L)) print("and yes:", sum(L))
practise: 1. Create two functions def sum3(a, b, c): # returns the sum of three numbers .... def pow3(x): # used to return the cube of x ... Use the above two functions to calculate: 1. Calculate the cube of 1 + 2 cube + 3 sum of cubes 2. Calculate 1+2+3 the sum of the cube which is: 1**3 + 2**3 + 3 ** 3 and (1+2+3)**3 2. Rewriting previous student information management procedures,Encapsulated as two functions: def input_student(): # This function is used to return a list of all user entered student information ... def output_studentn(L): # This function prints student information in tabular form ... The following is the call(The function and printing effect are the same as before): infos = input_student() print(infos) output_studentn(infos) 3. write function,Calculate the sum of the following polynomials: Sn = 1/(1*2) + 1/(2*3) + 1/(3*4) + ... ... + 1/(n*(n+1)) def Sn(n): ... print(Sn(3)) # 0.75 print(Sn(1000)) # ???
day08 review
two container classes gather set, Fixed collection frozenset Creation of collections set() set(iterable object) {1, 2, 3, 4} set comprehension: {expression for variable list in iterable object if ...} Creation of fixed collections frozenset() frozenset(iterable object) Collection features: disorder, not repeatable,can only store immutable objects set operations: & | - ^ < > <= >= == != in, not in, is, is not(Judging is id) collection method: S.add(x) Add to: S.remove(x) S.discard(x) S.clear() S.pop() two sentences def statement create a function,Use function variables to bind functions,The purpose is to later to repeat the call return statement grammar: return expression
Day09 Notes:
1. Passing parameters of functions (passing data to functions)
function parameters(pass data to the function) function parameters(Receive data from function call) python function parameter passing delivery method: 1. location parameter 1.1 serial parameter 2. keyword argument 2.1 dictionary keyword argument
1. Location parameter
location parameter: actual parameters(Arguments) The correspondence and formal parameters of(formal parameter)The corresponding relationship is Corresponding by location. For example see: position_give_args.py illustrate: Arguments and formal parameters are passed and matched by position The number of actual parameters must be the same as the number of formal parameters
2. Sequence parameter transfer
serial parameter: Sequence parameter passing refers to the process of calling a function,use*(Asterisk) After disassembling the sequence The way of passing parameters by position illustrate: When passing parameters in sequence,The position of the sequence disassembly will correspond to the formal parameters one-to-one For example see: sequence_give_args.py
3. Keyword parameters
keyword argument: The keyword parameter refers to the time when the parameter is passed,Assign a value to a parameter by its name Arguments and formal parameters are matched by name illustrate: Can not match by location For example see: keywords_give_args.py
4. Dictionary keyword parameters
dictionary keyword argument: means that the argument is a dictionary,use the dictionary** After dismantling, pass keyword parameter transmission delivery method illustrate: The key name and parameter name of the dictionary must be the same The key name of the dictionary must be a string that conforms to the naming rules for identifiers The key name of the dictionary must exist in the formal parameter For example see: dict_keyword_give_args.py
5. Comprehensive parameter transfer of functions
Synthesis of function parameters: 1. The way of passing parameters of a function is to ensure that the formal parameters can uniquely match the corresponding actual parameters. can be combined in any 2. The positional parameters of the function should be passed before the keyword parameters. Example: def myfun(a, b, c): pass myfun(100, *[200, 300]) myfun(100, *"BC") myfun(*"AB", 300) myfun(*[100], 200, *[300]) myfun(100, c=300,b=200) myfun(a=100, 200, c=300) # Incorrect myfun(100, **{'c':300, 'b':200}) myfun(100, **{'c':300}, b=200) myfun(100, b=200, **{'c':300})
practise: write a function minmax,Pass in three parameters,Returns the maximum and minimum of these three parameters small value element,result requirements,form tuple minimum first,The maximum value is returned after to the caller like: def minmax(a, b, c): .... The result of the call is as follows: t = minmax(300, 100, 200) print(t) # (100, 300)
2. The default parameters of the function
function default arguments grammar: def Function name(parameter name 1=Default argument 1, parameter name 2=Default argument 2, parameter name 3=Default argument 3, .....) effect: Let the caller of the function pass fewer parameters to call the function For example see: default_args.py illustrate: 1. Default parameters must exist in order from right to left,If a parameter has a default parameter, then all parameters to the right of it must have default parameters 2. The default parameter can have 0,1 one or more,even all have default parameters like: def fn(a, b=10, c): # mistake pass def fn(a=0, b=None, c=False): # it's right pass
practise: write a function,myadd,This function can pass two,three or four arguments The function of this function is to calculate the sum of all actual parameters like: def myadd(...): .... print(myadd(10, 20)) # 30 print(myadd(100, 200, 300)) # 600 print(myadd(1, 2, 3, 4)) # 10
1. The passing of variable and immutable arguments of functions
Passing of variadic and immutable arguments to functions For example see: variable_args.py variable_args2.py illustrate: When a mutable object is passed into a function via a function argument,inside the function Mutable objects can be manipulated through local variables(list,dictionary,gather...)
interview questions: What is the result of trying the following program, why? L = [1, 2] def fn(a, lst=[]): lst.append(a) print(lst) fn(3, L) # [1, 2, 3] fn(4, L) # [1, 2, 3, 4] fn(5) # [5] fn(6) # [5, 6] fn(7) # [5, 6, 7]
3. How the function parameters are defined
How function parameters are defined positional parameter Asterisk tuple parameter Named Keyword Parameters Double asterisk dictionary parameter
1. Positional parameters
positional parameter: grammar: def Function name(formal parameter variable 1, formal parameter 2, ....): statement block
2. Asterisk tuple parameter
Asterisk tuple parameter grammar: def Function name(*tuple parameter name): statement block effect: Collect redundant location parameters illustrate: Tuple parameter names are generally named as'args' *A function can only have one tuple parameter For example see: star_tuple_args.py
practise: write a program, mysum Arbitrary parameters can be passed in, The function of this function is to return the sum of all arguments def mysum(*args): .... print(mysum(1,2,3,4)) # 10 print(mysum(1,2,3)) # 6
3. Named Keyword Parameters
Named Keyword Parameters grammar def Function name(*,named keyword parameter 1, named keyword parameter 2,..): statement block or def Function name(*args,named keyword parameter 1, named keyword parameter 2,..): statement block effect: Forces all named keyword parameters to pass keyword or dictionary key parameter For example see: named_keywords_args.py
think: print() How is the parameter list of a function defined? practise: known built-in functions max The binding document is: max(...) max(iterable)---> value max(args1, arg2, *args) --> value counterfeit max function, write a max function exactly the same mymax function (Require: Internal keys are not allowed to be called max function) like: def mymax(...): ... print(mymax([6, 8, 3, 5])) # 8 print(mymax(100, 200)) # 200 print(mymax(1, 3, 5, 9, 7)) # 9 print(mymax()) # report an error
4. Double asterisk dictionary parameter
Double asterisk dictionary parameter grammar: def Function name(**dictionary parameter name): statement block effect: Collect redundant keyword arguments illustrate: Dictionary parameter names are generally named as'kwargs' There is at most one dictionary parameter in a function For example see: dict_kwargs.py
5. Formal parameter description of the function
1.Formal parameter description of the function: Positional parameters, default parameters, asterisk tuple parameters, double asterisk dictionary parameters can be mixed combined use 2.The definition order of function parameters from left to right is: positional parameter Asterisk tuple parameter Named Keyword Parameters Double asterisk dictionary parameter Example: def fn(a, b, *args, c, **kwargs): pass fn(1, 2, 3, 4, c=30, d=40, e=50) 3.Variable-length arguments to functions: There are two: Asterisk tuple parameter, double asterisk dictionary parameter Arbitrary parameters can be received with variable length parameters like: def fn(*args, **kwargs): print(args, kwargs)
4. Global and local variables
Global and local variables 1.local variable 1. Variables defined inside a function are called local variables(The formal parameters of the function are also local variable) 2. Local variables can only be used inside functions 3. Local variables can only be created when the function is called, and will be created after the function is called. automatic destruction 2.global variable 1. defined outside the function,Variables inside a module are called global variables 2. All functions can directly access global variables(But inside the function you can't its direct assignment) illustrate: Assignment statements inside functions do not affect global variables
practise: 1. write a function get_chinese_char_count(s),of this function function is given a string,Returns the number of Chinese characters in this string like: def get_chinese_char_count(s): ... s = input("Please enter a Chinese-English mixed string:") print('The number of Chinese you entered is', get_chinese_char_count(s)) Note: Chinese characters are encoded at 0 x4E00-0x9FA5 between 2. write a function isprime(x) judge x Is it a prime number.if prime return True,otherwise return False like: print(isprime(3)) # True print(isprime(4)) # False 3. write a function prime_m2n(m, n) return from m start,arrive n Finish list of all prime numbers in the range,and print the corresponding list (does not contain n) like: def prime_m2n(m, n): ... L = prime_m2n(10, 20) print(L) # [11, 13, 17, 19] 4. write a function primes(n) Returns all prime numbers in the specified range (does not contain n)list of,print a list of these prime numbers, like: def primes(n): ... L = primes(10) print(L) # [2, 3, 5, 7] 1) print prime numbers up to 100 2) print the sum of all prime numbers up to 200 5. write a myrange function,The parameter can be passed 1~3 indivual,actual meaning and range The function rules are the same,This function returns the range function rule list of like: L = myrange(4) print(L) # [0, 1, 2, 3] L = myrange(4, 6) print(L) # [4, 5] L = myrange(1, 10, 3) print(L) # [1, 4, 7]
day09 review
pass parameters(Arguments), pass data to the function(Give) formal parameter,Receive arguments from where the function was called(take) Parameters: location parameter sequence parameter function name(*sequence) keyword argument Dictionary keyword parameter function name(**dictionary) When passing parameters,Difference between mutable and immutable objects Immutable objects are not modified inside functions function parameters: Default parameter: def f1(a=1, b=2): pass f1() f1(100) f1(100, 200) How the formal parameters of the function are defined positional parameter *tuple parameter Named Keyword Parameters ** dictionary parameter Global and local variables
Day10 Notes:
1.globals() function and locals function
globals() function and locals function globals() Returns a dictionary of variables in the current global scope locals() Returns a dictionary of variables in the current local scope For example see: globals_local.py
2. Function variables
function variable function name is variable,It binds a function when the function is created For example see: function_variable.py function_variable2.py A function can act as an argument passing of another function You can assign a function to another function,The parameter variable of another function will be bind argument function For example see: func_give_func.py func_give_func2.py #Understand the following code and judge the result def myinput(fn): L = [1, 3, 9, 5, 7] return fn(L) print(myinput(max)) # 9 print(myinput(min)) # 1 print(myinput(sum)) # 25 #A function can act on the return value of another function For example see: return_function.py
practise: Write an interpretation executor that calculates the formula The following functions are known: def myadd(x, y): return x + y def mysub(x, y): return x - y def mymul(x, y): return x * y ... have a function that returns a function def get_func(s): '''This function function is,Pass in a string with s bind,according to s of The value is returned to the corresponding function above, like s == '+'or s=='add' return myadd ''' .... Implement this function yourself The program in the main function is as follows: def main(): while True: s = input("Please enter the calculation formula: ") # 1 plus 2 L = s.split() # L = ['1', 'Add', '2'] a = int(L[0]) b = int(L[2]) fn = get_func(L[1]) print("turn out:", fn(a, b)) # The result is: 3 main() # call the main function
3. Nested definitions of functions
Nested definitions of functions A function nested definition refers to a function that uses def statement to create other functions For example see: function_embed_define.py
4. The scope of python
1.python scope of The scope is also called the namespace, which is the namespace of the variable to find when accessing the variable 2.python The four scopes in LEGB see table below: For example see: namespace.py
scope | English explanation | English abbreviations |
---|---|---|
local scope | Local(function) | L |
outer nested function scope | Enclosing Fucntion local | E |
The scope of the module (file) where the function definition is located | Global(module) | G |
Scope of Python's built-in modules | Builtin(python) |
Lookup rules for variable names L ---> E ---> G ----> B Note: by default,variable name assignment creates or changes the current scope Binding relationship of internal variables
1.global statement
global statement effect: 1. tell the interpreter,global one or more variables declared by the statement,This Some variables are scoped at the module level,also known as global variable 2. global declaration(global) Map the variables of the assignment statement to the module text Scope inside the file grammar: global variable name 1, variable name 2, .... For example see: global.py illustrate: 1. If a global variable is to be assigned inside a function,must be declared globally (Otherwise it will be considered a local variable) 2. Global variables can be accessed directly without declaration inside the function(value) 3. cannot create local variables first,reuse global declared as a global variable,this this practice is against the rules 4. global The variable name in the variable list cannot appear in the formal parameter column of the function Inside and outside
2.nonlocal statement
nonlocal statement effect: tell the interpreter, nonlocal The declared variable is not a local variable,neither global variable,but a variable inside the outer nested function grammar: nonlocal variable name 1, variable name 2, .... For example see: nonlocal.py illustrate: 1. nonlocal Statements can only be used inside nested functions 2. right nonlocal Assigning a variable will scope the outer nested function operate on variables within 3. When there are two or more levels of function nesting,access nonlocal variable Only operate on the nearest layer of variables 4. nonlocal The variable name in the variable list of the statement cannot appear here in the parameter list of the function
practise: Log a function with global variables hello the number of times it was called Part of the code is as follows: count = 0 def hello(name): print("Hello", name) ... # Do it yourself here hello("Xiao Zhang") hello("Xiao Li) print("hello function is called", count, "Second-rate") # 2
def The purpose of the statement is to create a function
5.lambda expressions (aka anonymous functions)
lambda expression(aka anonymous function) effect: Create an anonymous function object same def similar,but don't provide the function name grammar: lambda [function parameter list]: expression For example see: lambda.py illustrate: 1. lambda A function created by an expression can only contain one expression 2. lambda simpler than functions,and can be created and destroyed at any time,beneficial to Reduce program coupling
practise: 1. write a lambda expression fx = lambda n: ..... the function judgment created by this expression n the square of this number+1 Is it divisible by 5, return if divisible True,otherwise return False print(fx(3)) # True print(fx(4)) # False 2. write a lambda expressions to create functions,This function returns two parameters maximum number def mymax(x, y): .... mymax = lambda ..... print(mymax(100, 200)) # 200 3. See what the following program is doing?what's the result ? def fx(f, x, y): print(f(x, y)) fx((lambda a, b: a + b), 100, 200) fx((lambda x, y: x**y), 3, 4)
6. The eval function and the exec() function
eval function and exec() function eval(source, global=None, local=None), put one string source Executed as an expression,return expression result after row exec(source, global=None, local=None) put one string source execute as a program For example see: eval.py exec.py eval2.py
practise: 1. give a number n,write a function mysum to calculate 1 + 2 + 3 + .... + n the sum require a function to do like: print(mysum(100)) # 5050 2. give a number n,write a function myfac to calculate n!(n factorial of) n! = 1 * 2 * 3 * ... * n print(myfac(5)) # 120 3. give a number n,write a function: 1 + 2**2 + 3**3 + .... + n**n the sum 4. Realization of student information management program with interface The interface is as follows: +----------------------+ | 1) Add student information | | 2) View Student Information | | 3) Delete student information | | 4) Modify student grades | | q) quit | +----------------------+ please choose:1 Please enter student name: xiaozhang Please enter student age: 20 Require each function to write a function corresponding to it(Reuse previous student information hypervisor)
day10 review
local variable global variable locals() globals() def fa(a, b): pass A function can be passed as a parameter to another function def fx(fn): pass fx(max) # pass in a function A function can be the return value of another function def fx(): return max m = fx() # This function call returns a max function def fy(): def hello(): print("hello") return hello h = fy() h() # this function nested definition python four scopes: local scope outer nested function scope global scope Scope of built-in modules global statement nonlocal statement def statement creation function lambda expression myadd = lambda x, y: x + y eval(s) function ... expression ... exec(s) function ... statement(program) ...
Day11 Notes:
2.6 Functional programming in Python
1. Functional programming
1.functional programming Functional programming is the use of a series of functions to solve a problem benefit: 1. Use each function to complete small functions, and any combination of a series of functions can complete large problems 2. Functions only take input and produce input, without any internal state that can affect output 2.reentrancy of functions If the input parameters of a function are certain, the function that returns a certain result is called a reentrant function Example: # Reentrant function, the incoming parameters must be. the result must be def myadd(x, y): return x + y # Non-reentrant functions: y = 200 def myadd2(x): return x + y print(myadd2(10)) # 210 y = 300 print(myadd2(10)) # 310 3.Functional programming requirements: def It is best not to create functions that access variables outside the local scope, so as to ensure the uniqueness of the returned results(reentrancy)
2. High Order Function
Higher order functions High Order Function What is a higher order function: A higher-order function is a function that satisfies one of the following conditions 1. A function accepts one or more functions passed in as parameters 2. function returns a function python Built-in higher-order functions: map, filter, sorted see details: python_base_docs_html/built-in function(builtins).html
1.map function
map function: Format: map(func, *iterables) For example see: map.py practise: 1. use map function: 1**3 + 2**3 + 3 ** 3 + .... 9**3 the sum 2. use map function: 1**4 + 2**4 + 3 ** 4 + .... 20**4 the sum hint: sum(map(.....))
2.filter function
filter function: filter(function, iterable) filter For example see: filter.py practise: 1. will 1 ~ 20 for even numbers filter After generating the iterable object, put the number generated by the iterable object into the list L middle 2. write a function is_prime(x) judge x Is it a prime number use filter function prints out: 20 ~ 30 all prime numbers between
3.sorted function
sorted function: effect: Sort the data of the original iterable object to generate a sorted list Format: sorted(iterable, key=None, reverse=False) illustrate: iterable iterable object key The function is used to provide a value, which will be used as the basis for sorting reverse The flag is used to set whether to sort in descending order For example see: sorted.py practise: names = ['Tom', 'Jerry', 'Spike', 'Tyke'] Sort by reverse order of strings: 'moT' yrreJ ekipS ekyT result: ['Spike', 'Tyke', 'Tom', 'Jerry']
3. Recursive function recursion
1.recursive function recursion: A function calls itself directly or indirectly recursive example: # function calls itself directly def f(): f() # call yourself f() # function calls itself indirectly def fa(): fb() def fb(): fa() fa() 2.Recursion Description: Recursion must control the number of recursive layers, and terminate recursion when certain conditions are met Almost all recursion can be used while loop instead 3.Advantages and disadvantages of recursion: advantage: Recursion simplifies the problem, makes the thinking clearer and the code more concise shortcoming: Recursion is greatly affected by the system environment. When the recursion depth is too large, unpredictable results may be obtained. 4.two stages of recursion recursion stage: Starting from the original problem, according to the recursive formula, recursion from the unknown to the past, and finally reach the termination condition of the recursion regression phase: find the result according to the recursive termination condition,Reverse step by step into the recursive formula.return to the original problem For example see: recursion.py recursion_fac.py
practise: write function mysum(n)summation recursively def mysum(n): # sum recursively ... print(mysum(100)) # 5050 thinking questions: Five friends are known to be together The fifth friend is 2 years older than the fourth friend The fourth friend is 2 years older than the third friend The third friend is 2 years older than the second friend The second friend is 2 years older than the first friend First friend said it was 10 years old
4. Closure closure
Closure closure 1.what is a closure: A closure is a function that refers to a variable outside this function illustrate: In essence, a closure is an object that binds together the inner nested function and the execution environment outside the function 2.A closure must satisfy three conditions: 1. There must be an inline function 2. Inline functions must reference variables in outer functions 3. The return value of the external function must be an inline function For example see: closure.py # For the application of closures see: closure2.py
practise:
1. Five friends are known to be together
The fifth friend is 2 years older than the fourth friend The fourth friend is 2 years older than the third friend The third friend is 2 years older than the second friend The second friend is 2 years older than the first friend First friend said it was 10 years old Write a program to print out the fifth friend with a third friend age
2. known list:
L = [[3, 5, 8], 10, [[13, 14], 15, 18], 20] 1) write a function print_list(lst) print out all elements print(L) # print 3 5 8 10 13 14 .... 2) write a function sum_list(lst) Returns the sum of all elements in this list print(sum_list(L)) # 86 Note: type(x) The type that can return a variable like: >>> type(20) is int # True >>> type([1, 2, 3]) is list # True 3. Rewriting previous student information management procedures Request to add four features: | 5) High grade by student-Low show student information | | 6) Low grade by student-High display student information | | 7) Highest by student age-Low show student information | | 8) By student age-High display student information |
day11 review
Higher order functions map, filter, sorted recursion recursion Closure closure
Day12 Notes
1. Decorators decorators (professional improvement)
1.decorator decorators(Professional Improvement) A decorator is a function whose main function is to wrap another function or class(later) The purpose of decoration is to not change the original function name(or class name) In the case of changing the behavior of the wrapped object 2.function decorator A function decorator means that the decorator passes in a function and returns a function. grammar: def Decorator function name(parameter): statement block return function object @Decorator function name<newline> def Function name(parameter list): statement block For example see: mydeco1.py mydeco2.py mydeco3.py mydeco4.py
2. The docstring of the function
docstring of the function The first string within a function that is not assigned to any variable is the function's docstring grammar: def Function name(parameter list): 'function docstring' function statement block Example: def myfun(name, x): '''This is the docstring of the function name Indicates a person's name x Indicates the amount of money ''' pass >>> help(myfun) illustrate: 1. The docstring is usually used to describe the function and usage of this function 2. Type in interactive mode: help(Function name) function can be viewed'docstring' 3. A function's docstring is bound in the function's __doc__ attribute functional __doc__ Attributes docstrings for binding functions docstrings for binding functions
3. Complete syntax of function definition statement (def statement)
function definition statement(def statement) full syntax of: [@decorator 1] [@decorator 2] [...] def Function name([positional parameter], [*tuple parameter], [Named Keyword Parameters], [**dictionary parameter]): '''docstring''' statement block Note: [] Represents its internal can be omitted
2.7 Modules
4. Module Module
module Module what is a module: A module is a collection of data,function,Program group composed of classes, etc. A module is a file, and the module file name usually starts with.py end. effect: Let some related data, functions, classes, etc. be logically organized together to make the logical structure clearer data in the module,Functions, classes, etc. can be provided to other modules or programs for use Classification of modules: Built-in modules(builtins) can be used directly in the parser Standard library modules, Install python installed and ready to use third-party modules(Usually open source),Need to install by yourself User-written modules(Can be used as a third-party module for others)
5. Module import statement
1.import statement
module import statement import statement grammar: import module name 1 [as Module new name 1], module name 2 [as Module new name 2], .... Example: import math # import math module import sys, os effect: Import a module as a whole into the current module usage: module name.property name or module name.function property name(actual parameter) like: math.factorial(5) dir(obj) The function returns a list of strings of all properties help(obj) The function can view the relevant docstring of the module practise: 1. Enter the radius of a circle and print the area of the circle 2. Enter the area of a circle and print the radius of the circle (request math Function and data implementation within modules)
2.from import statement
from import statement grammar: from module name import module attribute name 1 [as property new name 1], module attribute name 2 [as property new name 2], .... effect: Import one or more properties of a module into the scope of the current module Example: from math import factorial as fac from math import sin from math import pi print(fac(5)) # 120
3.from import * statement
from import * statement grammar: from module name import * effect: Import all properties of a module into the current module Example: from math import * print(sin(pi/2)) print(factorial(5))
6.dir function
dir function: dir([object]) returns a list of strings illustrate: If called with no arguments, returns a list of all variables in the current scope If an object is given as a parameter, returns a list of all variables of this object 1) For a module, returns all properties of the module 2) For a class, return all variables of this class, and recurse all variables of the base class object 3) For other objects, return all class variables and base class variables
7. Built-in modules
built-in module 1.math module module name math see details: python_base_docs_html/math module math.html 2. time module time module name: time see details: python_base_docs_html/time module time.html practise: Write a program that inputs your date of birth, 1) Figure out how many days you've been born? 2) Figure out what day of the week you were born? 3.system module sys Documentation see: python_base_docs_html/system module sys.html
practise: 1. Please write a function fun Its function is to compute the sum of the following polynomials: fn = 1 + 1/1! + 1/2! + 1/3! + 1/4! + .. + 1/n! (of mathematical modules factorial accomplish) beg n When equal to 100,fn the value of take a look fn(100)what is the value of 2. Write a program to format an electronic clock: HH:MM:SS format display time request to change every second 3 write function f(n)find the sum of the next polynomial fn = 1/1 - 1/3 + 1/5 - 1/7 + 1/9 .... 1/(2*n-1)the sum beg n When the value is 1000000, 1) Print f(1000000) the value of 2) Print f(1000000) * 4 value to see what
day12 review
decorator decorator function: def decorated function name(fn): ... return function like: def mydeco(fn): return fn @mydeco def fun(): print("fun function is called") fun = mydeco(fun) Example: def mydeco(fn): def fx(a, b): print("++++++") fn(a, b) print('------') return fx @mydeco def fun(x, y): pass fun(100, 200) function name and function call def fun(): pass print(fun) # print function bound by fun print(fun()) # Call the function bound by fun and print the return result of the function docstring of the function def fx(): '''docstring''' used for help() helper function function object __doc__property binding docstring module concept A module is a collection of data,function,Program group composed of classes, etc. import import import statement: import statement import math, sys, time from import statement from math import sin,cos, pi from import * statement from math import * dir() function help() function Use of modules: math module time module sys module
Day13 Notes
1. Customize the module and import
1.custom module and import Require: Module filename suffix must start with .py end Module filenames must be valid identifiers Avoid name conflicts with builtin module names Import method: import statement from import statement from import * statement For example see: mymod.py 2.import The path order in which the statement looks for module files import module name # where to find this "modulename.py" 1. Search for built-in modules 2. The path to search for when the program is running(current path) 3. sys.path provided path sys.path is a list,The internal storage is the search path of the module >>> import sys >>> print(sys.path) 3.Install third-party modules or packages pip3 install module name Let import Statement can find its own module 1. Put your own modules in sys.path in a folder in 2. Revise sys.path list,A string to add a folder inside (Note:This method only works for the current program) like: import sys sys.path.append('/home/tarena') For example see: test_mymod2.py
2. Modular programming advantages
Advantages of modular programming: 1. Conducive to multi-person cooperative development 2. Make the code more maintainable 3. Improve code reuse 4. Helps to resolve variable name conflicts(Scope of global variables within modules global in the module)
3. Import the module
1.module loading process when the module is imported,All statements within the module are executed If a module has been imported,Then the statements in the module will not be re-executed when importing again 2.The process by which modules are imported and executed 1. First search the relevant path to find the module name.py 2. Determine if there is a corresponding module for this module pyc document.if.pyc file ratio.py New files are loaded directly.pyc document 3. if.pyc file ratio.py old file,use the module name.py generate .pyc document,and load and execute 3.compilation of modules compile explain execution mymod.py -----> mymod.pyc --------> python3
4. Properties of the module
module properties __doc__ Attributes docstring for binding modules The module's docstring is used for help(module) function to provide help information For example see: mymod2.py __file__Attributes file pathname to use for binding modules __name__Attributes __name__The attribute is used to record the name of the module itself effect: 1. record module name 2. Used to determine whether the main module illustrate: When the module is the main module(That is, the first module to run)Runtime, __name__property binding '__main__' When this module is not the main module,__name__property binding module name like: mymod.py The module name is 'mymod'
5. The __all__ list of modules
modular__all__list effect: when used from xxx import *statement import,import only__all__ properties in the list illustrate: __all__A list is a list of strings used to store exportable properties For example see: mymod3.py Module's hidden properties in the module'_' properties at the beginning,Using from xxx import * guide time will not be imported,These properties are often called hidden properties For example see: mymod4.py
6. Random module random
random module random effect: Blocks for simulating or generating random outputs Documentation see: python_base_docs_html/random module random.py practise: use random module,Randomly generate a 6-digit numeric password for yourself 442260
number guessing game: Let the program randomly generate an integer(0~100)between,with variables x bind Let the user loop through the input integers with y bind,print the guessing result if y > x prompt the user"you guessed it" if y < x prompt the user"you guessed small" if y equal x request the user"congratulations you guessed it right",then exit loop input,and print the number of times the user guessed the number
7. Package (module package) package
Bag(module pack) package A package is a method of grouping modules into folders effect: Classify a series of modules,Helps prevent naming conflicts One or some modules can be loaded when needed,instead of all modules Example: mypack/ __init__.py menu.py games/ __init__.py contra.py supermario.py tanks.py office/ __init__.py excel.py word.py
8. Package import
package import Import rules for the same module import Package names [as package alias] import Package names.module name [as Module new name] import Package names.subpackage name.module name [as Module new name] from Package names import module name [as Module new name] from Package names.subpackage name import module name [as Module new name] from Package names.subpackage name.module name import property name [as property new name] from Package names import * from Package names.module name import *
1. The init.py file and the __all__ list in the file
1.__init__.py document __init__.py is a file that must exist in a regular package __init__.py will be called automatically when the package is loaded effect: Write the contents of this package Fill in the package's docstring inside the package exist__init__.py The file can load some other dependencies of this package. it module 2.__init__.py inside __all__list effect: Used to record which packages or modules in this package need to be imported when used from Bag import *statement when importing a module,find only__all__ All modules or subpackages in illustrate: __all__list only from xxx import * kick in For example see: mypack/games/__init__.py
import The order in which the statement searches paths for packages: 1. The path to search for when the program is running(current working directory) 2. sys.path provided path
2. Relative import of packages
Relative imports of packages The relative import of the package refers to the mutual import of the modules within the package grammar: from relative path package or module import property or module name or from relative path package or module import * relative path: exist from import statement and from imoprt *can be used in the sentence use relative path . represents the current directory .. Represents the upper level directory ... Represents the upper-level directory .... and so on Note: Relative imports cannot go outside the package For example see: mypack/games/contra.py
practise: 1. Simulate Doudizhu licensing,54 cards in total Spades('\u2660'), plum bossom('\u2663'), Hearts('\u2666') square('\u2665') A2-10JQK king,little king three,Each player is dealt 17 cards,Three cards left Enter Enter,Print the 17 cards of the 1st person Enter Enter,Print the 2nd person's 17 cards Enter Enter,Print the 3rd person's 17 cards Enter Enter,Show three hole cards 2. Modify the original student information management program,Split the program into modules: Require: 1. main event loop while statement in main.py middle 2. show_menu function in menu.py middle 3. Functions related to student operations are placed in student_info.py middle 3. Print the Yanghui triangle(Only 6 layers are printed, thinking questions,talk tomorrow or the day after) 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1
day13 review
custom module identifier.py cannot be 123.py imported statement: import statement from import statement from import * statement Path to search for modules: 1. Indexing built-in modules 2. current runtime path 3. search sys.path the path provided in mymod.py ---> mymod.pyc ----> python3 Preset properties of modules __doc__Attributes __file__Attributes __name__Attributes main module '__main__' Non-main module binding 'module name' __all__list The effect is limited to from import *when importing,import only__all__list properties within Module's hidden properties _Properties starting with an underscore are in from import *will not be imported when imported random module name: random function: random.random() random.randint() random.randrange(...) random.sample() random.choice() .... Bag package package import: import from import from import * Example: import Package names.xxx.yyy.zzz from Package names.xxx.yyy.zzz import aaa from Package names.xxx.yyy.zzz import * __init__.py effect: Contents of the package: function,data,docstring __init__.py inner __all__list Tell from import * What the statement imports __all__ = ['contra', 'tanks'] Relative imports of packages Can only be used in two statements: from relative path import statement from relative path import *statement relative path: . .. ...
Day14 Notes
1. exception exception (basic)
abnormal exception (Base) what is wrong Errors are problems that cause the program to not execute properly due to logic or syntax, etc. Features unpredictable what is an exception An exception is a state identified when a program fails.when lead-up occurs,program no longer execute down,And go to the place where this function is called to handle this error and return to positive normal state effect: used as a signal,Notify the upper-layer caller that there is an error that needs to be handled The program has two states: normal status/abnormal state
2.try statement
try Two syntaxes of the statement try-except statement try-finally statement try-except syntax of the statement try: Statements that may trigger exceptions except error type 1 [as variable 1]: exception handling statement 1 except error type 2 [as variable 2]: exception handling statement 2 except (error type 3, error type 4) [as variable 3]: Exception Handling Statement 3 ... except: exception handling statement other else: Statement where exception did not occur finally: final statement 2.effect: try to catch errors,Get notified of exceptions,Convert the program from an abnormal state to a normal state and continue illustrate: as clause is a variable used to bind the error object,can be omitted except clause can have one or more,but at least one else Clause can have at most one.can also be omitted finally Clause can have at most one.can also be omitted For example see: try_except.py practise: write a function get_score() to get grades entered by students information(0-100)the integer,If the input is abnormal,then this function returns 0, Otherwise return the grade entered by the user def get_score(): .... # Implement it yourself here (the try statement can be added inside the function) score = get_score() print("The student's grade is:", score) python3 All error types in: Documentation see: python_base_docs_html/python all exception types.html
3.try-finally statement
try-finally statement grammar try: Statements that may trigger exceptions finally: final statement illustrate: finally clause cannot be omitted must not exist except clause effect: usually used try-finally statement to do the things that must be handled when the exception is triggered whether the exception occurs or not,finally clause will be executed Note: try-finally Statements do not change the program(normal/abnormal)state Example: What is the following statement doing?: def get_number(): s = input("Please enter an integer:") or '0' i = int(s) return i print(get_number()) Rewrite the above program,make your own rules,Keep the program from crashing after rewriting: def get_number(): s = input("Please enter an integer:") try: i = int(s) except: i = 0 return i
4.raise statement
raise statement effect: trigger an error,Put the program into an abnormal state Send error notification to caller grammar: raise exception type or raise exception object or raise # Retrigger the last exception Example: raise ValueError # raise ValueError("???????") For example see: raise.py raise2.py
practise: write a function get_age() Used to obtain a person's age information This function specifies that the user can only enter 1~140 integer between,if the user Enter other data to trigger directly ValueError type of error notification like: def get_age(): .... try: age = get_age() print("The age entered by the user is:", age) except ValueError as err: print('User input is not 1~140 integer between' ',Failed to get age')
5.assert statement (assertion statement)
assert statement(assert statement) grammar: assert truth expression, Bad data(usually a string) effect: When the truth expression is False Time,create one with bad data AssertionError type of error,and enter an abnormal state Usually used to deliberately make a mistake Equivalent to: if bool(truth expression) == False: raise AssertionError(Bad data) For example see: assert.py
6. Statement summary in exception
Statement summary in exception: try-except statement for capture(take over)error notification,Convert abnormal state to normal state try-finally statement for execution in any state(normal/abnormal)statements that must be executed raise statement trigger error(Send error notification),Put the program into an abnormal state assert statement Trigger on condition AssertionError type of error notification
7. Iterator
1.iterator Iterator what is an iterator Iterators are tools for accessing iterable objects iterator means iter(obj) the object returned by the function(example) Iterators can be used next(it) function to get the data of an iterable object 2.iterator function iter and next iter(iterable) Get an iterator from an iterable,iterable Must be an iterable object that provides an iterator next(Iterator) from iterator iterator Get the next record in,like If the next record cannot be fetched,then trigger StopIteration abnormal illustrate: Iterators can only take values forward,won't go back use iter A function can return an iterator of an iterable object Example: L = [2, 3, 5, 7] it = iter(L) # Get an iterator from the L object print(next(it)) # 2 print(next(it)) # 3 print(next(it)) # 5 print(next(it)) # 7 print(next(it)) # StopIteration exception # Use an iterator to access the integer sequence generator returned by the range() function it = iter(range(1, 10, 3)) next(it) # 1 next(it) # 4 next(it) # 7 next(it) # StopIteration For example see: iterator.py
practise: have a collection s = {'Tang monk', 'Goku', 'Bajie', 'sand monk} # Use the for statement to iterate over all elements as follows: for x in s: print(x) else: print("end of traversal") # Please rewrite the above for statement into a while statement and iterator implementation practise: 1. A ball falls from a height of 100 meters,The rebound height is the original height after each landing half of,fall again,programming: 1) Figure out how high the ball bounces off the 10th behind 2) Calculate how many meters the ball travels after the 10th bounce 2. Decomposition prime factors.enter a positive integer,Decomposition prime factors as input: 90 then print: 90=2*3*3*5 (A prime factor is the smallest prime number that is divisible by the original number(does not include 1)) 3. Modify the original student information management program,Add exception handling statement,let the program Executes logically in any case. If entering grades,Age, etc. will not cause the program to crash
day14 review
abnormal try-except statement catch exception try-finally Statement Execute the statement that must be executed raise statement that triggers an exception raise exception type raise exception type() raise assert Statement Assertion Statement try: Statements that may trigger exceptions except exception type 1 as e: ... except exception type 2: ... except (exception type 3, exception type 4): .... except: .... else: ... finally: ... iterator iterator iter(iterable object) return iterator next(iterator) value(when no value is triggered raise StopIteration) iterative loop for x in range(10): ... Equivalent to it = iter(range(10)) while True: try: x = next(it) ... except StopIteration: break
Day15 Notes:
1. Generator Generator
1.Builder Generator what is a generator: Generators are iterable objects that can provide data dynamically Generators generate data while the program is running,Unlike container classes,it usually doesn't Store a lot of data in memory,Instead, use now benefit: Does not take up computer memory There are two types of generators: generator function generator expression Definition of generator function contain yield The function of the statement is a generator function,This function is called and will return a generator object yield translate to(produce or generate) 2.yield statement grammar: yield expression illustrate: yield can only be used for def in function,The purpose is to use this function as a generator function usage yield used to generate data,for iterators next(it) function usage For example see: yield.py illustrate: 1. The invocation of the generator function will return a generator object,The generator object is an iterable object 2. generator function return will trigger a StopIteration abnormal (end of generation) For a practical example of generator see: myinteger.py
practise: Write a generator function myevent(start, stop) used to generate from start start,arrive stop Finish(does not contain stop) within the range a series of even numbers def myeven(start, stop): .... # Do it yourself here evens = list(myeven(10, 20)) print(evens) # [10, 12, 14, 16, 18] for x in myeven(21, 30): print(x) # print 22 24 26 28
2. Generator Expressions
generator expression grammar: (expression for variable in iterable object [if truth expression]) effect: Create a new generator in a comprehensible form illustrate: if clause can be omitted Generator expressions can also be nested like list comprehensions Example: gen = (x**2 for x in range(1, 5)) it = iter(gen) # get iterator next(it) # 1 next(it) # 4 next(it) # 9 next(it) # 16 next(it) # StopIteration
practise: known list: L = [2, 3, 5, 7] 1) Write a generator function.Enable this function to provide data dynamically,number provided Add 1 to the square of the number in the original list 2) Write a generator expression.enable this expression to provide data dynamically,supply The data is the square of the numbers in the list plus 1 3) create a list,The data in this list is the square of the numbers in the original list plus 1 practise: 1.Try writing a generator myfilter function,This function is the same as the system built-in filter Consistent function 2. Understand what is the output of the following functions?why? 1st program L = [2, 3, 5, 7] a = [x*10 for x in L] it = iter(a) print(next(it)) # ??? L[1] = 333 print(next(it)) # ??? 2nd program L = [2, 3, 5, 7] a = (x*10 for x in L) it = iter(a) print(next(it)) # ??? L[1] = 333 print(next(it)) # ???
3. Iterative utility function
iterative utility function The role of the iteration tool function is to generate an iterable object that meets the conditions zip(iter1[,iter2[, ...]]) return a zip generator object This object is used to generate a tuple,The data for this tuple comes from each iterable in the parameter,The number of generated tuples starts from the smallest An iterable object determines enumerate(iterable, start=0) return a enumerate generator object,This object generates type as(index,value pair) tuple of Default index starts at zero,can also be used start specify zip Example: numbers = [10086, 10000, 10010, 95588] names = ['China Mobile', 'China Telecom', 'China Unicom'] for t in zip(numbers, names): print(t) # result # (10086, 'China Mobile') # (10000, 'China Telecom') # (10010, 'China Unicom') for t in zip(numbers, names, range(1, 10000)): print(t) enumerate Example: names = ['China Mobile', 'China Telecom', 'China Unicom'] # for t in zip(range(100000000), names): # print(t) for t in enumerate(names): print(t) # print (0, 'China Mobile') (1, 'China Telecom') (2, 'China Unicom') for t in enumerate(names, 101): print(t) # print (101, 'China Mobile') (102, 'China Telecom') (103, 'China Unicom') zip For an example of the principle of the function, see: myzip.py
practise: write a program,Read in any line of text,End input when a blank line is entered, print the input result with line numbers like: please enter: hello<Enter> please enter: abc<Enter> please enter: tarena<Enter> please enter: <Enter> print as follows: line 1: hello line 2: abc line 3: tarena
container list,string,tuple(sequence), byte string,byte array dictionary,gather,Fixed collection
4. Byte strings and byte arrays
1.Byte strings and byte arrays 1.byte string(byte sequence) bytes Store data in bytes A bytestring is an immutable sequence of bytes illustrate: byte is 0~255 integer between,Used to represent the value of a byte 1.A literal way of creating an empty byte string: b'' b"" b'''''' b"""""" 2.Creates a literal value of a non-empty byte string b'ABCD' b"ABC" b'''aaaa''' b"""BBBB""" 2.Byte string constructor bytes bytes() generate an empty bytestring,Equivalent to b'' bytes(Integer iterable object) Initialize a byte string with an iterable object bytes(integer n) generate n a byte string with a value of 0 bytes(string, encoding='utf-8') Convert to byte string code to generate a byte string Example: B = bytes() B = bytes(range(0x41, 0x61)) B = bytes([65, 66, 67, 68]) B = bytes(10) B = bytes("Hello", 'utf-8') B = bytes("Chinese", 'utf-8') 3.Operations on byte strings: + += * *= < <= > >= == != in / not in Indexing and Slicing 4.function: len(x), max(x), min(x), sum(x), any(x), all(x) 5.bytes and str difference: bytes storage bytes(0~255 integer between) str storage UNICODE character(0~0x10FFFF) character of 6.bytes and str conversion coding(encode) str --------------> bytes b = s.encode(encoding='utf-8') decoding(decode) bytes ---------------> str s = b.decode(encoding='utf-8') Example: s = "ABC Chinese" b = s.encode('utf-8') s2 = b.decode('utf-8') print(s, b, s2) 2.byte array bytearray: mutable byte string 1.Byte array constructor bytearray bytearray() bytearray(Integer iterable object) bytearray(integer n) bytearray(string, encoding='utf-8') 2.operation: same byte string + += * *= Compare: < <= > >= == != in / not in index/slice (Byte arrays can be indexed and sliced for assignment,The same rules as indexing and cutting of lists slice assignment rule) 3.bytearray Methods:Documentation see: python_base_docs_html/bytearray.html
practise: 1. Write a generator function myxrange([start,]stop[,step]) to generate a series of integers Require myxrange function and range The function is exactly the same (call not allowed range Functions and Lists) written by myself myxrange,Combine generator expressions to find all within 100 some odd sum of squares 2. Write a generator function fibonacci, Before generating Fibonacci numbers n number 1 1 2 3 5 8 .... like: def fibonacci(n): ... yield ... ... 1) print the first 20 numbers: for x in fibonacci(20): print(x) 2) Print the sum of the first 40 Fibonacci numbers print(sum(fibonacci(40))) 3. thinking questions: How to enable the student management system to read the information in the file to load data? (Preview file operations)
day15 review
Builder Generate data dynamically There are two types of generators: generator function generator expression generator function: def myxxxx(....): ... yield statement ... A call to a generator function just returns the generator use next(it) to iterator(Builder) when you want data,The generator function will implement The generator function encountered during execution yield will be suspended(hang),will yield The generated data is returned to next(it) function def myxrange(...): ... for x in myxrange(1, 10, 3): print(x) generator expression: (x*2 for x in range(10)) [x*2 for x in range(10)] zip(iterable, *args) function enumerate(iterable, start=0) function (0, "ABC") byte string bytes and byte array bytearray byte byte is a storage unit of 8 bits byte string: literal value b'' b"" b'''''' b"""""" b'ABC' b'123' b'hello' Constructors for byte strings and byte arrays bytes() bytearray() bytes(iterable object) bytearray (iterable object) bytes(integer n) bytearray(integer n) bytes(string, coding'utf-8') bytearray(...) operation: + += * *= < > <= >= == != in / not in Indexing and Slicing sequence: str, list, tuple, bytearray, bytes len(x), max(x) ....
Day16 Notes:
1. File
1.document File A file is the basic unit for storing data Files are often used for long-term storage of data The data in the file is stored sequentially in bytes 2.File operation process 1. open a file 2. read/write file 3. close file Note: any operating system,The number of simultaneously open files for an application maximum number limit 3.file open function open(filename, mode='rt') for opening a file,return the file stream object used to manipulate this file,If opening fails, will trigger OSError error notification 4.Close method of file stream object F.close() close file.Free up system resources For example see: file_open.py Command to display file contents in hexadecimal: $ xxd file name python Read and write operations of Chinese text files: Documentation see: python_base_docs_html/document file.html For an example of reading a text file see: file_read_text1.py
practise: write a file yourself"info.txt", Some text information is stored internally as follows: Zhang San,20,100 Li Si,18,98 little king,22,95 Write a program to read these data out,and printed on the screen terminal in the following format Zhang San is 20 years old,grade is: 100 Li Si is 18 years old,grade is: 98 Xiao Wang is 22 years old,grade is: 95 file stream object readlines For an example of the method see: file_read_text2.py read For an example of how to use the method, see: file_read_text3.py
2. The text file mode of python3
python3 text file mode pattern character: 't' illustrate: 1. Read and write operations on text files require strings(str)read and write operations 2. Automatic encoding during reading and writing(encode) and decoding (decode)operate 3. separated by row,exist python Internal unified use'\n'newline character to separate Line breaks for each operating system: Linux newline: '\n' Windows newline: '\r\n' new Mac OS newline: '\n'
3. Write operation of text file
Writing a text file: method: F.write(x) F.writelines(list) pattern string: 'w' 'x' 'a' See documentation for details: python_base_docs_html/document.html For example see: file_write_text.py practise: 1. write a program,Enter the names of many people,age,grades in file 'infos.txt'middle Define the file format yourself(Commas are recommended(,)to separate the information) Check to see if the file format is what you want when you're done typing (Working with text files) L = input_student() def save_to_file(L, filename='infos.txt') .. save_to_file(L)
4. Binary file operations
binary file operations binary mode characters: 'b' The default file is stored in bytes(byte)data in units,ordinary people artificial format Reading and writing binary files requires strings(bytes) or bytes array(bytearray)operate For binary file read and write methods, you need to operate in bytes F.read(n) F.readline() F.readlines() F.write(byte string) F.writelines(a list of byte strings) For example see: file_read_binary.py For an example of writing a binary file, see: file_write_binary.py
5.F.seek method
F.seek method effect: Set the read and write location of the file,Returns the new read and write location Format: F.seek(Offset, whence=relative position) Offset Greater than 0 means move to the end of the file Less than 0 means move to the head of the file relative position: 0 represents the offset from the beginning of the file 1 Represents the offset from the current read and write position 2. represents the offset from the end of the file For example see: seek.py
6. Standard input and output files
standard input and output files: module name: sys sys.stdin standard input file(Default is keyboard) sys.stdout standard output file(Default is screen terminal) sys.stderr standard error output file(Default is screen terminal) Note: Standard files do not need to be opened to use,No need to close manually For example see: stdout.py
7. Chinese character encoding
How many bytes do ten Chinese characters occupy? Chinese character encoding(only two) GB series: GB18030(Two-byte or four-byte encoding, 27533 words) GBK(two-byte encoding,20013 words) GB2313(two-byte encoding,About 7,000 words) (Windows Commonly used) international standard: UNICODE(UNCODE16/UNICODE32) <-> UTF-8 (Linux/Mac OS X/ IOS/ Android Commonly used) UTF-8 middle: English ASCII (0x0 - 0x7F) one byte (0x80 - 0x3FF) two-byte (0x400 - 0xFFFF) three bytes(Chinese in this area) python encoded string: 'gb2312' 'gbk' 'gb18030' 'utf-8' 'ascii' ... like: s = "Hello" print(s.encode('gbk')) print(s.encode('utf-8')) print(s.encode('ascii'))#Error, "hello" is not in ascii
1. Coding Comments
Coding Comments: in the source file,The following content written in the first or second line is an encoding comment # -*- coding:gbk -*- or # -*- coding:utf-8 -*-
practise: 1. Write a program to implement the function of copying files Require: 1. Consider the problem of very large files 2. To be able to copy binary files(like:pictures etc.) 3. Consider closing the file 2.Rewrite the original student information management program,The following two functions are required to be added: | 9) read data from file(si.txt) | | 10) Save information to file(si.txt) |
day16 review
document: There are two ways to read and write: binary mode: 'b' byte string/byte array text file: 't' string(Default is'utf-8'coding) Two operating modes: read file read(INPUT operate) 'r' write file write(OUTPUT operate) 'w','x','a' process: 1. open a file 2. read/write file 3. close file open(file pathname, pattern string='rt') return file stream object F.close() F.read(n) F.readline() F.readlines() F.write(byte string/string) F.writelines(byte string/string list) F.seek(Offset, relative position) F.tell() F.flush() clear the buffer Chinese character encoding: two: UNCODE coding <--> UTF-8 'utf-8' GB serial number 'gb2312' 'gbk' 'gb18030' ASCII English code: 'ascii' Coding Comments: # -*- coding:utf-8 -*- # -*- coding:gbk -*-
Day17 Notes:
2.8 Object-Oriented Programming in Python
1. Ojbect-Oriented Programming
1.Object-Oriented Programming Ojbect-Oriented Programming Two programming ideas: procedural programming --> The smallest unit is: function function object oriented programming --> The smallest unit is: kind class 2.what is an object: Object refers to an object or entity in reality 3.What is Object Orientation: treat everything as an object(example) Describe things in terms of relationships between various objects 4.What are the characteristics of the object:(1)Objects have many properties(noun,adjective)-- Name, age, gender, Hair color (2)Objects have many behaviors(action,verb) -- study,Have a meal,sleep,kick the ball,Work
2. What is a class
1.what is a class Objects with the same properties and behavior are grouped together,a class Classes are tools for describing objects,Objects of this class can be created with classes(example) signal: car(kind) ----> BYD E6(Beijing A.88888) example \ \--> BMW X5(Beijing B.00000) object(example) dog(kind) ----> Little Beijing(Household registration number: 000001) object \ \---> guide dog(Household registration number:00002) object int(kind) -----> 100 object \ \---> 200 object 2.class creation statement: grammar: class class name(inheritance list): '''class docstring''' instance method(functions within a class method)definition class variable class method(@classmethod) static method(@staticmethod) effect: create a class Classes are used to describe the behavior and properties of objects A class is used to create one or more objects of this class(example) illustrate: class name must be an identifier The class name is actually a variable,it binds a class For example see: class.py
3.class constructor Format: class name([parameter list]) effect: Create an instance object of this class,And return the reference relationship of this instance object For example see: constructor.py illustrate: object(example)Class methods and instance methods can be called object(example) Has its own scope and namespace,can be added to this instance instance variable(Also called instance property)
4.instance method(instance method) Define the format: class class name(inheritance list): def instance method name(self, parameter 1, parameter 2, ...): '''docstring of the method''' statement block effect: Used to describe the behavior of an object,make all objects of this type have the same the behavior of illustrate: The essence of an instance method is a function,is a function defined in an inner class Instance methods have at least one parameter,The first parameter binds the instance that calls this method example,Commonly named as'self' 5.Instance method invocation syntax: example.instance method name(call parameter) or class name.instance method name(example, call parameter) For example see: instance_method.py
6.instance properties attribute (Also called instance variable) Each instance can use its own variables to record each object's own data,this variable called instance variable use syntax: example.property name assignment rule: This property is created the first time a property is assigned a value Assigning a value to a property again changes the binding relationship of this property effect: Record each object's own data practise: define a"people" kind class Human: def set_info(self, name, age, address="unknown"): ... Do it yourself here def show_info(self): '''This information is displayed here''' ... Do it yourself here s1 = Human() s1.set_info('Xiao Zhang', 20, 'Dongcheng District, Beijing') s2 = Human() s2.set_info('Xiao Li', 18) s1.show_info() # Xiao Zhang is 20 years old and lives in: ... s1.show_info() # Xiao Li is 18 years old, home: unknown
7.delete attribute: del statement del object.instance variable name del Statement summary: 1) delete variable del a,b,c 2) remove element from list del L[0], L[0:3] 3) delete key from dictionary del d['name'] 4) delete attribute del obj.name
8.initialization method effect: Add properties to newly created objects syntax format: class class name(inheritance list): def __init__(self [,parameter list]) statement block Note:[]Represents the contents of which can be omitted illustrate: 1. The name of the initialization method must be '__init__' immutable 2. The initialization method is called automatically after the constructor creates the instance,and will be The example itself passes the first parameter self incoming'__init__' method 3. The arguments to the constructor will be passed through__init__method parameter list into__init__method 4. Inside the initialization method if needed return return,must return None For example see: init_method.py
practise: write a student class Student kind,This class is used to describe student information,student information has: Name,age,score(Default is 0) 1) Add an initialization method to the class,Implements automatic settings when the object is created: name, age, score Attributes 2) Add to set_score method,Ability to modify grade information for objects 3) Add to show_info method to print the information of the student object like: class Student: def __init__(....): .... def set_score(....): ... def show_info(...) ... L = [] L.append(Student('Xiao Zhang', 20, 100)) L.append(Student('Xiao Li', 18, 95)) L.append(Student('small money', 19)) L[-1].set_score(70) for s in L: s.show_info()
2. Destructor method
Destructor Format: class class name(inheritance list): def __del__(self): .... effect: Release the resources occupied by this object before this object is destroyed illustrate: The destructor method is called automatically before the object is destroyed python The language advises against doing anything on object destruction,because of the destruction time is difficult to determine For example see: del_method.py
3. Preset instance properties
Preset instance properties __dict__ Attributes __dict__property binding a dictionary that stores this instance's own variables Example: class Dog: pass dog1 = Dog() print(dog1.__dict__) # {} dog1.color = "White" print(dog1.__dict__) # {'color': "white"}
4.class attribute
__class__ Attributes __class__ property binding the class that created this instance effect: The class that created this instance can be accessed with the help of this property Example: class Dog: pass dog1 = Dog() print(dog1.__class__) dog2 = dog1.__class__() # Dog()
5. Functions for instance objects
functions for instance objects: isinstance(obj, class_or_tuple) return this object obj is an object of a class,or an object of a class within some class.if return if yes True,otherwise return False type(obj) the type of the returned object Example: class Dog: pass dog1 = Dog() isinstance(dog1, Dog) # True isinstance([1,2,3], Dog) # False isinstance([1, 2, 3], (int, str)) # False isinstance([1, 2, 3], (int, str, list))#True type(dog1) is Dog # True
practise: there are two people: the first person: Name:Zhang San, age:35 age second person: Name:Li Si, age:15 age Behavior: 1. teach others to learn teach 2. work to make money work 3. borrow money borrow 4. show your information show_info matter: Zhang San teaches Li Sixue python Li Si teaches Zhang San learns the glory of the king Zhang San earned 1,000 yuan at work Li Si borrowed 200 yuan from Zhang San 35 The old Zhang San has 800 yuan,The skills it learns are: King of Glory 15 Year-old Li Si has 200 yuan,The skills it learns are: python practise: 1. perfect number: 1 + 2 + 3 = 6 (6 is a perfect number) 1, 2,3 are all factors of 6(can be counted by a number x Divisible numbers y,but y for x factor of) 1 x 6 = 6 2 x 3 = 6 Exactly means the sum of all factors except itself is equal to itself ask for 4 - 5 perfect number Answer: 6 28 496 ... 2. The Student Information Management Program,dictionary for storing student information,replace with use Student type object to store student information
day17 review
object oriented: what is an object what is a class characteristics of objects: Attributes industry kind class Classes are used to describe objects, created objects(example) instance method class class name: def instance method name(self, method parameter list): statement block call syntax: object.instance method name(Arguments) class name.instance method name(object, Arguments) class within class: class class name: instance method(self, ...): ... class variable class method static method Constructor class name(call arguments) Create an instance(object) instance variable(instance properties) record object data v = object.property name # value object.property name = v # Assignment (create or modify instance variables) delete instance variable del object.property name initialization method: def __init__(self, method parameters): .... effect: Create instance variables(instance properties) Destructor: def __del__(self): ... Preset instance properties: __dict__ bind instance variable(instance properties)dictionary class Dog: pass dog1.color = "White" # add instance variable dog1.__dict__['kinds'] = "Beijing" # add instance variable __class__ bind the class that created this instance type(obj) return obj.__class__ type(obj) # The return type is equivalent to obj.__class__ isinstance(obj, class or tuple of classes) obj.__class__ is kind or obj.__class__ in tuple
Day18 Notes:
2.9 Advanced Object-Oriented Programming in Python
1. Class
1.kind define method: class class name: ... classes are objects,It is an object that can create instances 2.class variable A class variable is an attribute of a class, this attribute belongs to the class, not an instance of this class effect: Commonly used to store common properties of objects created by this class illustrate: Class variables can be accessed directly through the class Class variables can be accessed directly through an instance of the class(value) Class variables can be accessed through objects of this class__class__property indirect access For example see: class_variable.py Both instance methods and class methods are variables of the class(class variable)
2. Class docstring
class docstring: The first string in the class that is not assigned to any variable is the class's document string A class's docstring is bound in the class's __doc__ attribute Example: class Dog: '''Dog class docstring''' >>> help(Dog) >>> print(Dog.__doc__)
3. Class slot list
Category __slots__ list: effect: Instances created by restricting a class can only be created in fixed properties(instance variable) Objects are not allowed to add instance properties other than this list A program error occurred for the accessing user due to a mistyped attribute name illustrate: __slots__property is a list,The value of the list is a string contain__slots__The instance object created by the class of the property does not have __dict__Attributes,That is, this instance does not use a dictionary to store instance attributes For example see: slots.py
4. Class method @classmethod
class method @classmethod Class methods are methods used to describe the behavior of a class,class method belongs to class,Does not belong Objects created by this class illustrate: 1. Class methods need to use@classmethod Decorator Definition 2. A class method has at least one parameter,The first parameter is used for binding kind,Convention is written as'cls' 3. Both a class and an instance of that class can call class methods 4. Class methods cannot access instance properties of objects created by this class For example see: classmethod.py
5. Static method @staticmethod
static method @staticmethod A static method is a function defined inside a class,The scope of this function is inside the class illustrate: 1. Static methods need to be used@staticmethod Decorator Definition 2. A static method is the same as a normal function definition,No need to pass in self and cls parameter 3. Static methods can only be called with the class or an instance of the class 4. Static methods cannot access class and instance variables For example see: staticmethod.py
6. Function, static method, class method, instance method
function,static method, class method, instance method: commonality: statement block,implement the corresponding function
practise: 1. Use a class to describe a student's information(You can also rewrite the previous Student kind) 2. Student information has: Name,age,score 3. Store these student objects in a list,can be added arbitrarily,and Delete student information 1) print out the number of students 2) Print out the grade point average for all students 3) Print out the average age of all students (It is recommended to use a class variable to record a list of student information)
7. Inheritance and derived
1.inherit inheritnce and derived derived what is inheritance/Derive Derivation is to derive a new class from an existing class Inheritance means that objects in a derived new class will have the properties of the original class sex and behavior effect: Using inheritance derivation mechanism, you can add some common functions to the base class. Implement code sharing Change the function of the original class without changing the base class code noun: base class(base class)/superclass(super class)/father kind(father class) Derived class(derived class) / Subclass(child class)
8. Single inheritance and the __base__ attribute of the class
2.single inheritance: grammar: class class name(base class name): statement block illustrate: Single inheritance refers to a class that derives from a derived class from a base class For example see: inherit.pyinherit.py Inheritance Notes: python3 Any class in which directly or indirectly inherits from object kind object Class is the superclass of all classes 3.Category__base__Attributes __base__ Attribute is used to record the base class of this class python For the inheritance relationship of built-in classes, see: >>> help(__builtins__)
9. Overriding overridde
cover overridde Overriding refers to in the class with inheritance relationship.The subclass implements the same as the base class The method of the same name, when the instance of the subclass calls the method, the actual call is the overridden version of the subclass, a phenomenon called overriding effect: Implement a method with the same name as the parent class but with different functions For example see: override.py question: when an overwrite occurs, How to call the overridden method of the parent class?
10.super function
1.super function super(cls, obj) Returns an instance of the bound superclass(Require obj must Yes cls class or cls object of subclass) super() Returns an instance of the bound superclass, equivalent to: super(__class__, The first parameter of an instance method), must be used within a method call effect: with the help of super() The returned instance indirectly invokes the overridden method of the parent class For example see: super.py 2.super Applications Explicitly call the initializer method of the base class When the subclass implements__init__method, base class__init__method will not be called automatically.If you need to call, you need to use super explicit transfer. For example see: super_init.py
practise: 1. write a class Bicycle bicycle,Have run method,when called Show mileage km class Bicycle: def run(self, km): print("bike ride", km, 'kilometer') write another EBicycle Electric bicycles,exist Bicycle The basics Added battery power on volume Attributes,There are two methods: fill_charge(vol) to charge vol for electricity run(km) method,10 per ride km 1 degree of power consumption,Simultaneously display Display the current battery,Called when the battery runs out Bicycle of run method (ride with pedals) class EBicycle: .... b = EBicycle(5) The newly bought electric car has 5 kWh of electricity b.run(10) 10 electric rides km inside,4 kWh left b.run(100) 40 electric rides km inside,0 kWh left,with pedals 60 rides km b.fill_charge(10) Electric bike charging 10 degrees b.run(50) 50 electric rides km inside,5 kWh left
day18 review
kind -> object (example) class object(instance) object: real variable(instance properties) List method kind: class variable(class attribute) class method(@classmethod) @classmethod def myclassmethod(cls, ....): .... static method(functions within a class) Preset class properties(class variable) __docs__ binding docstring __base__ Bind the base class of the current class(father) __slots__list Restrict a class to only have fixed instance variables(instance properties) inherit / Derive single inheritance class class name(only one parent class): pass cover: Inheritance-related classes,A subclass implements a method with the same name as the superclass,subclass call The method actually calls the overridden version of the subclass once covered,There is no way for subclass objects to directly call the overridden method of the parent class super(kind, object) super() # can only be called from within a method use super Explicitly call the parent class __init__ initialization method super().__init__(Pass arguments to the initial method of the parent class)
Day19 Notes
1. Functions for classes
functions for classes: issubclass(cls, class_or_tuple) determine whether a class is Does it inherit from a class class or some class tuple middle a class,return if yes True,otherwise return False Example: class A: pass class B(A): pass class C(B): pass issubclass(C, B) # True issubclass(bool, int) # True issubclass(str, (A, B, int, float)) # False issubclass(str, (A, B, int, object)) # True
Features of Object-Oriented Programming Languages: inherit package polymorphism
2. Package
package Encapsulation refers to hiding the implementation details of a class,Let users not care about these details The purpose of encapsulation is to allow the user to pass as few methods as possible(or attribute)Hold target
3. Private properties and methods
private properties and methods python double underscore in class__beginning,identifiers that do not end with a double underscore is a private member,Private members can only be accessed using the methods of the class and Revise For example see: enclosure.py
4. polymorphic
1.polymorphism polymorphic literal meaning: 'multiple states' 2.The state of programming languages: static(compile-time state) # C/C++ dynamic(runtime state) # C++/Java 3.Polymorphism originally refers to classes with inheritance relationship,Call a method of the base class object,actual energy The phenomenon of calling to a subclass to override a method is called polymorphism illustrate: python All objects are only'runtime state(dynamic)',No C++compile-time state in the language(static) For example see: poly.py
5. multiple inheritance
multiple inheritance multiple inheritance Multiple inheritance is when a subclass inherits from two or more base classes syntax for multiple inheritance: class class name(base class name 1, base class name 2, ...): statement illustrate: 1. A subclass inherits from multiple parent classes at the same time,The method in the parent class can be the same as inherited when 2. If two parent classes have methods with the same name,And in the subclass there is no override cover this method,Call result is difficult to determine For example see: multi_inherit.py Multiple inheritance problem(defect) identifier(namespace) conflicting issues Use multiple inheritance with caution For example see: multi_inherit2.py multiple inheritance MRO(Method Resolution Order) question MRO --> solution(find)order Category __mro__Attributes The search order used to record the methods of the class For example see: mro.py
6. Use of object to string function
Use of object to string function repr(obj) return an attachment python a string of grammar rules, usually: eval(repr(obj)) == obj str(obj) Returns a string with the given object(this character Strings are usually read by humans) For example see: repr_str.py illustrate: The above two functions must return a string
7. Function rewriting
1.function rewrite Function overriding refers to adding the corresponding method in the custom class,let's customize Instances of the class can be functionally manipulated like built-in objects 2.Overriding method of object to string function repr(obj) function override method: def __repr__(self): return 'string' str(obj) function override method: def __str__(self): return 'string' For example see: mynumber.py student.py str(obj) Function call method description: 1. call first obj.__str__() method value. 2. if obj.__str__()method does not exist,then tune use obj.__repr__() method value 3. if it doesn't exist anymore obj.__repr__()method.then call object Category__repr__method value.
1. Built-in function rewrite
Built-in function override method name Function name __abs__(self) abs(obj) function __len__(self) len(obj) function __reversed__(self) reversed(obj) __round__(self) round(obj) For example see: len_overwrite.py
2. Value conversion function rewrite
Numeric conversion function rewrite method name Function name __complex__(self) complex(obj) __int__(self) int(obj) __float__(self) float(obj) __bool__(self) bool(obj) For example see: mynumber2.py
3. Boolean test function bool(obj) function rewrite
boolean test function bool(obj) function rewrite effect: used for bool(obj) function value: used for if in the truth expression of the statement used for while in the truth expression of the statement illustrate: 1. Priority call obj.__bool__() method to get value 2. when not there obj.__bool__() method,use obj.__len__() boolean value to determine whether the return value is zero 3. when not there__len__() method,return directly True For example see: bool.py
8. Object property management functions
Object property management functions getattr(obj, name[, default]) get from an object properties of objects; getattr(x, 'y') Equivalent to x.y; when the attribute does not exist,if given default parameter,then return back default,if not given default produces a indivual AttributeError mistake hasattr(obj, name) with the given name return object obj Yes has this property,This approach can avoid getattr(obj, name)throws an error when setattr(obj, name, value) to the object obj named name property set the corresponding value value, set(x, 'y', v) Equivalent to x.y = v delattr(obj, name) delete object obj middle name Attributes, delattr(x, 'y') Equivalent to del x.y
9. Iterators (Advanced)
1.iterator(advanced) what is an iterator may pass next(it) The object that the function takes is the iterator iterator protocol: The iterator protocol means that objects can use next function get next item data,Trigger one when there is no next item of data StopIteration Exception to terminate iteration convention Implementation method of iterator protocol: __next__(self) method to implement the iterator protocol 2.what is an iterable object: means usable iter(obj) The function returns an iterator object(example) The inner part of the iterable object needs to be defined __iter__(self) method to return iterator object(example) For example see: mylist_iterable.py
practise: 1. Changes to previous student information management procedures Request to transfer student's grades,Name, age attributes are encapsulated, do not allow remove Student Function and method access and modification outside the class 2. Implement a system built-in range class with the same function: class MyRange: def __init__(self, ....): ... def __iter__(self): ... Implement the following functions: L = list(MyRange(5)) print(L) # [0, 1, 2, 3, 4] print(sum(MyRange(1, 101))) # 5050 L2 = [x**2 for x in MyRange(1, 10, 3)] print(L2) # [1, 16, 49] for x in MyRange(10, 0, -3): print(x) # 10, 7, 4, 1
day19 review
issubclass(cls, class or tuple) package __ Start with private properties and private methods to implement polymorphism dynamic and static inherit,package,polymorphism multiple inheritance A subclass inherits from two or more parent classes __mro__ Method Resolution Order super(B, b).xxxx() function rewrite Enable custom classes to operate using built-in functions repr __repr__ str __str__ len abs round reversed int float complex bool Four attribute-related functions setattr(obj, name, value) hasattr(obj, name) getattr(obj, name [,default]) delattr(obj, name) iterator __next__(self) method Implement the iterator protocol iterable object __iter__(self) method return iterator
Day20 Notes
2.10 Exceptions
1. Exception
abnormal Exception-Related Statements Review: try-except try-finally raise assert
2.with statement
3. Environment Manager
environment manager class has __enter__ and __exit__A class with instance methods is called environment manager __enter__will enter with is called when the statement,and return by as variable managed objects __exit__will be leaving with is called when the statement,and can use parameters to Judgment is leaving with Whether an exception occurred during the statement,and make corresponding deal with For example see: with2.py
4. Operator overloading
operator overloading What is operator overloading Let the custom class generate the object(example)able to use operations character to operate effect: Let instances of custom classes use operators like built-in objects Make the program concise and easy to read Assign operators to new rules for custom objects
1. Arithmetic operator overloading
Arithmetic operator overloading method name Operator and Expression Description __add__(self, rhs) self + rhs addition __sub__(self, rhs) self - rhs subtraction __mul__(self, rhs) self * rhs multiplication __truediv__(self, rhs) self / rhs division __floordiv__(self, rhs) self // rhs floor removal __mod__(self, rhs) self % rhs Surplus __pow__(self, rhs) self ** rhs exponentiation rhs (right hands side) right hand side For example see: mynumber1.py illustrate: The methods and parameters of operator overloading already have fixed meanings,not recommend change the original meaning
practise: Implements the addition of two custom lists class MyList: def __init__(self, iterable=()): ... ..... L1 = MyList(range(1, 4)) L2 = MyList([4, 5, 6]) L3 = L1 + L2 print(L3) # MyList([1, 2, 3, 4, 5, 6]) L4 = L2 + L1 print(L4) # MyList([4, 5, 6, 1, 2, 3]) L5 = L1 * 2 print(L5) # MyList([1, 2, 3, 1, 2, 3]) # think: L6 = 2 * L2 # Can it? Why?
2. Overloading of reverse arithmetic operators
Overloading of reverse arithmetic operators When the left side of the operator is a built-in type,Arithmetic for custom types on the right during operation,Will appear TypeError mistake Operator overloading due to inability to modify code for built-in types,At this time need Overloading is done using reverse arithmetic operator overloading method name Operator and Expression Description __radd__(self, lhs) lhs + self addition __rsub__(self, lhs) lhs - self subtraction __rmul__(self, lhs) lhs * self multiplication __rtruediv__(self, lhs) lhs / self division __rfloordiv__(self, lhs) lhs // self floor removal __rmod__(self, lhs) lhs % self Surplus __rpow__(self, lhs) lhs ** self exponentiation For example see: code/mylist.py
3. Compound assignment arithmetic operator overloading
Compound assignment arithmetic operator overloading with compound assignment arithmetic operators x += y For example,this operator takes precedence transfer x.__iadd__(y) method.if there is not__iadd__method When the conjunctive assignment operator is disassembled into x = x + y and then call x = x.__add__(y) method,if it doesn't exist anymore__add__method will trigger TypeError abnormal The same rules apply to other compound assignment arithmetic operators method name Operator and Expression Description __iadd__(self, rhs) self += rhs addition __isub__(self, rhs) self -= rhs subtraction __imul__(self, rhs) self *= rhs multiplication __itruediv__(self, rhs) self /= rhs division __ifloordiv__(self, rhs) self //= rhs floor division __imod__(self, rhs) self %= rhs Surplus __ipow__(self, rhs) self **= rhs exponentiation For example see: mylist2.py
question: # ---- Program 1 is implemented as a list ------- L = [1, 2, 3] def f1(lst): lst += [4, 5, 6] f1(L) print(L) # [1, 2, 3, 4, 5, 6] # -----The program is implemented with tuples -------- L = (1, 2, 3) def f1(lst): lst += (4, 5, 6) f1(L) print(L) # (1, 2, 3)
4. Overloading of comparison operators
Overloading of comparison operators: method name Operator and Expression Description __lt__(self, rhs) self < rhs less than __le__(self, rhs) self <= rhs less than or equal to __gt__(self, rhs) self > rhs more than the __ge__(self, rhs) self >= rhs greater or equal to __eq__(self, rhs) self == rhs equal __ne__(self, rhs) self != rhs not equal to
5. Bitwise operator overloading
Bitwise operator overloading: method name Operator and Expression Description __and__(self, rhs) self & rhs bit and __or__(self, rhs) self | rhs bit or __xor__(self, rhs) self ^ rhs bit XOR __lshift(self, rhs) self << rhs shift left __rshift(self, rhs) self >> rhs move right
6. Reverse bitwise operator overloading
Reverse bitwise operator overloading: method name Operator and Expression Description __rand__(self, lhs) lhs & self bit and __ror__(self, lhs) lhs | self bit or __rxor__(self, lhs) lhs ^ self bit XOR __rlshift(self, lhs) lhs << self shift left __rrshift(self, lhs) lhs >> self move right
7. Compound assignment bitwise operator overloading
Compound assignment bitwise operator overloading: method name Operator and Expression Description __iand__(self, rhs) self &= rhs bit and __ior__(self, rhs) self |= rhs bit or __ixor__(self, rhs) self ^= rhs bit XOR __ilshift(self, rhs) self <<= rhs shift left __irshift(self, rhs) self >>= rhs move right
8. Unary operator overloading
Unary operator overloading: method name Operator and Expression Description __neg__(self) - self negative __pos__(self) + self Positive sign __insert__(self) ~ self Negate grammar: class class name: def __xxx__(self): .... For example see: mylist4.py
9.in / not in operator overloading
in / not in operator overloading: method name Operators and Expressions __contains__(self, e) e in self For example see: mylist5.py
10. Overloading of indexing and slicing operators
Overloading of indexing and slicing operators: L[0] L[::2] method name Operator and Expression Description __getitem__(self, i) x = self[i] value __setitem__(self, i, v) self[i] = v assign __delitem__(self, i) del self[i] drop index For example see: mylist6.py
5.slice constructor
slice Constructor effect: for creating a slice slice object,This object stores a slice starting value of,end value and step size information,Default is None Format: slice(start=None, stop=None, step=None) slice object properties s.start The starting value of the slice defaults to None s.stop the end value of the slice,The default is None s.step step size of slice,The default is None For example see: mylist7.py
6. Feature property @property
characteristic attribute @property Implement what other languages have getter and setter Function effect: used to simulate a property pass@property Decorators can assign and get values to mocked properties to control For example see: property.py
7.PEP8 encoding specification
PEP8 Coding Standards Documentation see: python_base_docs_html/PEP8 Coding Standards.html
return
return default, if default is not given, a
AttributeError errors
hasattr(obj, name) returns the object obj with the given name is
Whether there is this property, this approach can avoid
throws error when getattr(obj, name)
setattr(obj, name, value) gives the name of the object obj
The attribute of name sets the corresponding value value,
set(x, 'y', v) is equivalent to x.y = v
delattr(obj, name) delete the name attribute in the object obj,
delattr(x, 'y') is equivalent to del x.y
#### 9. Iterators (Advanced) ```python 1.iterator(advanced) what is an iterator may pass next(it) The object that the function takes is the iterator iterator protocol: The iterator protocol means that objects can use next function get next item data,Trigger one when there is no next item of data StopIteration Exception to terminate iteration convention Implementation method of iterator protocol: __next__(self) method to implement the iterator protocol 2.what is an iterable object: means usable iter(obj) The function returns an iterator object(example) The inner part of the iterable object needs to be defined __iter__(self) method to return iterator object(example) For example see: mylist_iterable.py
practise: 1. Changes to previous student information management procedures Request to transfer student's grades,Name, age attributes are encapsulated, do not allow remove Student Function and method access and modification outside the class 2. Implement a system built-in range class with the same function: class MyRange: def __init__(self, ....): ... def __iter__(self): ... Implement the following functions: L = list(MyRange(5)) print(L) # [0, 1, 2, 3, 4] print(sum(MyRange(1, 101))) # 5050 L2 = [x**2 for x in MyRange(1, 10, 3)] print(L2) # [1, 16, 49] for x in MyRange(10, 0, -3): print(x) # 10, 7, 4, 1
day19 review
issubclass(cls, class or tuple) package __ Start with private properties and private methods to implement polymorphism dynamic and static inherit,package,polymorphism multiple inheritance A subclass inherits from two or more parent classes __mro__ Method Resolution Order super(B, b).xxxx() function rewrite Enable custom classes to operate using built-in functions repr __repr__ str __str__ len abs round reversed int float complex bool Four attribute-related functions setattr(obj, name, value) hasattr(obj, name) getattr(obj, name [,default]) delattr(obj, name) iterator __next__(self) method Implement the iterator protocol iterable object __iter__(self) method return iterator
Day20 Notes
2.10 Exceptions
1. Exception
abnormal Exception-Related Statements Review: try-except try-finally raise assert
2.with statement
3. Environment Manager
environment manager class has __enter__ and __exit__A class with instance methods is called environment manager __enter__will enter with is called when the statement,and return by as variable managed objects __exit__will be leaving with is called when the statement,and can use parameters to Judgment is leaving with Whether an exception occurred during the statement,and make corresponding deal with For example see: with2.py
4. Operator overloading
operator overloading What is operator overloading Let the custom class generate the object(example)able to use operations character to operate effect: Let instances of custom classes use operators like built-in objects Make the program concise and easy to read Assign operators to new rules for custom objects
1. Arithmetic operator overloading
Arithmetic operator overloading method name Operator and Expression Description __add__(self, rhs) self + rhs addition __sub__(self, rhs) self - rhs subtraction __mul__(self, rhs) self * rhs multiplication __truediv__(self, rhs) self / rhs division __floordiv__(self, rhs) self // rhs floor removal __mod__(self, rhs) self % rhs Surplus __pow__(self, rhs) self ** rhs exponentiation rhs (right hands side) right hand side For example see: mynumber1.py illustrate: The methods and parameters of operator overloading already have fixed meanings,not recommend change the original meaning
practise: Implements the addition of two custom lists class MyList: def __init__(self, iterable=()): ... ..... L1 = MyList(range(1, 4)) L2 = MyList([4, 5, 6]) L3 = L1 + L2 print(L3) # MyList([1, 2, 3, 4, 5, 6]) L4 = L2 + L1 print(L4) # MyList([4, 5, 6, 1, 2, 3]) L5 = L1 * 2 print(L5) # MyList([1, 2, 3, 1, 2, 3]) # think: L6 = 2 * L2 # Can it? Why?
2. Overloading of reverse arithmetic operators
Overloading of reverse arithmetic operators When the left side of the operator is a built-in type,Arithmetic for custom types on the right during operation,Will appear TypeError mistake Operator overloading due to inability to modify code for built-in types,At this time need Overloading is done using reverse arithmetic operator overloading method name Operator and Expression Description __radd__(self, lhs) lhs + self addition __rsub__(self, lhs) lhs - self subtraction __rmul__(self, lhs) lhs * self multiplication __rtruediv__(self, lhs) lhs / self division __rfloordiv__(self, lhs) lhs // self floor removal __rmod__(self, lhs) lhs % self Surplus __rpow__(self, lhs) lhs ** self exponentiation For example see: code/mylist.py
3. Compound assignment arithmetic operator overloading
Compound assignment arithmetic operator overloading with compound assignment arithmetic operators x += y For example,this operator takes precedence transfer x.__iadd__(y) method.if there is not__iadd__method When the conjunctive assignment operator is disassembled into x = x + y and then call x = x.__add__(y) method,if it doesn't exist anymore__add__method will trigger TypeError abnormal The same rules apply to other compound assignment arithmetic operators method name Operator and Expression Description __iadd__(self, rhs) self += rhs addition __isub__(self, rhs) self -= rhs subtraction __imul__(self, rhs) self *= rhs multiplication __itruediv__(self, rhs) self /= rhs division __ifloordiv__(self, rhs) self //= rhs floor division __imod__(self, rhs) self %= rhs Surplus __ipow__(self, rhs) self **= rhs exponentiation For example see: mylist2.py
question: # ---- Program 1 is implemented as a list ------- L = [1, 2, 3] def f1(lst): lst += [4, 5, 6] f1(L) print(L) # [1, 2, 3, 4, 5, 6] # -----The program is implemented with tuples -------- L = (1, 2, 3) def f1(lst): lst += (4, 5, 6) f1(L) print(L) # (1, 2, 3)
4. Overloading of comparison operators
Overloading of comparison operators: method name Operator and Expression Description __lt__(self, rhs) self < rhs less than __le__(self, rhs) self <= rhs less than or equal to __gt__(self, rhs) self > rhs more than the __ge__(self, rhs) self >= rhs greater or equal to __eq__(self, rhs) self == rhs equal __ne__(self, rhs) self != rhs not equal to
5. Bitwise operator overloading
Bitwise operator overloading: method name Operator and Expression Description __and__(self, rhs) self & rhs bit and __or__(self, rhs) self | rhs bit or __xor__(self, rhs) self ^ rhs bit XOR __lshift(self, rhs) self << rhs shift left __rshift(self, rhs) self >> rhs move right
6. Reverse bitwise operator overloading
Reverse bitwise operator overloading: method name Operator and Expression Description __rand__(self, lhs) lhs & self bit and __ror__(self, lhs) lhs | self bit or __rxor__(self, lhs) lhs ^ self bit XOR __rlshift(self, lhs) lhs << self shift left __rrshift(self, lhs) lhs >> self move right
7. Compound assignment bitwise operator overloading
Compound assignment bitwise operator overloading: method name Operator and Expression Description __iand__(self, rhs) self &= rhs bit and __ior__(self, rhs) self |= rhs bit or __ixor__(self, rhs) self ^= rhs bit XOR __ilshift(self, rhs) self <<= rhs shift left __irshift(self, rhs) self >>= rhs move right
8. Unary operator overloading
Unary operator overloading: method name Operator and Expression Description __neg__(self) - self negative __pos__(self) + self Positive sign __insert__(self) ~ self Negate grammar: class class name: def __xxx__(self): .... For example see: mylist4.py
9.in / not in operator overloading
in / not in operator overloading: method name Operators and Expressions __contains__(self, e) e in self For example see: mylist5.py
10. Overloading of indexing and slicing operators
Overloading of indexing and slicing operators: L[0] L[::2] method name Operator and Expression Description __getitem__(self, i) x = self[i] value __setitem__(self, i, v) self[i] = v assign __delitem__(self, i) del self[i] drop index For example see: mylist6.py
5.slice constructor
slice Constructor effect: for creating a slice slice object,This object stores a slice starting value of,end value and step size information,Default is None Format: slice(start=None, stop=None, step=None) slice object properties s.start The starting value of the slice defaults to None s.stop the end value of the slice,The default is None s.step step size of slice,The default is None For example see: mylist7.py
6. Feature property @property
characteristic attribute @property Implement what other languages have getter and setter Function effect: used to simulate a property pass@property Decorators can assign and get values to mocked properties to control For example see: property.py
7.PEP8 encoding specification
PEP8 Coding Standards Documentation see: python_base_docs_html/PEP8 Coding Standards.html