Python basic super detailed notes [notes written for self review ~]

Keywords: Python

Bold style @[toc]

Computer composition

hardware system

  • cpu: cpu
  • Memory: internal memory: external memory: hard disk u disk
  • Input devices: keyboard, mouse
  • Output devices: monitors, printers

software system

  • System software: operating system
  • Application software: qq, wechat

python Fundamentals

notes

  • Single-Line Comments
#
  • multiline comment
#Second
"""

"""
#First kind
'''

'''

variable

  • Role of variables
    • A variable is the name of the memory address where the current data is stored
  • Define variables
Variable name = value    #First calculate the value to the right of the equal sign, and then assign it to the left

The variable name is customized to meet the identifier naming rules

  • Understanding data types

identifier

The identifier naming rule is a unified specification when python defines various names, as follows:

  • It consists of numbers, letters and underscores
  • Cannot start with a number
  • Built in keywords cannot be used
  • Strictly case sensitive
False None True and as assert break class
continue def del elif else except finally for
from global if import in is lambda nonlocal
not or pass raise return try while with yield

Naming rules

  • See the name and know the meaning.
  • Big hump: that is, the first letter of each word is capitalized, such as MyName.
  • Small hump: words after the second (inclusive) are capitalized, for example: myName
  • Underline: include: my_name

Use variables

my_name = 'TOM'
print(my_name)

schoolName = 'full text'
print(schoolName)

Recognize bug s

Debug tool

Debug tool is a tool integrated in pyCharm IDE to debug programs. Here programmers can view the execution details and processes of programs or mediate bugs.

Steps for using the Debug tool:

1. Break point

2.Debug debugging

Break

  • Breakpoint location

The first line of code of the code block to be debugged by the target, that is, a breakpoint.

  • Method of breaking point

Click the blank space to the right of the line number of the object code.

data type

  • Numeric value: int (integer), float (floating point number)
  • Boolean
  • str (string)
  • list
  • Tuple (tuple)
  • set
  • dict (Dictionary)
#The type() function checks the python data type

output

Function: the program outputs content to the user

print('hello Python')

age =  18
print(age)

#Demand: output "my age is 18 this year"

Format symboltransformation
%scharacter string
%dSigned decimal integer
%fFloating point number
%ccharacter
%uUnsigned decimal integer
%oOctal integer
%xHexadecimal integer (lowercase ox)
%XHexadecimal integer (uppercase OX)
%eScientific counting (lowercase 'e')
%EScientific counting (capital 'E')
%g%Abbreviations for f and% e
%G%Abbreviations for f and% E
age = 18
name = 'TOM'
weight =75.5
stu_id = 1

print('My age this year is%d year' % age)
print('My name is%s' % name)
print('My weight is%.3f kg .' % weight)   #. 3f retain three decimal places
print('My student number is%03d' % stu_id)       #03d format output three digits
print('My name is%s,this year%d Years old,Weight is%.3f kg .,The student number is%03d' % (name,age,weight,stu_id))

# expand
print('My name is%s,this year%s Years old, weight%s kg .' % (name,age,weight))
print(f'My name is{name},next year{age+1}Years old') #3.6 coming out

Escape character

  • \n: Line feed
  • \t: Tab, a tab key (4 spaces) distance.

input

In python, the function of the program to receive the data input by the user is input.

Input syntax

input("Prompt information")

Input characteristics

  • When the program is executed to input, wait for user input, and continue to execute downward after input is completed.

  • In python, after receiving user input, input is generally stored in variables for easy use.

  • In python, input will treat any received user input data as a string.

    shifting clause

Q: the data input by input () is of string type. If the user inputs 1, what should he do to get an integer?

A: just convert the data type, that is, convert the string type to integer.

typle()                 #Convert a sequence to a tuple
str()                   #Convert data to string
float()                 #Convert data to floating point 
list()                  #Convert a sequence to a list
eval()                  #Evaluates a finite python expression in a string and returns an object 

pycharm interaction

python console (bottom left corner of software)

Classification of operators

  • Arithmetic operator
  • Assignment Operators
  • compound assignment operators
  • Comparison operator
  • Logical operator

Arithmetic operator

operatordescribeexample
+plus1+1
-reduce1-1
*ride2*2
/except10/2
%Surplus9% 4 output is 1
**index2 * * 4 the output result is 16
()parenthesesParentheses are used to improve the operation priority, that is, (1 + 2) * 3, and the output result is 9
/exceptThe output of 10 / 2 is 5
//to be divisible by9 / / 4 the output is 2
  • Priority order of mixed operation: () higher than * * higher than * / /% higher than +-

Assignment Operators

operatordescribeexample
=assignmentAssign the result to the right of = to the variable to the left of the equal sign
  • Single variable assignment
num = 1
print(num)
  • Assignment of multiple variables
num1,float1,str1 =10,0.5,'hello world'
print(num1)
print(float1)
print(str1)
  • Assign the same value to multiple variables
a = b = 10
print(a)
print(b)

compound assignment operators

operatordescribeexample
+=Additive assignment operatorc += a is equivalent to c = c + a
-=Subtraction assignment operatorc -= a is equivalent to c = c - a
*=Multiplication assignment operatorc *= a is equivalent to c = c * a
/=Division assignment operatorc /= a is equivalent to c = c / a
//=Integer division assignment operatorc //= a is equivalent to c = c // a
%=Remainder assignment operatorC% = a is equivalent to C = C% a
**=Power assignment operatorc **= a is equivalent to c = c ** a
  • Note: first calculate the expression on the right of the assignment operator, and then calculate the compound assignment operation

Comparison operator

Comparison operators are also called relational operators, which are usually used to judge.

operatordescribeexample
==Judge equality. If the results of two operands are equal, the condition result is true; otherwise, the condition result is falseIf a=3 and b=3, then (a==b) is true
!=Not equal to. If the results of two operands are not equal, the condition is true; otherwise, the condition is falseIf a=1 and b=3, then (a!=b) is true
>Whether the result of the operand on the left side of the operator is greater than the result of the operand on the right side. If greater than, the condition is true; otherwise, it is falseIf a=7 and b=3, then (a > b) is true
<Whether the result of the operator on the left side of the operator is less than the result of the operand on the right side. If less than, the condition is true; otherwise, it is falseIf a = 7 and B = 3, then (a < b) is false
>=Whether the operand result on the left side of the operator is greater than or equal to the operand result on the right side. If greater than, the condition is true; otherwise, it is falseIf a = 7 and B = 3, then (a > = b) is true
<=Whether the operand result on the left side of the operator is less than or equal to the operand result on the right side. If less than, the condition is true; otherwise, it is falseIf a = 3 and B = 3, then (a < = b) is true

Logical operator

operatorLogical expressiondescribeexample
andx and yOne false is falsetrue and true returns true
orx or yOne truth is one truthfalse or true returns true
notnot xEither true or falsenot true returns false
a = 1
b = 2
c = 3
print((a < b) and (b < c)) #true
print((a > b) and (b < c)) #false
print((a > b) or (b < c))  #true
print(not (a > b))    #true

expand

Logical operation between numbers

a = 0
b = 1
c = 2

# and operator, as long as one value is 0, the result is 0, otherwise the result is the last non-0 number
print(a and b)   # 0
print(b and a)   # 0
print(a and c)   # 0
print(b and c)   # 2
print(c and b)   # 1
#or operator, the result is 0 only if all values are 0, otherwise the result is the first non-0 number
print(a or b)  # 1
print(a or c)  # 2
print(b or c)  # 1

Conditional statement

Suppose a scenario:

  • Have you ever been to an Internet cafe at this age?
  • What is the one thing you must do when you want to surf the Internet? (key considerations)
  • Why give the ID card to the staff?
  • Is it to judge whether you are an adult?
  • If adults can surf the Internet? If you are not an adult, you are not allowed to surf the Internet?

In fact, the so-called judgment here is a conditional statement, that is, if the condition is true, some codes will be executed, and if the condition is not true, these codes will not be executed.

Single branch grammar

if condition:
    Code 1 for conditional execution
    Code 2 for conditional execution
    ......

Multi branch grammar

if condition:
    Code 1 for conditional execution
    Code 2 for conditional execution
    ......
elif condition:
    Code 1 for conditional execution
    Code 2 for conditional execution
    ......
else condition:
    Code 1 for conditional execution
    Code 2 for conditional execution
    ......

expand

age >= 18 and age <= 60 It can be reduced to 18 <= age <= 60

if nesting

if Condition 1:
    Code 1 for conditional execution
    Code 2 for conditional execution
    ......
    
    if Condition 2:
        Code 1 for conditional execution
    	Code 2 for conditional execution
   		......

Random number expansion

import Module name   #Export random module
random.randint(start,end)  #Use the random integer function in the random module

ternary operator

Ternary operators are also called ternary operators or ternary expressions.

The syntax is as follows:

# Expression executed when condition holds if condition else expression executed when condition does not hold

example:

a = 1
b = 2

c = a if a > b else b
print(c)

#Requirement: there are two variables. Compare the size. If variable 1 is greater than variable 2, execute variable 1 - variable 2; Otherwise, variable 2 - variable 1

q =22
w =12
r = q - w if q > w else w - q
print(r)

while Loop

Role of circulation

The function of loop: make the code execute repeatedly more efficiently.

Classification of cycles

In python, loops are divided into while and for, and the final implementation effect is the same.

grammar

while condition:
    Code 1 repeatedly executed when the condition is true
    Code 2 executed repeatedly when the condition is true
    ......

Counter

# Cyclic counter
i = 0
while i < 5:
    print('Daughter in law, I was wrong')
    i+=1
    
print('End of task')

break and continue

break and continue are two different ways to exit a loop when certain conditions are met.

understand

  • break is to terminate the loop
  • continue is the code that exits the current loop and then executes the next loop.

Example: 99 multiplication table

for loop

for Temporary variable in sequence:
    Repeated code 1
    Repeated code 2
    ......

else

Loops can be used with else. The indented code below else refers to the code to be executed after the loop ends normally.

while...else

Syntax:

while condition:
    Code executed repeatedly when the condition is true
else:
    Code to be executed after the loop ends normally
  • Else refers to the code to be executed after the normal end of the loop, that is, if the loop is terminated by break, the code indented below else will not be executed.
  • Because continue is to exit the current cycle and continue the next cycle, the cycle can normally end under the control of continue. When the cycle ends, the else indented code is executed.
for...else

Syntax:

for Temporary variable in sequence:
    Repeatedly executed code
    ...
else:
    Code to be executed after the loop ends normally
  • Else refers to the code to be executed after the normal end of the loop, that is, if the loop is terminated by break, the code indented below else will not be executed.
  • Because continue exits the current cycle and continues the next cycle, the cycle can normally end under the control of continue. When the cycle ends, else indented code is executed.

character string

subscript

"Subscript" is also called "index", which is the number. For example, the function of train seat number: quickly find the corresponding seat according to the number. Similarly, the function of subscript is to quickly find the corresponding data through subscript.

section

Slicing refers to the operation of intercepting part of the operated object. String, list and tuple all support slicing.

grammar

sequence[Start position subscript:End position subscript:step]

be careful

  • It does not contain the data corresponding to the end position subscript, either positive or negative integers;
  • Step size is the selection interval, which can be positive or negative integers. The default step size is 1.

common method

The common operation methods of string include search, modification and judgment.

lookup

The so-called string search method is to find the position or number of occurrences of the substring in the string.

  • find(): check whether a substring is included in the string. If the subscript is returned at the beginning of the substring, otherwise - 1 will be returned.

1. Grammar

String sequence.find(Substring, start position subscript, end position subscript)

Note: the start and end subscripts can be omitted, indicating that they are found in the whole string sequence.

  • index(): check whether a substring is included in the string. If the subscript is returned at the beginning of the substring, otherwise an exception will be reported

1. Grammar

String sequence.index(Substring, start position subscript, end position subscript)

Note: the start and end subscripts can be omitted, indicating that they are found in the whole string sequence.

  • rfind(): the same function as find(), but the search direction starts from the right.

  • rindex(): the same function as index(), but the search direction starts from the right.

  • count(): returns the number of occurrences of a substring in the string

1. Grammar

String sequence.count(Substring, start position subscript, end position subscript)

Note: the start and end subscripts can be omitted, indicating that they are found in the whole string sequence.

modify

Modifying a string means modifying the data in the string in the form of a function.

  • replace(): replace

1. Grammar

String sequence.replace(Old substring, new substring, replacement times)

Note: replacement times: if the occurrence times of the substring are found, the replacement times are the occurrence times of the substring.

After calling the replace function, it is found that the data of the original string has not been modified, and the modified data is the return value of the replace function;

Description string is an immutable data type;

Whether data can be changed is divided into variable type and immutable type.

  • split(): splits the string according to the specified character.

1. Grammar

String sequence.split(Split characters, num)

Note: num indicates the number of split characters. The number of data to be returned is num+1.

Split returns a list, missing split characters;

  • join(): combine strings with one character or substring, that is, combine multiple strings into a new string.

1. Grammar

Character or substring.join(A sequence of multiple strings)

Note: the string data in the merge list is a large string

  • toggle case

    • capitalize(): converts the first character of a string to uppercase.

    Note: after the capitalization () function is converted, only the first character of the string is capitalized, and all other characters are lowercase.

    • title(): converts the first letter of each word in the string to uppercase.

    • lower(): converts uppercase to lowercase in a string.

    • upper(): converts the small case of the string to uppercase.

  • Delete white space characters

    • lstrip(): delete the blank character at the left of the string.
    • rstrip(): deletes the white space character to the right of the string.
    • strip(): delete the blank characters on both sides of the string.
  • string alignment

    • ljust(): returns a new string that is left aligned with the original string and filled to the corresponding length with the specified character (default space). (left)

    1. Grammar

    String sequence.ljust(Length, fill character)
    
    • rjust(): returns a right aligned original string and fills it with a new string of corresponding length with the specified character (default space). The syntax is the same as ljust(). (right)
    • center(): returns a new string centered on the original string and filled with the specified character (default space) to the corresponding length. The syntax is the same as ljust().

judge

The so-called judgment is to judge whether it is true or false. The returned result is Boolean data type: true or false.

  • Startswitch(): check whether the string starts with the specified substring. If yes, it returns true; otherwise, it returns false. If the start and end position subscripts are set, check within the specified range.

1. Grammar

String sequence.startswith(Substring, start position subscript, end position subscript)
  • Endswitch(): determines whether a string ends with a substring

  • isalpha(): returns true if the string has at least one character and all characters are letters; otherwise, returns false.

  • isdigit(): returns true if the string contains only numbers; otherwise, returns false.

  • isalnum(): returns true if the string has at least one character and all characters are letters or numbers; otherwise, returns false.

  • isspace(): returns true if the string contains whitespace; otherwise, returns false.

list

Format of list

[Data 1, data 2, data 3, data 4......]
  • The list can store multiple data at one time and can be of different data types.
  • List data can be modified

Common operations of list

The job of list is to store multiple data at one time. Programmers can operate on these data: add, delete, modify and query.

subscript

Start from 0

  • index(): returns the subscript of the specified data location.

1. Grammar

List sequence.index(Data, start position subscript, end position subscript)

Note: if the searched data does not exist, an error will be reported.

  • count(): counts the number of times the specified data appears in the current list.
  • len(): access list length, that is, the number of data in the list.

Judge whether it exists

  • In: judge whether the specified data is in a list sequence. If true, otherwise false
  • Not in: judge whether the specified data is not in a list sequence. If not, return true; otherwise, return false

Add data to list

Function: add specified data to the list.

  • append(): append data to the end of the list.

1. Grammar

List sequence.append(data)

2. Attention

If the data appended by append() is a sequence, the entire sequence is appended to the list

  • extend(): append data at the end of the list. If the data is a sequence, the data of this sequence will be added to the list one by one.

1. Grammar

List sequence.extend(data)

2. Attention

If it is a sequence, the sequence data will be disassembled and added to the list

  • insert(): add data at the specified location.

1. Grammar

List sequence.insert(Position subscript, data)

List data deletion

  • del

1. Grammar

del target
  • pop(): delete the data of the specified subscript (the last by default) and return the data.

1. Grammar

List sequence.pop(subscript)
  • remove(): removes the first match of a data in the list.

1. Grammar

List sequence.remove(data)
  • clear(): clear the list

List data modification

  • Modify specified subscript data

  • Reverse: reverse()

  • Sort: sort()

1. Grammar

List sequence.sort(key = None,reverse = False)

Note: reverse indicates the collation, reverse = True descending, reverse = False ascending (default)

List copy data

Function copy()

name_list = {'TOM','LILY','ROSE'}

list1 = name_list.copy()

print(list1)
print(name_list)

Loop traversal of list

Requirement: print each data in the list in turn.

while
  • code
name_list = ['TOM','LILY','ROSE']

i = 0
while i < len(name_list):
    print(name_list[i])
    i += 1
for
  • code
name_list = ['Tom','lily','rose']

for i in name_list:
    print(i)

List nesting

The so-called list nesting means that a list contains other sub lists.

Application scenario: the names of students in class 1, 2 and 3 should be stored, and the names of students in each class are in a list.

name_list = [['Xiao Ming','Xiao Hong','Little green'],['tom','lily','rose'],['Zhang San','Li Si','Wang Wu']]

Thinking: how to find the data "Li Si"?

#Step 1: click the subscript to find the list where Li Si is located
print(name_list[2])

#Step 2: from the list where Li Si is located, click the subscript to find the data Li Si
print(name_list[2][1])

tuple

  • Application scenario of tuple
  • Define tuple
  • Tuple common operations

Application scenario of tuple

Think: what if you want to store multiple data, but these data cannot be modified?

A: list? A list can store multiple data at once, but the data in the list can be changed.

num_list = [10,20,30]
num_list[0] = 100

A tuple can store multiple data, and the data in the tuple cannot be modified.

Define tuple

Tuple features: defining tuples uses parentheses and commas to separate various data. Data can be of different data types.

#Multiple data tuples
t1 = (10,20,30)

#Single data tuple
t2 = (10,)

Note: if the defined tuple has only one data, add a comma after the data, otherwise the data type is the only data type of the data

t2 = (10,)
print(type(t2))   #tuple

t3 = (20)
print(type(t3))   #int

t4 = ('hello')
print(type(t4))   #str

Common operations of tuples

Tuple data does not support modification, but only search, as follows:

  • Find data by subscript
typle1 = ('aa','bb','cc','bb')
  • index(): find a data. If the data exists, the corresponding subscript will be returned. Otherwise, an error will be reported. The syntax is the same as the index method of list and string.
typle1 = ('aa','bb','cc','bb')
print(tpple1.index('aa'))
  • count(): counts the number of times a data appears in the current tuple.
tuple1 = ('aa','bb','cc','bb')
print(tuple1.count('bb'))
  • len(): counts the number of data in tuples.
tuple1 = ('aa','bb','cc','bb')
print(len(tuple1))

Tuple modification operation

Note: if the data in the tuple is modified directly, an error will be reported

t1 = ('aa','bb','cc','bb')
t1[0] = 'aaa'

However, if there is a list in the tuple, modifying the data in the list is supported.

t2 = ('aa','bb',['cc','dd'])
print(t2[2])
t2[2][0] = 'ccc'

Dictionaries

Application scenario of dictionary

Thinking 1: if there are multiple data, such as' TOM ',' male ',' 20 ', how to store them quickly?

Answer: List

list1 = ['Tom','male','20']

Thinking 2: how to find the data 'Tom'?

A: just find the data with subscript 0.

list1[0]

Think 3: if the data order changes in the future, as shown below, can you still access the data 'Tom' with list[0]?

list1 = ['male',20,'tom']

A: No, the subscript of the data 'Tom' is 2

Thinking 4: when the data order changes, the subscript of each data will also change. How to ensure that the same standard data is used to find data before and after the data changes?

A: dictionary. The data in the dictionary appears in the form of a key value pair. The dictionary data has nothing to do with the data order, that is, the dictionary does not support subscripts. No matter how the data changes in the later stage, you only need to find the data according to the name of the corresponding key.

Syntax for creating Dictionaries

Dictionary features:

  • The symbol is braces
  • The data is in the form of key value pairs
  • Key value pairs are separated by commas
# There is a data dictionary
dict1 = {'name':'Tom','age':20,'gender':'male'}

# Empty dictionary
dict2 = {}

dict3 = dict()

Common operations of dictionary

increase

Writing method: dictionary sequence [key] = value

Note: if the key exists, modify the value corresponding to the key; If the key does not exist, add this key value pair.

dict1 = {'name':'Tom','age':20,'gender':'male'}

dict1['name'] = 'Rose'
#Results: {name':'Rose','age':20,'gender':'male '}
print(dict1)

dict1['id'] = 110

#{'name':'Rose','age': 20,'gender': 'male', 'id':110}
print(dict1)

Note: the dictionary is of variable type.

Delete

  • del()/del: delete the dictionary or delete the specified key value pair in the dictionary.
dict1 = {'name':'Tom','age':20,'gender':"male"}

del dict1['gender']
#Result: {name':'Tom','age':20}
print(dict1)
  • clear(): clear the dictionary
dict1 = {'name':'Tom','age':20,'gender':"male"}
dict1.clear()

change

Writing method: dictionary sequence [key] = value

Note: if the key exists, modify the value corresponding to the key; If the key does not exist, add this key value pair.

check

key value lookup
dict1 = {'name':'Tom','age':20,'gender':'male'}
print(dict1['name'])
print(dict1['id'])

If the key currently searched exists, the corresponding value is returned; Otherwise, an error is reported.

get()
  • grammar
Dictionary sequence.get(key,Default value)

Note: if the key currently searched does not exist, the second parameter (default value) is returned. If the second parameter is omitted, None is returned.

keys()
dict1 = {'name':'tom','age':20,'gender':'male'}
print(dict1.keys())  #dict_keys(['name','age','gender'])
values()
dict1 = {'name':'tom','age':20,'gender':'male'}
print(dict1.values())  #dict_values(['tom',20,' male '])
items()
dict1 = {'name':'tom','age':20,'gender':'male'}
print(dict1.items())  #dict_items(['name','tom'),('age',20),('gender ',' male '])

Circular traversal of dictionary

key traversing dictionary

dict1 = {'name':'tom','age':20,'gender':'male'}
for key in dict1.keys():
    print(key)

Traverse the value of the dictionary

dict1 = {'name':'tom','age':20,'gender':'male'}
for value in dict1.values():
    print(value)

Traversing dictionary elements

dict1 = {'name':'tom','age':20,'gender':'male'}
for item in dict1.items():
    print(item)

Traverse the key value pairs of the dictionary

dict1 = {'name':'tom','age':20,'gender': 'male'}
for key,value in dict1.items():
    print(f'{key} = {value}')

aggregate

Create collection

Create a collection using {} or set(), but if you want to create an empty collection, you can only use set(), because {} creates an empty dictionary.

s1 = {10,20,30,40,50}
print(s1)

s2 = {10,30,20,10,30,40,30,50}
print(s2)

s3 = set('abcdefg')
print(s3)

s4 = set()
print(type(s4)) #set

s5 = {}
print(type(s5)) #dict

Note: the collection has the function of de duplication

Set data has no order

Collection common operation methods

Add data

  • add()
s1 = {10,20}
s2.add(100)
s1.add(10)
print(s1) #{100,10,20}

Because the set has the function of de duplication, no operation will be performed when the data added to the set is the existing data of the current set.

  • update(), the appended data is a sequence
s1 = {10,20}
#s1.update(100)  #report errors
s1.updata([100,200])
s1.updata('abc')

Delete data

  • remove(), delete the specified data in the collection. If the data does not exist, an error will be reported.
s1 = {10,20}

s1.remove(10)
print(s1)

s1.remove(10)  #report errors
print(s1)
  • discard(), delete the specified data in the collection. If the data does not exist, no error will be reported.
s1 = {10,20}

s1.discard(10)
print(s1)

s1.discard(10)
print(s1)
  • pop(), randomly delete a data in the collection and return the data.
s1 = {10,20,30,40,50}

del_num = s1.pop()
print(del_num)
print(s1)

Find data

  • In: judge whether the data is in the set sequence
  • Not in: judge that the data is not in the set sequence
s1 = {10,20,30,40,50}

print(10 in s1)
print(10 not in s1)

Public operation

1, Operator

operatordescribeSupported container types
+mergeString, list, tuple
*copyString, list, tuple
inDoes the element existString, list, tuple, dictionary
not inDoes the element not existString, list, tuple, dictionary

2, Public method

functiondescribe
len()Calculate the number of elements in the container
Del or del()delete
max()Returns the maximum value of the element in the container
min()Returns the minimum value of the element in the container
range(start,end,step)Generate a number from start to end in step for the for loop
enumerate()The function is used to combine a traversable data object (such as list, tuple or string) into an index sequence, and list data and data subscripts at the same time. It is generally used in the for loop.

Note: the sequence generated by range() does not contain the end number

enumerate(Traversable object,start=0)    #The start parameter is used to set the starting value of the subscript of traversal data. The default value is 0
#The returned result is a tuple. The first data of the tuple is the subscript corresponding to the data of the original iteration object, and the second data of the tuple is the data of the original iteration object

list1 = ['a','b','c','d','e']
for i in enumerate(list1):
    print(i)
    
for index,char in enumerate(list1,start=1):
    print(f'The subscript is{index},The corresponding character is{char}')

Container type conversion

tuple()

Function: convert a sequence into tuples

list()

Function: convert a sequence into a list

set()

Function: convert a sequence into a set

Note: 1. The collection can quickly complete the list de duplication

2. The collection does not support subscripts

Derivation

  • List derivation
  • Dictionary derivation
  • Set derivation

List derivation

Function: use an expression to create a regular list or control a regular list.

List derivation is also called list generation.

  • while loop implementation
# 1. Prepare an empty list
list1 = []

# 2. Write cycle, and add numbers to the empty list list1 in turn
i = 0
while i < 10:
    list1.append(i)
    i += 1
print(list1)
  • for loop implementation
list1 = []
for i in range(10):
    list1.append(i)

print(list1)
  • List derivation implementation
list1 = [i for i in range(10)]  # Return data traversal data
print(list1)

List derivation with if

Requirement: create an even list of 0-10

  • Method 1: range() step implementation
list1 = [i for i in range(0,10,2)]
print(list1)
  • Method 2: if implementation
list1 = [i for i in range(10) if i % 2 == 0]
print(list1)

Multiple for loops implement list derivation

Requirement creation list is as follows:

[(1,0),(1,2),(1,2),(2,0),(2,1),(2,2)]
  • The code is as follows:
list1 = [(i,j) for i in range(1,3) for j in range(3)]
print(list1)

Dictionary derivation

Think: if there are two lists:

list1 = ['name','age','gender']
list2 = ['tom',20,'man']

How to quickly merge into one dictionary?

Dictionary derivation

Dictionary derivation function: quickly merge the list into a dictionary or extract the target data in the dictionary,

#Create a dictionary: the dictionary key is a number from 1 to 5, and the value is the power of 2
dict1 = {i: i**2 for i in range(1,5)}
print(dict1) #{1:1,2:4,3:9,4:16}

Merge the two lists into one dictionary

list1 = ['name','age','gender']
list2 = ['tom',20,'man']

dict1 = {list1[i]:list2[i] for i in range(len(list1))}
print(dict1)

Note: if the number of data in two lists is the same, len can count the length of any list

If the number of data in two lists is different, the number of list data with more len statistics will report an error, and the number of list data with less len statistics will not report an error.

Extract target data from dictionary

counts = {'MBP':268,'HP':125,'DELL':201,'Lenovo':199,'acer':99}
#Demand; Extract dictionary data with the above number of computers greater than or equal to 200
count1 ={key : value for key,value in counts.items() if value >= 200 }
print(count1)

Set derivation

Requirement: create a set with data to the power of 2 in the list below

list1 = [1,1,2]
set1 = {i ** 2 for i in list1}
print(set1)

The collection has the function of data De duplication

Function basis

  • Function function
  • To use a function
  • Parameter action of function
  • Function return value
  • Documentation for functions
  • Function nesting

Function function

Demand: users withdraw money from ATM:

1. After entering the password, the "select function" interface is displayed

2. After querying the balance, the "select function" interface is displayed

3. After taking 2000, the "selection function" interface is displayed

Feature: display the "selection function" interface, which needs to be repeatedly output to the user, then do you want to implement it?

Definition of function: a function is to integrate a piece of code block with independent functions into a whole and name it, and call the name where necessary to complete the corresponding requirements.

In the development process of function, code reuse can be realized more efficiently.

Define function

def Function name(parameter):
    Code 1
    Code 2
    ......

Call function

Function name(parameter)

be careful:

1. Parameters are optional for different requirements.

2. In python, functions must be defined before use.

case

1. Build the overall framework (reproduction requirements)

print('The password is correct and the login is successful')

#The 'Select function' interface is displayed

print('Balance query completed')

#The "select function" interface is displayed

print('I withdrew 2000 yuan')

#The "select function" interface is displayed

2. Confirm the "select function" interface

print('Check the balance')
print('deposit')
print('withdraw money')

3. Package selection function“

Note: we must first define functions and then call functions.

#Encapsulating ATM function options -- defining functions
def select_func():
    print('-----Please select a function-----')
    print('Check the balance')
    print('deposit')
    print('withdraw money')
    print('-----Please select a function-----')

4. Call function

Call the function where you want to display the "select function" function.

print('The password is correct and the login is successful')
#Display "select function" interface -- call function
select_func()

Considerations for functions

1. Parameters are optional for different requirements.

2. In python, functions must be defined and used first.

Parameter action of function

Thinking: the completion requirements are as follows: how to write a program when a function completes the addition of two numbers 1 and 2?

# Define function
def add_num1():
    result = 1 + 2
    print(result)
    
#Call function
add_num1()

Thinking: the above add_num1 function can only complete the · addition of numbers 1 and 2. If you want this function to be more flexible, you can add the sum of any two numbers specified by the user. How to write the program?

Analysis: if the user needs to specify a specific number when calling the function, the number specified by the user needs to be received when defining the function. The number specified when calling the function and the number received when defining the function are the parameters of the function.

#When defining the function, the parameters a and b for receiving user data are defined at the same time. A and b are formal parameters
def add_num2(a,b):
    result = a + b
    print(result)
    
#When calling the function, real data 10 and 20 are passed in, and the real data is an argument
add_num2(10,20)

Function return value

For example, when we go shopping in the supermarket, such as buying cigarettes, will the salesperson return us the product of cigarettes after giving the money? In the function, if we need to return the result to the user, we need to use the return value of the function.

def buy():
    return 'smoke'


#Use variables to save function return values
goods = buy()
print(goods)

application

Requirements: make a calculator, calculate the sum of any two numbers, and save the results.

def sum_num(a,b):
    return a + b

#Save the return value of the function with the result variable
result = sum_num(1,2)
print(result)

Documentation for functions

Thinking: after defining a function, how can a programmer write a program that can quickly prompt the function?

Answer: Notes

Think: if there is a lot of code, do we need to find the location of this function definition in a lot of code to see the comments? What if you want to view the function more conveniently?

Answer: function description document

Note: the function description document is also called the function description document.

grammar

help()  #Function of help function: view the function description document (function explanation information)

def Function name(parameter):                  #Expression 1
    """Describe the location of the document"""
    code

def Function name(parameter):                #Expression 2 (press enter in the middle of multi line comments to automatically generate parameter description)
    """
    Parameter one
    Parameter two
    Describe the location of the document"""
    code    
help(Function name)

Function nested call

The so-called function nested call means that another function is called in one function

  • Example
def testB():
    print('--- testB start ----')
    print('Here is testB Code executed by function...(ellipsis)...')
    print('---- testB end----')
        
def testA():
    print('---- testA start----')
    testB()
    print('---- testA end----')
    
testA()

Print graphics

1. Print a horizontal line

def print_line():
    print('-' * 20)
    
    
print_line()

2. Print multiple horizontal lines

def print_line():
    print('-' * 20)
    
def print_lines(num):
    i = 0
    whlie i < num:
        print_line()
        i += 1
print_lines(5)

Function calculation

1. Find the sum of three numbers

def sum_num(a,b,c):
    return a + b + c


result = sum_num(1,2,3)
print(result)  #6

2. Average the three numbers

def sum(a,b,c):
    return a + b + c
def avg(a,b,c):
    sun = sum(a,b,c)
    return sun / 3
giao = avg(1,2,3)
print(giao)

Function upgrade

  • Variable scope
  • Multi function program execution flow
  • Return value of function
  • Parameters of function
  • Unpack and exchange the values of two variables
  • quote
  • Variable and immutable types

Variable scope

Variable scope refers to the effective range of variables, which is mainly divided into two categories: local variables and global variables.

  • local variable

The so-called local variables are variables defined inside the function body, that is, they only take effect inside the function body.

def testA():
    a = 100
    
    print(a)
    
    
testA()  #100
print(a) #Error: name "a" is not defined

Variable a is a variable defined inside the testA function. If it is accessed outside the function, an error will be reported immediately.

Function of local variable: temporarily save data inside the function body, that is, destroy the local variable after the function call is completed.

  • global variable

The so-called global variable refers to the variable that can take effect both inside and outside the function.

Think: what if there is A data to be used in both function A and function B?

A: store this data in a global variable.

# Define global variable a
a = 100


def testA():
    print(a)    #Access global variable a and print the data stored in variable a
    
def testB():
    print(a)  #Access global variable a and print the data stored in variable a
    
    
testA()  #100
testB()  #100

Modify global variables

Thinking: the testB function needs to modify the value of variable a to 200. How to modify the program?

a = 100

def testA():
    print(a)
    
def testB():
    a = 200
    print(a)
    
testA() #100
testB()  #200
print(f'global variable a = {a}')  #Global variable a = 100

Think: is the variable a in a = 200 inside the testB function modifying the global variable a?

A: No. Observing the above code, it is found that the data of a obtained in line 15 is 100, which is still the value when defining the global variable a, but does not return the internal 200 of testB function. Therefore, a = 200 in testB function defines a global variable.

Thinking: how to modify global variables inside the function body?

a = 100

def testA():
    print(a)
    
    
def testB():
    #Global keyword declares that a is a global variable
    global a
    a = 200
    print(a)

Multi function program execution flow

Generally, in the actual development process, a program is often composed of multiple functions (classes will be explained later), and multiple functions share some data, as shown below:

  • Shared global variables
#1. Define global variables
glo_num = 0

def test1():
    global glo_num
    #Modify global variables
    glo_num = 100
    
    
def test2():
    #Call the modified global variable in test1 function
    print(glo_num)
    
#2. Call test1 function and execute the internal code of the function: declare and modify global variables
test1()
#3. Call test2 function and execute the internal code of the function: print
test2() #100
  • The return value is passed as a parameter
def test1():
    return 50

def test2(num):
    print(num)
    
#1. Save the return value of function test1
result =test1()


#2. Pass the variable of the function return value as a parameter to the test2 function
test2(result)   #50

Return value of function

Think: if a function returns two returns (as shown below), how does the program execute?

def return_num():
    return 1
	return 2

result = return_num()
print(result)  #1

A: only the first return is executed because return can exit the current function, so the code below return will not be executed

Think: if a function needs to have multiple return values, how to write code?

def return_num():
    return 1,2


result = return_num()

Note: 1.return can directly return writing tuples, lists, dictionaries and multiple values

2.return a,b is written. When multiple data are returned, the default is tuple type

Parameters of function

Position parameters

Positional parameters: when calling a function, parameters are passed according to the parameter positions defined by the function.

def user_info(name,age,gender):
    print(f'What's your name{name},Age is{age},Gender is{gender}')
    
user_info('TOM',20,'male')

Note: the order and number of parameters passed and defined must be consistent.

Keyword parameters

Function call, specified in the form of "key = value". It can make the function clearer and easier to use, and also clarify the sequence requirements of parameters.

def user_info(name,age,gender):
    print(f'What's your name{name},Age is{age},Gender is{gender}')
    
    
user_info('Rose',age=20,gender='female')
user_info('Xiao Ming',gender='male',age=16)

Note: when calling a function, if there is a location parameter, the location parameter must be in front of the keyword parameter, but there is no order between the keyword parameters.

Default parameters

Default parameters are also called default parameters. They are used to define functions and provide default values for parameters. The value of the default parameter may not be passed when calling functions (Note: all location parameters must appear in front of the default parameters, including function definition and call)

def user_info(name,age,gender='male'):
    print(f'What's your name{name},Age is{age},Gender is{gender}')
    
    
user_info('TOM',20)
user_info('Rose',18,'female')

Note: when calling a function, if the value is passed for the default parameter, the default parameter value will be modified; Otherwise, use this default value.

Indefinite length parameter

Variable length parameters are also called variable parameters. It is used for scenarios where multiple parameters will be passed during uncertain calls (it is OK not to pass parameters). At this time, you can package location parameters or package keyword parameters to transfer parameters, which will be very convenient.

  • Package location transfer
def user_info(*args):          #The default is * args (this is the bottom layer), but args can be replaced
    print(args)
    
#('TOM',)
user_info('TOM')
#('TOM',18)
user_info('TOM',18)

be careful; All the parameters passed in will be collected by the args variable, which will be combined into a tuple according to the position of the parameters passed in. Args is a tuple type, which is package location transfer.

  • Package keyword delivery
def user_info(**kwargs):
    print(kwargs)
    
    
    
#('name':'TOM','age':18,'id':110)
user_info('TOM',age=18,id=110)

Note: keyword packet return is dictionary type

To sum up: both package location transfer and package keyword transfer are a process of package grouping.

Unpacking and exchanging variable values

Unpacking
  • Unpacking: tuples
def return_num():
    return 100,200



num1,num2 = return_num()
print(num1)   #100
print(num2)   #200
  • Unpacking: Dictionary
dict1 = {'name':'TOM','age':18}
a,b = dict1

#Unpack the dictionary and take out the key of the dictionary
print(a)   #name
print(b)    #age

print(dict1[a])  #TOM
print(dict1[b])   #18

Exchange variable values

Demand: there are variables a = 10 and b = 20. Exchange the values of the two variables

  • Method 1

The data is stored by means of a third variable.

# 1. Define intermediate variables
c = 0

#2. Store the data of a to c
c = a

#3. Assign the data 20 of b to a, where a = 20
a = b

#4. Assign the data 10 of the previous c to B, where b = 10
b = c

print(a)  #20
print(b)  #10
  • Method 2
a,b =1,2
a,b = b,a
print(a)
print(b)

quote

In python, values are passed by reference.

We can use id() to determine whether two variables are references to the same value. We can understand the id value as the address identification of that memory.

  • int type (immutable type)
#1.int type (immutable type) will independently open up memory space for storage
a = 1
b = a

print(b) #1

print(id(a))   #140708464157520
print(id(b))   #140708464157520

a = 2
print(b)  #1. Description: int type is immutable

  • List (variable type)
#2. List
aa = [10,20]
bb = aa
print(id(aa))  #2500998619656
print(id(bb))  #2500998619656

aa.append(30) 
print(id(aa)) #2500998619656
print(id(bb)) #2500998619656

Reference as argument

def test1(a):
    print(a)
    print(id(a))
    
    a += a
    
    print(a)
    print(id(a))
    
#int: different id values before and after calculation
b = 100
test1(b)

#List: the id values before and after calculation are the same

c = [11,22]
test1(c)

Variable and immutable types

The so-called variable type and immutable type mean that data can be modified directly. If it can be modified, it is variable, otherwise it is immutable.

  • Variable type
    • list
    • Dictionaries
    • aggregate
  • Immutable type
    • integer
    • float
    • character string
    • tuple

Function enhancement

target

  • Application: student management system
  • recursion
  • lambda expressions
  • Higher order function

Application: student management system

System introduction

Requirements: enter the system display system function interface, and the functions are as follows:

  • Add student
  • Delete student
  • Modify student information
  • Query student information
  • Display all student information
  • Exit the system

The system has 6 functions, which users can select according to their own needs.

1.2 step analysis

1. Display function interface

2. User input function serial number

3. Execute different functions (functions) according to the function serial number entered by the user

3.1 defining functions

3.2 calling functions

Overall framework

# Define function interface function
def info_print():
    print('Please select a function.......')
    print('1,Add student')
    print('2,Delete student')
    print('3,Modify student')
    print('4,Query students')
    print('5,Show all students')
    print('6,Exit the system')
    print('-'*20)
# 1. Display interface
while True:
    info_print()
    # 2. According to the functions entered by the user
    user_num = int(input('Please enter the function serial number:'))

    #3. Execute different functions (functions) according to the function serial number entered by the user
    # If the user enters 1. Execute the addition; If the user enters 2. Execute delete
    if user_num == 1:
        print('add to')
    elif user_num == 2:
        print('delete')
    elif user_num == 3:
        print('modify')
    elif user_num == 4:
        print('query')
    elif user_num == 5:
        print('Show all students')
    elif user_num == 6:
        print('Exit the system')

1.3 requirements realization

All function functions operate student information. All stored student information should be a global variable with the data type of list.

info = []
1.3.1 display function interface

Define function print_info, responsible for displaying system functions.

# Define function interface function
def info_print():
    print('Please select a function.......')
    print('1,Add student')
    print('2,Delete student')
    print('3,Modify student')
    print('4,Query students')
    print('5,Show all students')
    print('6,Exit the system')
    print('-'*20)
# 1. Display interface
while True:
    info_print()
1.3.2 adding students
  • requirement analysis

1. Receive the student information entered by the user and save it

2. Judge whether to add student information

2.1 if the student's name already exists, an error will be reported

2.2 if the student's name does not exist, prepare an empty dictionary, add the data entered by the user to the dictionary, and then add dictionary data to the list

3. Call this function where the corresponding if condition holds

  • code implementation
# Define add function
def info_add():
    """Add student function"""
    #Receive user input student information
    new_id=input("Please enter student number:")
    new_name=input('Please enter your name:')
    new_tel=input("Please enter phone number:")

    global info   #Declare global variables
    for i in info:      #Determine whether to duplicate the name
        if new_name == i['name']:
            print('This user exists!')
            return


    info_dict = {}
    info_dict['id'] = new_id
    info_dict['name'] = new_name
    info_dict['tel'] = new_tel

    info.append(info_dict)
1.3.3 delete student
  • requirement analysis

Delete according to the student name entered by the user

1. The user enters the name of the target student

2. Check whether the student exists

2.1 if it exists, delete the data from the list

2.2 if it does not exist, it will prompt "the user does not exist"

3. Call the function where the corresponding if condition holds

  • code implementation
#Define delete student
def info_del():
    """Delete student"""
    del_name = input('Please enter the name of the student to delete:')

    global info
    for i in info:
        if del_name == i['name']:
            info.remove(i)
            break
    else:
        print('The student does not exist')

    print(info)

1.3.4 modify student information
  • requirement analysis

1. The user enters the name of the target student

2. Check whether the student exists

2.1 if it exists, modify the student's information, such as mobile phone number

2.2 if it does not exist, an error is reported

3. Call the function where the corresponding if condition holds

  • code implementation
#Define and modify students
"""Modify student"""
def info_alt():
    alt_name =input('Please enter student name')
    global info
    for i in info:
        if alt_name == i['name']:
            i['tel'] = input("Please enter a new phone number")
            break
    else:
        print("The student does not exist")
1.3.5 query student information
  • requirement analysis
  1. User input target student name

  2. Check if the delegates are present

    2.1 if it exists, the information of this student will be displayed

    2.2 if it does not exist, an error will be reported

  3. Call this function where the corresponding if condition holds

  • code implementation
#Query student information

def info_find():
    """Query students"""
    find_name = input('Please enter the name of the student you want to find:')
    global info
    for i in info:
        if find_name == i["name"]:
            print('The information found is as follows......')
            print(f"The student number of the student is{i['id']},Name is{i['name']},The phone number is{i['tel']}")
            break
    else:
        print('No one was found')    

1.3.6 display all student information
  • requirement analysis

Print all student information

  • code implementation
#Display all student information
def info_printall():
    """Display all student information"""
    print('Student number\t full name\t cell-phone number')
    for i in info:
        print(f"{i['id']}\t{i['name']}\t{i['tel']}")

1.3.7 exit the system

When the user enters the function No. 6, he / she should exit the system. The code is as follows:

    elif user_num == 6:
        info_exit = input('Are you sure you want to exit the program? yes sign out no Don't quit')
        if info_exit == 'yes':
            break
1.3.8 complete code
info = []

# Define function interface function
def info_print():
    print('Please select a function.......')
    print('1,Add student')
    print('2,Delete student')
    print('3,Modify student')
    print('4,Query students')
    print('5,Show all students')
    print('6,Exit the system')
    print('-'*20)



# Define add function
def info_add():
    """Add student function"""
    #Receive user input student information
    new_id=input("Please enter student number:")
    new_name=input('Please enter your name:')
    new_tel=input("Please enter phone number:")

    global info   #Declare global variables
    for i in info:      #Determine whether to duplicate the name
        if new_name == i['name']:
            print('This user exists!')
            return

    info_dict = {}
    info_dict['id'] = new_id
    info_dict['name'] = new_name
    info_dict['tel'] = new_tel

    info.append(info_dict)


#Define delete student
def info_del():
    """Delete student"""
    del_name = input('Please enter the name of the student to delete:')

    global info
    for i in info:
        if del_name == i['name']:
            info.remove(i)
            break
    else:
        print('The student does not exist')

    print(info)

#Define and modify students
"""Modify student"""
def info_alt():
    alt_name =input('Please enter student name')
    global info
    for i in info:
        if alt_name == i['name']:
            i['tel'] = input("Please enter a new phone number")
            break
    else:
        print("The student does not exist")

#Query student information

def info_find():
    """Query students"""
    find_name = input('Please enter the name of the student you want to find:')
    global info
    for i in info:
        if find_name == i["name"]:
            print('The information found is as follows......')
            print(f"The student number of the student is{i['id']},Name is{i['name']},The phone number is{i['tel']}")
            break
    else:
        print('No one was found')

#Display all student information
def info_printall():
    """Display all student information"""
    print('Student number\t full name\t cell-phone number')
    for i in info:
        print(f"{i['id']}\t{i['name']}\t{i['tel']}")

# 1. Display interface
while True:
    info_print()
    # 2. According to the functions entered by the user
    user_num = int(input('Please enter the function serial number:'))

    #3. Execute different functions (functions) according to the function serial number entered by the user
    # If the user enters 1. Execute the addition; If the user enters 2. Execute delete
    if user_num == 1:
        info_add()
    elif user_num == 2:
        info_del()
    elif user_num == 3:
        info_alt()
    elif user_num == 4:
        info_find()
    elif user_num == 5:
        info_printall()
    elif user_num == 6:
        info_exit = input('Are you sure you want to exit the program? yes sign out no Don't quit')
        if info_exit == 'yes':
            break
    else:
        print("The function serial number entered is incorrect")

Recursive and anonymous functions

recursion

1. Recursive application scenarios

Recursion is a programming idea. Application scenarios:

  1. In our daily development, if we want to traverse all the files under a folder, we usually use recursive implementation;
  2. In the subsequent algorithm courses, many algorithms are inseparable from recursion, such as quick sorting.

2. Recursive characteristics

  • The function is called internally
  • There must be an exit

3. Application: Digital summation within 3

  • code
# 3 + 2 + 1
def sum_numbers(num):
    # 1. If it is 1, directly return to 1 - exit
    if num == 1:
        return 1     #Function of return: return value and exit function
    # 2. If it is not 1, repeat the accumulation and return the result
    return num + sum_numbers(num-1)

sum_result = sum_numbers(3)
#The output is 6
print(sum_result)

lambda expressions

Application scenario of lambda

If a function has a return value and only one sentence of code, you can use lambda to simplify it.

lambda syntax

lambda parameter list : expression
  • The parameters of lambda expression are optional, and the parameters of function are fully applicable in lambda expression.
  • lambda expressions can accept any number of parameters, but can only return the value of one expression.

application

def fn1():
    return 100

ws =fn1()
print(ws)

wq = lambda:200
print(wq())

Note: the lambda expression is printed directly, and the memory address of the lambda is output

Application: calculate a+ b

def add(a,b):
    return a + b
print(add(1,2))


aq =lambda a,b:a+b
print(aq(1,2))

Parameter form of lambda

  • No parameters
wq =lambda:100
print(wq())
  • One parameter
wq =lambda i : i
print(wq('hello python'))
  • Default parameters
wq =lambda a,b,c=100:a+b+c
print(wq(10,20))
  • Positional variable parameter: * args (return tuple)
wq = lambda *args: args
print(wq(10,20,30))
  • Keyword variable parameter: * * kwargs (return Dictionary)
wq = lambda **kwargs: kwargs
print(wq(name='python',giao='1234'))

Application of lambda

lambda with judgment
wq = lambda a,b: a if a > b else b
print(fn1(1000,500))
The list data is sorted by the value of the dictionary key
students =[
    {'name':'TOM','age':20},
    {'name':'giao','age':17},
    {'name':'jack','age':22}
]
#1. Sort the values corresponding to name key in ascending order
students.sort(key=lambda x:x['name'])

#2. Sort the values corresponding to name key in descending order
students.sort(key=lambda x:x['name'],reverse=True)

#3. Sort the values corresponding to the age key
students.sort(key=lambda x:x['age'])

Higher order function

The function is passed in as a parameter. Such a function is called a high-order function, which is the embodiment of functional programming. Functional programming refers to this highly abstract programming paradigm

Experience higher order functions

In python, the abs() function can calculate the absolute value of a number.

abs(-10)  #10

The round() function completes the rounding calculation of numbers.

round(1.2)  #1
round(1.9)   #2

Demand: sum any two numbers after sorting them according to the specified requirements.

  • Method 1
def add_ num(a,b):
    return abs(a) + abs(b)

result = add_num(-1,2)
print(result)  #3
  • Method 2
def sum_num(a,b,f):
    return f(a) +f(b)

result = sum_num(-1,2,abs)
print(result)  #3

Note: after comparing the two methods, it is found that the code of method 2 will be more concise and the function flexibility will be higher. Functional programming uses a lot of functions to reduce the repetition of code, so the program is relatively short and the development speed is fast.

Built in higher order function

map()

map(func,lst), apply the passed function variable func to each element of the lst variable, and form the result into a new list (python2) / iterator (python3).

Requirement: calculate the power 2 of each number in list1 sequence.

list1  = [1,2,3,4,5]


def func(x):
    return x ** 2

result = map(func,list1)

print(result)  #<map object at 0x000001A0FFE8E7F0>
print(list(result))  #[1,4,9,16,25]
reduce()

reduce(func,lst), where func must have two parameters. The result of each func calculation continues to accumulate with the next element of the sequence.

Note: the parameter func passed in by reduce() must receive 2 parameters.

Requirement: calculate the cumulative sum of each number in list1 sequence.

import functools

list1 = [1,2,3,4,5]

def func(a,b):
    return a + b

result = functools.reduce(func,list1)

print(result) #15
filter()

The filter(func,lst) function is used to filter the sequence, filter out unqualified elements, and return a filter object. If you want to convert to a list, you can use list() to convert.

list1 = [1,2,3,4,5,6,7,8,9,10]

def wqw(x):
    return x%2==0

result = filter(wqw,list1)
print(list(result))

File operation

  • Role of file operation
  • Basic operation of files
    • open
    • Reading and writing
    • close
  • File backup
  • Operation of files and folders

Role of file operation

Summary: the function of file operation is to store some contents (data), which can be used directly the next time the program is executed without having to make a new copy, saving time and effort.

Basic operation of files

File operation steps

1. Open file

2. Read and write operations

3. Close file

Note: you can only open and close files without any read-write operations.

open

In python, you can use the open function to open an existing file or create a new file. The syntax is as follows:

open(name,mode)

Name: is the string of the name of the target file to be opened (which can contain the specific path where the file is located).

Mode: set the mode of opening files (access mode): read-only, write, append, etc.

Open file mode

patterndescribe
rOpen the file as read-only. The pointer to the file will be placed at the beginning of the file. This is the default mode.
rbOpen a file in binary format for read-only. The file pointer will be placed at the beginning of the file. This is the default mode.
r+Open a file for reading and writing. The file pointer will be placed at the beginning of the file.
rb+Open a file in binary format for reading and writing. The file pointer will be placed at the beginning of the file.
wOpen a file for writing only. If the file already exists, open the file and edit it from the beginning, that is, the original content will be deleted. If the file does not exist, create a new file.
wbOpen a file in binary format for writing only. If the file already exists, open the file and edit it from the beginning, that is, the original content will be deleted. If the file does not exist, create a new file.
w+Open a file for reading and writing. If the file already exists, open the file and edit it from the beginning, that is, the original content will be deleted. If the file does not exist, create a new file.
wb+Open a file in binary format for reading and writing. If the file already exists, open the file and edit it from the beginning, that is, the original content will be deleted. If the file does not exist, create a new file.
aOpen a file for append. If the file already exists, the file pointer will be placed at the end of the file. That is, the new content will be written after the existing content. If the file does not exist, create a new file for writing.
abOpen a file in binary format for append. If the file already exists, the file pointer will be placed at the end of the file. That is, the new content will be written after the existing content. If the file does not exist, create a new file for writing.
a+Open a file for reading and writing. If the file already exists, the file pointer will be placed at the end of the file. The file is opened in append mode. If the file does not exist, create a new file for reading and writing.
ab+Open a file in binary format for append. If the file already exists, the file pointer will be placed at the end of the file. If the file does not exist, create a new file for reading and writing.

Order function

In python, the abs() function can calculate the absolute value of a number.

abs(-10)  #10

The round() function completes the rounding calculation of numbers.

round(1.2)  #1
round(1.9)   #2

Demand: sum any two numbers after sorting them according to the specified requirements.

  • Method 1
def add_ num(a,b):
    return abs(a) + abs(b)

result = add_num(-1,2)
print(result)  #3
  • Method 2
def sum_num(a,b,f):
    return f(a) +f(b)

result = sum_num(-1,2,abs)
print(result)  #3

Note: after comparing the two methods, it is found that the code of method 2 will be more concise and the function flexibility will be higher. Functional programming uses a lot of functions to reduce the repetition of code, so the program is relatively short and the development speed is fast.

Built in higher order function

map()

map(func,lst), apply the passed function variable func to each element of the lst variable, and form the result into a new list (python2) / iterator (python3).

Requirement: calculate the power 2 of each number in list1 sequence.

list1  = [1,2,3,4,5]


def func(x):
    return x ** 2

result = map(func,list1)

print(result)  #<map object at 0x000001A0FFE8E7F0>
print(list(result))  #[1,4,9,16,25]
reduce()

reduce(func,lst), where func must have two parameters. The result of each func calculation continues to accumulate with the next element of the sequence.

Note: the parameter func passed in by reduce() must receive 2 parameters.

Requirement: calculate the cumulative sum of each number in list1 sequence.

import functools

list1 = [1,2,3,4,5]

def func(a,b):
    return a + b

result = functools.reduce(func,list1)

print(result) #15
filter()

The filter(func,lst) function is used to filter the sequence, filter out unqualified elements, and return a filter object. If you want to convert to a list, you can use list() to convert.

list1 = [1,2,3,4,5,6,7,8,9,10]

def wqw(x):
    return x%2==0

result = filter(wqw,list1)
print(list(result))

File operation

  • Role of file operation
  • Basic operation of files
    • open
    • Reading and writing
    • close
  • File backup
  • Operation of files and folders

Role of file operation

Summary: the function of file operation is to store some contents (data), which can be used directly the next time the program is executed without having to make a new copy, saving time and effort.

Basic operation of files

File operation steps

1. Open file

2. Read and write operations

3. Close file

Note: you can only open and close files without any read-write operations.

open

In python, you can use the open function to open an existing file or create a new file. The syntax is as follows:

open(name,mode)

Name: is the string of the name of the target file to be opened (which can contain the specific path where the file is located).

Mode: set the mode of opening files (access mode): read-only, write, append, etc.

Open file mode

patterndescribe
rOpen the file as read-only. The pointer to the file will be placed at the beginning of the file. This is the default mode.
rbOpen a file in binary format for read-only. The file pointer will be placed at the beginning of the file. This is the default mode.
r+Open a file for reading and writing. The file pointer will be placed at the beginning of the file.
rb+Open a file in binary format for reading and writing. The file pointer will be placed at the beginning of the file.
wOpen a file for writing only. If the file already exists, open the file and edit it from the beginning, that is, the original content will be deleted. If the file does not exist, create a new file.
wbOpen a file in binary format for writing only. If the file already exists, open the file and edit it from the beginning, that is, the original content will be deleted. If the file does not exist, create a new file.
w+Open a file for reading and writing. If the file already exists, open the file and edit it from the beginning, that is, the original content will be deleted. If the file does not exist, create a new file.
wb+Open a file in binary format for reading and writing. If the file already exists, open the file and edit it from the beginning, that is, the original content will be deleted. If the file does not exist, create a new file.
aOpen a file for append. If the file already exists, the file pointer will be placed at the end of the file. That is, the new content will be written after the existing content. If the file does not exist, create a new file for writing.
abOpen a file in binary format for append. If the file already exists, the file pointer will be placed at the end of the file. That is, the new content will be written after the existing content. If the file does not exist, create a new file for writing.
a+Open a file for reading and writing. If the file already exists, the file pointer will be placed at the end of the file. The file is opened in append mode. If the file does not exist, create a new file for reading and writing.
ab+Open a file in binary format for append. If the file already exists, the file pointer will be placed at the end of the file. If the file does not exist, create a new file for reading and writing.

Posted by piersk on Sun, 21 Nov 2021 19:00:38 -0800