Python core programming

Posted by kooks on Tue, 22 Feb 2022 06:37:41 +0100

1. Preface

1.1 access to resources

Browser input: code tarena. com. cn

Account No.: tarenacode

Password: Code_ two thousand and thirteen

Address: AIDCode/aid2202/01_month01/to_student_for_month01.zip

1.2 Course Introduction

1.3 learning philosophy

1.3.1 weak grammar, emphasizing essence

It is a learning process that weakens language rules and pays attention to procedural principles.

Grammar is a representation. Only by understanding the deep mechanism can it be used flexibly.

Learning programming needs to go deep into memory and analyze the principle, so as to see through the grammar.

Tai Chi's principle of "exerting force before mind" is like that of "exerting force before mind".

1.3.2 technology, more art

Programming is not only a technology, but also an art.

Write high-quality code (functionality, maintainability, flexibility) and enjoy the fun of programming.

1.3.3 project oriented and practical

2048 core algorithm runs through the core of Python.

The epidemic information management system runs through object-oriented.

The integrated operation framework runs through Python advanced.

Second hand housing information management system runs through the whole stage.

1.4 learning methods

1.4.1 the knowledge of the day must be understood

What is, that is to understand the definition of knowledge points.

Why, that is to understand the role of knowledge points.

Where is the applicability of understanding knowledge points.

How to use is to understand the grammar of knowledge points.

1.4.2 you must be able to do exercises on the same day

See demo01, demo02 with your eyes in class presentation

Class practice, knock exercise01, exercise02

Only when you finish it alone can you do it.

2. Introduction to Python

2.1 computer infrastructure

2.1.1 hardware

In 1944, American Hungarian mathematician von Neumann proposed the basic structure of computer.

Five components: arithmetic unit, controller, memory, input device and output device.

– arithmetic unit: process the data according to the instructions in the program.

– controller: command all parts of the computer to coordinate work according to program requirements.

Generally, the arithmetic unit and controller are integrated in the central processing unit (CPU).

– memory: store the data information of various programs.

Memory RAM – small capacity, fast speed, temporary storage of data

Hard disk HDD – large capacity, slow speed, permanent storage of data


Input device: a device that transmits information from the outside to a computer.

For example: mouse, keyboard, scanner

Output device: a device by which a computer transmits information to the outside world.

For example: monitor, audio, printer

2.1.2 software

Operating system:

– a program that manages and controls computer software and hardware resources.

– isolate the differences between different hardware to simplify software development.

​ – Windows,Linux,Unix.

Application software: software developed for a specific purpose.

Software: program + document.

– a program is a set of instructions that a computer can recognize and execute.

– documentation is illustrative information required to facilitate understanding of the program.

2.2 basic knowledge

2.2.1 Python definition

Is a free, open source, cross platform, dynamic, object-oriented programming language.

2.2.2 execution mode of Python program

2.2.2.1 interactive

Enter the command on the command line and press enter to get the result.

(1) Open terminal

(2) Enter interactive: Python 3

(3) Write code: print("hello world")

(4) Leave interactive: exit()

2.2.2.2 document type

Write instructions to py file, you can run the program repeatedly.

(1) Preparation of documents

(2) Open terminal

(3) Enter the directory where the program is located: cd directory

(4) Executor: python3 file name

2.2.3 common linux commands

(1) pwd: view the path of the current working directory

(2) cd: change the working directory (enter a directory)

practice:

(1) Creates a python file in the specified directory

– Directory: / home/tarena/month01

– file name: exercise01 py

(2) Write in the file: print("Hello, world!")

(3) Run python program

2.2.4 execution process

The computer can only recognize the machine code (1010), not the source code (python).

(1) The process of transforming source code into machine code is divided into two categories: Compilation and interpretation.

(2) Compilation: before the program runs, the source code is transformed into machine code through the compiler, such as C language.

– advantages: fast running speed

– disadvantages: the development efficiency is low and can not cross platform.

(3) Explanation: when the program is running, the interpreter translates the program line by line and then executes it, such as Javascript.

– advantages: high development efficiency and cross platform;

– disadvantages: slow running speed.

(4) python is an interpretive language, but in order to improve the running speed, a compilation method is used. After compilation, the pyc file is obtained and the bytecode is stored (specific to the representation of python, not machine code).

Source code - compile -- > bytecode - interpret -- > machine code

|-- once --|

2.2.5 interpreter type

(1) CPython (C language development)

(2) Jython (java Development)

(3) IronPython (.net development)

3. Basic data operation

3.1 basic knowledge

3.1.1 pycharm common shortcut keys

"""
    create a file:exercise03
    Exchange rate converter
"""

# 1. Access to data - USD
usd = input("Please enter USD:")
# 2. Logic processing - USD * 6.99
cny = int(usd) * 6.99
# 3. Display results - xx USD is xx RMB
print(usd + "The dollar is" + str(cny) + "RMB")

(1) Move to the beginning of the line: home key

(2) Move to end of line: end keyboard

(3) Comment Code: ctrl +/

(4) Copy line: ctrl +d

(5) Delete line: shift + delete

(6) Select column: shift + alt + left mouse button

(7) Move line: ctrl + shift + up and down arrows

(8) Code format: ctrl+alt+l

3.1.2 notes

What people see is usually the description of the code.

(1) Single line comment: starts with # sign.

(2) Multiline comment: start with three quotation marks and end with three quotation marks.

3.1.3 function

Represents a function. The function definer is the person who provides the function, and the function caller is the person who uses the function.

(1) Print (data): displays the contents in parentheses in the console

print("Hello")
print("world")

(2) Variable = input("content to be displayed") function: assign the content entered by the user to the variable

name = input("Please enter your name:")
age = input("Please enter age:")
print(name + "What is your age:" + age + ".")

Exercise 1: display the ancient poem "climb high" in the terminal

            Climb high
         Author: Du Fu
 When the wind is strong, the high apes howl and mourn, and the white birds fly back.
Boundless falling trees rustle down and endless Yangtze River rolls in.
Thousands of miles of sorrowful autumn often visit, and have been on stage alone for more than a hundred years.
Hardship and bitterness hate the numerous frost temples, and the new turbid wine cup is down and out.

Exercise 2: judging the composition of an English sentence: I kiss you

Please enter the subject of I kiss you: I

Please enter the predicate of I kiss you: Kiss

Please enter the object of I kiss you: you

The subject you enter is: I, the predicate is: kiss, and the object is: you

3.2 data

3.2.1 variables

(1) Definition: the identifier associated with an object.

(2) Naming:

It is composed of letters, numbers and underscores. It cannot start with a number.

Keyword (blue) cannot be used, otherwise syntax error SyntaxError will occur.

(3) Suggested naming: lowercase letters, multiple words separated by underline.

class_name = "xxx"

(4) Assignment: create a variable or change the data associated with a variable.

(5) Syntax:

Variable name = Data

Variable name 1 = variable name 2 = Data

Variable name 1, variable name 2 = data 1, data 2

# Create variable
name01 = "Sun WuKong"
name02 = "Tang Monk"
name03 = name01 + name02
# Modify variable
name01 = "name of a fictitious monkey with supernatural powers"
print(name03)
# Variable assignment variable
name04 = name01
print(name04)

3.2.2 delete statement

(1) Syntax:

name01 = "name of a fictitious monkey with supernatural powers"
name02 = name01
del name01, name02

(2) Function:

Used to delete variables and disassociate objects at the same time.

Release the object if possible.

(3) Reference count for automated memory management:

The number of bound (referenced) variables per object record is destroyed when it is 0.

3.2.3 core type

In python, a variable has no type, but the associated object has a type.

3.2.3.1 shaping int

(1) Represents an integer, including positive, negative and 0.

For example: - 5, 100, 0

(2) Face value:

Decimal system: each person counts with ten states. Every decimal is one. The writing method is 0 ~ 9.

num01 = 10

Binary: each person counts with two states. Every two enters one. The writing method is 0b followed by 0 or 1.

num02 = 0b10

Octal: each person counts with eight states. Every eight enters one. The writing method starts with 0o, followed by 0 ~ 7.

num03 = 0o10

Hexadecimal: each person counts with sixteen states. Every hexadecimal enters one. The writing method is 0x, followed by 09,AF,a~f

num04 = 0x10

3.2.3.2 float ing point

(1) Represents decimal, including positive and negative numbers, 0.0.

(2) Face value:

Decimal: 1.0 2.5

Scientific counting method:

e/E (sign) index

1.23e-2 (equivalent to 0.0123)

1.23456e5 (equivalent to 123456.0)

# decimal
num01 = 1.23

# Scientific counting method
num02 = 1e-5
print(0.00001)

3.2.3.3 string str

(1) used to record text information (text information).

(2) literal value: double quotation marks

3.2.3.4 Boolean bool

(1) used to indicate true and false types

(2) there are only two values:

True means true (the condition is satisfied or established), and the essence is 1

False means false (the condition is not satisfied or tenable), and the essence is 0

result = input("Please enter your occupation:") == "teacher"
print(result) # Enter the teacher and the result is True; Enter other, and the result is False

3.3 calculation

3.3.1 type conversion

(1) Convert to integer: int (data)

(2) Convert to floating point: float (data)

(3) Convert to string: str (data)

(4) Convert to Boolean: bool (data)

The result is False: bool(0) bool(0.0) bool(None)

(5) Mixed type automatic upgrade:

1 + 2.14 returns 3.14

1 + 3.0 returns 4.0

# str -> int
data01 = int("3")
# int -> str
data02 = str(5)

# str -> float
data03 = float("1.2")
# float -> str
data04 = str(1.2)

# int -> float
data05 = float(250)
# float -> int
data06 = int(1.9)
print(data06)  # 1 rounding down (truncation and deletion)

# Note: when converting strings to other types,
# Must be a string representation of the target type
# print(int("10.5")) # report errors
# print(float("abc"))# report errors

Exercise: enter the unit price of goods, the quantity purchased and the payment amount in the terminal. Calculate how much money you should get back.

effect:

Please enter the unit price of goods: 5

Please enter the purchase quantity: 3

Please enter the payment amount: 20

Should be retrieved: 5.0

3.3.2 operators

3.3.2.1 arithmetic operators

+Addition

-Subtraction

*Multiplication

/Division: the result is a floating point number

//Integer division: the result of division removes the decimal part

%Seeking remainder

**Power operation

Priority from high to low:

()

**

* / % //

+ -

Exercise 1: enter a confirmed number of epidemic cases in the terminal, then enter a cured number, and print the cured proportion

Format: cure rate is xx%

effect:

Please enter the number of confirmed patients: 500

Please enter the number of cured persons: 495

The cure rate was 99.0%

Exercise 2: the ancient scale is 16 Liang per kilogram. Get two in the terminal and calculate a few catties and a few Liang.

effect:

Please enter the total number: 100

The result is: 6 Jin and 4 liang

Exercise 3:

Speed and displacement formula of uniform speed change linear motion:

Displacement = initial velocity × Time + acceleration * square of time / 2

Known (input in the terminal): displacement, time and initial velocity

Calculation: acceleration

effect:

Please enter the distance: 100

Please enter the initial speed: 6

Please enter time: 10

Acceleration: 0.8

3.3.2.2 enhanced operator

y += x is equivalent to y = y + x

y -= x is equivalent to y = y - x

y *= x is equivalent to y = y * x

y /= x is equivalent to y = y / x

y //= x is equivalent to y = y // x

Y% = x is equivalent to y = y% X

y **= x is equivalent to y = y ** x

data01 = 10
# data01 + 5
# print(data01) # 10
data01 += 5   # data01 = data01 + 5
print(data01)  # 15

Exercise: enter a four digit integer in the terminal and calculate the sum of each addition.

For example: enter 1234 and print 1 + 2 + 3 + 4 results

effect:

Please enter a four digit integer: 1234

The result is: 10

3.3.2.3 comparison operator

< less than

< = less than or equal to

>Greater than

>=Greater than or equal to

==Equals

!= Not equal to

Returns a Boolean value

Mathematical representation of comparison operation: 0 < = x < = 100

Exercise 1: write the meaning of the proposition expressed in the following code

print(666 == "666")
print(27 % 10 == 2)
print(float(input("Please enter your height:")) > 170) 

Exercise 2: write code according to the proposition

You entered a positive number

The month is entered

The number entered is not even

3.3.2.4 logical operators

(1) and

Express and express the relationship between the two, one false and the other false.

Example:

True and True # True

True and False # False

False and True # False

False and False # False

int(input("Please enter deposit:")) >= 100000 and input("Please enter real estate:") == "have"

(2) Or or

It means the relationship between or, which is true

Example:

True or True # True

True or False # True

False or True # True

False or False # False

int(input("Please enter deposit:")) > 100000 and input("Please enter real estate:") == "have"

(3) Non not

Indicates negation

For example:

not True # returns False

not False # returns True

Exercise: write the code according to the proposition

Older than 25 and less than 170

The position is an executive or the annual salary is more than 500000

(4) Short circuit operation

Once the result is determined, the following statements will no longer be executed.

3.3.2.5 identity operator

(1) Syntax:

x is y

x is not y

(2) Function:

Is is used to judge whether two objects are the same object. If yes, it returns True; otherwise, it returns False.

The role of is not is opposite to that of is

3.3.2.6 priority

High to low:

Arithmetic operator

Comparison operator

Enhanced operator

Identity operator

Logical operator

4. Statement

4.1 line

(1) Physical lines: lines of code written by programmers.

(2) Logical line: the instructions that the python interpreter needs to execute.

(3) Recommendations:

A logical line is on a physical line.

Use one semicolon in the logical line if necessary; separate.

(4) Line feed:
If the logical line is too long, you can use implicit or explicit line wrapping.

– implicit line feed: all contents in parentheses can be automatically wrapped () [] {}

- explicit line feed: line feed through the line break character \ (backslash) must be placed at the end of a line to tell the interpreter that the next line is also a statement of the line.

# 4 physical lines 4 logical lines
a = 1
b = 2
c = a + b
print(c)

# 1 physical line and 4 logical lines (not recommended)
a = 1;b = 2;c = a + b;print(c)

# 4 physical lines and 1 logical line
# --Line feed
d = 1+\
    2+\
    3+4\
    +5+6

# --Bracket
e = (1+2+
     3+4
     +5+
     6)

4.2 selection statement

4.2.1 if else statement

(1) Function: let the program execute statements selectively according to conditions.

(2) Grammar

  if Condition 1:
     Statement block 1
  elif Condition 2:
     Statement block 2
  else:
     Statement block 3

(3) Description:

elif clauses can have 0 or more.

The else clause can have 0 or 1, and can only be placed at the end of the if statement.

(4) Demo:

sex = input("Please enter gender:")
if number == "male":
    print("Hello, sir")
elif number == "female":
    print("Hello, madam")
else:
    print("Gender unknown")

Exercise 1:

Enter an integer in the terminal

Print integer, negative, zero

Exercise 2:

Enter the number of course stages in the terminal and display the course name

effect:

Input: output:

1. Python language core programming

2 Python advanced software technology

3 Web full stack

4 project practice

5. Data analysis and artificial intelligence

Exercise 3:

Enter the height of 4 students in the terminal and print the highest value

Algorithm:

170 160 180 165

Suppose the first is the maximum

Compare the hypothetical with the second one and find that the larger one replaces the hypothetical one

Compare the hypothetical with the third one and find that the larger one replaces the hypothetical one

Compare the hypothetical with the fourth one and find that the larger one replaces the hypothetical one

Finally, the assumption is the largest

effect:

Please enter the height of the first student: 170

Please enter the height of the second student: 160

Please enter the height of the third student: 180

Please enter the height of the fourth student: 165

Highest classmate: 180

Exercise 4:

Print the IQ level according to the psychological age and actual age.

IQ = psychological age MA divided by actual age CA multiplied by 100

Genius: above 140 (inclusive)

Extraordinary: 120-139 (inclusive)

Intelligence: 110-119 (inclusive)

Normal: 90-109 (inclusive)

Dull: 80-89 (inclusive)

Low energy: below 80

Exercise 5:

Enter the month in the terminal and print the corresponding days

1 3 5 7 8 10 12 31 days

2 there are 29 days

4 6 9 11 30 days

If the month is exceeded, it indicates that the month is wrong

effect:

Please enter month: 10

31 days

4.3 circular statements

4.3.1 while statement

(1) Function:

You can make a piece of code meet the conditions and execute it repeatedly.

(2) Syntax:

while condition:
    # Statements that meet the conditions for execution 

(3) Description:

If the condition is satisfied, execute the loop body, and then decide whether to execute the loop body again according to the condition;

count = 0  # 1. Start 
while count < 3:  # 2. End
    print(count)  # 0  1  2
    count += 1  # 3. Interval

Exercise 1:

Repeat the following code and enter y to continue (exit without entering y)

    print("Positive number") elif number < 0:
    print("negative") else:
    print("Fatal Frame") ```

Exercise 2:

Display 0 1 2 3 in the terminal

Display 2 3 4 5 6 in the terminal

Display 1 3 5 7 in the terminal

Display 8 7 6 5 4 in the terminal

Display - 1 - 2 - 3 - 4 - 5 in the terminal

Exercise 3:

Enter 5 scores in the terminal in a cycle,

Finally, print the average score (total score divided by the number of people)

effect:

Please enter grade: 98

Please enter grade: 83

Please enter grade: 90

Please enter grade: 99

Please enter grade: 78

Average score: 89.6

Exercise 4:

The thickness of a piece of paper is 0.01 mm

Please calculate how many times you fold in half over Mount Everest (8844.43 meters)

Idea:

Data: thickness and times

Algorithm: thickness * = 2 times + = 1

Exercise 5:

The program generates a random number between 1 and 100.

Let the player repeat the guess until it is right.

Tips: big, small, Congratulations, guess right, how many times in total.

effect:

Please enter the number to guess: 50

Big

Please enter the number to guess: 25

Small

Please enter the number to guess: 35

Big

Please enter the number to guess: 30

Small

Please enter the number to guess: 32

Congratulations, you guessed right. I guessed five times in total

4.3.2 for statement

(1) Function:

Data elements used to traverse iteratable objects.

Iteratable objects refer to objects that can obtain data elements in turn, such as container type.

(2) Syntax:

for Variable list in Iteratable object:
    # Statement block 1

(3) Description:

else clause can be omitted.

When a loop is terminated with break in the loop body, the else clause is not executed.

message = "I'm the monkey king"
for item in message:
    print(item)  

practice:

Input any integer in the terminal to calculate the cumulative sum

"1234" - > "1" - > accumulate 1

effect:

Please enter an integer: 12345

The cumulative sum is 15

4.3.2.1 range function

(1) Function:

Used to create an iterative object that generates a series of integers (also known as integer sequence generator).

(2) Syntax:

Range (start point, end point, interval)

(3) Description:

The iteratable object returned by the function can be used to extract the elements in it with for

The number returned does not contain an end point

The default starting point is 0

The interval defaults to 1

# Writing 1: range (start, end, interval)
# Note: the end value is not included
for item in range(1, 3, 1):
    print(item)

# Writing 2: range (start, end)
# Note: the interval is 1 by default
for item in range(1, 3):
    print(item)

# Writing 3: range (end)
# Note: the default value is 0 at the beginning
for item in range(3):
    print(item)

practice:

Accumulate 0 1 2 3 in the terminal

Add 2 3 4 5 6 to the terminal

Accumulate 1 3 5 7 in the terminal

Accumulate 8 7 6 5 4 in the terminal

Accumulate - 1 - 2 - 3 - 4 - 5 in the terminal

4.4 jump statement

4.4.1 break statement

(1) Jump out of the loop body and the following code will no longer be executed.

(2) You can make the else part of the while statement not execute.

4.4.2 continue statement

(1) Skip this time and continue the next cycle.

# Demand: accumulate the number between 1-100 that can be divided by 3
# Thought: skip if the conditions are not met, otherwise accumulate
sum_value = 0
for item in range(1, 101):
    if item % 3 != 0:
        continue
    sum_value += item
print(sum_value)

Exercise: add up between 10 – 60, and the number of bits is not the sum of 3 / 5 / 8 integers.

5. Container type

5.1 general operation

5.1.1 mathematical operators

(1) +: used to splice two containers

(2) + =: splice the original container with the right container, and rebind the variable

(3) *: repeatedly generate container elements

(4) * =: use the original container to generate duplicate elements and rebind variables

(5) < <= > >= == !=: Compare the elements in the two containers in turn. If they are different, the comparison result will be returned.

# 1. Splice 2 container elements
name = "name of a fictitious monkey with supernatural powers"
name += "Bajie"
print(name)  # Wukong Bajie

# 2. Duplicate container element
name = "Tang Monk"
name *= 2
print(name)  # Tang Seng Tang Seng

# 3. Comparison operation: compare the elements in two containers in turn. If they are different, the comparison result will be returned.
print("name of a fictitious monkey with supernatural powers" > "Tang Monk")

practice:

Obtain an integer in the terminal as the side length and print the rectangle.

please enter an integer:5
$$$$$
$   $
$   $
$   $
$$$$$

please enter an integer:8
$$$$$$$$
$      $
$      $
$      $
$      $
$      $
$      $
$$$$$$$$

5.1.2 member operators

(1) Syntax:

Data in sequence

Data not in sequence

(2) Function:

Returns the bool type if a value is found in the specified sequence.

# 4. Member operation
# True
print("name of a fictitious monkey with supernatural powers" in "I'm the monkey king")
print("Saint sun" in "I'm the monkey king")

# False
print("Qi Sheng" in "I'm the monkey king")
print("Shengda" in "I'm the monkey king") 

5.1.3 index

(1) Purpose: locate a single container element.

(2) Syntax: container [integer]

(3) Description:

The forward index starts from 0, the second index is 1, and the last one is len(s)-1.

The reverse index starts with - 1, - 1 represents the last one, - 2 represents the penultimate one, and so on. The first one is - len(s).

message = "I am the saint of Qi Tian in Huaguo Mountain"
print(message[2])  # flower
print(message[-2])  # large
print(len(message)) # 9
# Note: the index cannot be out of bounds IndexError
# print(message[99])
# print(message[-99]) 

5.1.4 slice

(1) Function:

Locate multiple container elements.

(2) Syntax:

Step: index: container end

(3) Description:

The end index does not contain the location element

The step size is the offset that the slice moves each time it gets the current element

Start, end, and step size can be omitted

message = "I am the saint of Qi Tian in Huaguo Mountain"
print(message[2:5:1])  # Huaguo Mountain
print(message[1: 5])   # It's Huaguo Mountain
print(message[2:-4])   # Huaguo Mountain
print(message[:-4])    # I'm Huaguo Mountain
print(message[:])      # I am the saint of Qi Tian in Huaguo Mountain
print(message[-3:])    # Heavenly sage 
print(message[:2])     # I am
print(message[-2:])    # Great sage
print(message[-2: 3:-1])  # Datianqi mountain
print(message[1: 1])  # empty
print(message[2: 5:-1])  # empty
# Special: flip
print(message[::-1])  # Shengdatianqi mountain fruit flower is me

practice:

String: content = "I'm Jin Hai, the warden of Beijing prison."

Print first character, print last character, print middle character

The first three characters and the last three characters of the printed word

Proposition: Jinhai in string content

Proposition: capital prison is not in the string content

Print "governor of Beijing prison" through slices

Print "long prison teacher Beijing" through slices

Print "my division prison sea" through slice

Print characters in reverse order

5.1.5 built in function

(1) len(x) returns the length of the sequence

(2) max(x) returns the maximum element of the sequence

(3) min(x) returns the minimum element of the sequence

(4) sum(x) returns the sum of all elements in the sequence (elements must be numeric)

5.2 string str

5.2.1 definitions

An immutable Sequence container composed of a series of characters, which stores the coded value of the characters.

5.2.2 coding

5.2.2.1 basic knowledge

(1) byte: the smallest storage unit of the computer, equal to 8 bit s

(2) Characters: single numbers, words and symbols.

(3) Character set (code table): store the corresponding relationship between characters and binary sequences.

(4) Encoding: the process of converting characters into corresponding binary sequences.

(5) Decoding: the process of converting binary sequences into corresponding characters.

5.2.2.2 coding method

(1) ASCII code: including English, numbers and other characters, each character is 1 byte.

(2) GBK Code: compatible with ASCII code, including 21003 Chinese characters; English 1 byte, Chinese 2 bytes.

(3) Unicode character set: international unified coding, 2 bytes for each character in the old character set and 4 bytes in the new character set.

(4) UTF-8 encoding: storage and transmission mode of Unicode, 1 byte in English and 3 bytes in Chinese.

5.2.3 literal value

5.2.3.1 difference between single quotation mark and double quotation mark

(1) Double quotation marks inside single quotation marks are not terminators

(2) A single quotation mark within a double quotation mark is not a terminator

5.2.3.2 function of three quotation marks

(1) Line breaks are automatically converted to line breaks \ n

(2) Three quotation marks can contain single quotation marks and double quotation marks

(3) As document string

5.2.3.3 escape characters

(1) Definition: change the original meaning of characters.

(2) Syntax:

 \'   \"   \n   \\   \t 

(3) Original string: cancel escape.

       a = r"C:\newfile\test.py"

5.2.3.4 string formatting

(1) Definition: generates a string in a certain format.

(2) Syntax: String% (variable)

"My name is%s,Age is%s" % (name)

(3) Type code:

%s string% d integer% f floating point number

print("%.2d:%.2d"%(2,3)) # 02:03
print("The cure rate is%d%%" % 5) # The cure rate was 5%
print("Price%.2f element" % (5 / 3)) # Price: 1.67 yuan

Exercise: extract variables according to the following text, format and print information with strings

67802 people were diagnosed and 63326 were cured in Hubei, with a cure rate of 0.99

70 seconds is 01 minutes and 10 seconds

5.3 list

5.3.1 definition

A variable sequence container consisting of a series of variables.

5.3.2 basic operation

(1) Create list:

List name = []  
List name = list(Iteratable object)

(2) Add element:

List name.append(element) 
list.insert(Index, element)

(3) Locate element:

List name[Indexes] = element
 variable = List name[Indexes]
variable = List name[section] # A new list is created when the slice is read 
List name[section] = data # When the slice is assigned, the data will be stored in the left side in turn

(4) Traversal:

Forward:

​    for Variable name in List name:
​       Variable names are elements

Reverse:

​    for Index name in range(len(List name)-1,-1,-1):
​       List name[Index name]Is the element

(5) Delete element:

List name.remove(element) 
del List name[Index or slice]

demonstration:

# 1. Create
# Writing method 1: list name = [data 1, data 2]
# Name list
list_names = ["name of a fictitious monkey with supernatural powers", "Tang Sanzang", "Bajie", "Monk Sha"]
# Age list
list_ages = [26, 23, 25, 16]

# Writing method 2: list name = list (iteratable object)
list_name = list("Sun WuKong")
print(list_name)  # ['sun', 'Wu', 'empty']

# 2. Add
# --Append: list name Append (data)
list_names.append("Little white dragon")
# --Insert: list name Insert (index, data)
list_names.insert(2, "nezha")
print(list_names) # ['Wukong', 'tangsanzang', 'Nezha', 'Bajie', 'Shaseng', 'little white dragon']

# 3. Positioning
# --Index: container name [integer]
# --Read
element = list_names[-1]
print(element) # Little white dragon
# --Modification
list_names[-1] = "Erlang God"
print(list_names) # ['Wukong', 'tangsanzang', 'Nezha', 'Bajie', 'Shaseng', 'Erlang God']
# --Slice: container name [integer: integer: integer]
# --Create a new list (copy) by slice reading
names = list_names[:3]
print(names) # ['Wukong', 'Tang Sanzang', 'Nezha']
# --Through slice modification, traverse the data on the right and store it on the left in turn
list_names[:3] = ["empty", "Tang Tang", "Pig pig"]
# list_names[:3] = 100 # Because 100 cannot be used for
list_names[:3] = "Sun WuKong"
print(list_names) # ['sun', 'Wu', 'Kong', 'Bajie', 'Shaseng', 'Erlang God']

# 4. Traversal: operate each element of the container
# --Method 1: for element in container
# Applicability: read from beginning to end
for name in list_names:
    print(name)

# --Mode 2: for index in range:
# Applicability: not read from beginning to end
# len(list_names) - 1 is the maximum index (total - 1)
# -1 index can go to 0
# -1 reverse order
# Function: reverse order
for i in range(len(list_names) - 1, -1, -1):
    print(list_names[i])

# Function: modify
for i in range(len(list_names)):
    # If the text length is 3, change it to None
    if len(list_names[i]) == 3:
        list_names[i] = None
print(list_names) # ['sun', 'Wu', 'empty', 'Eight Precepts',' monk Sha ', None]

# 5. Delete
# --Method 1: delete the list name according to the element Remove (element)
list_names.remove("Bajie")

# --Method 2: delete del container name [index or slice] according to location
del list_names[0]
del list_names[-2:]
print(list_names) # ['Wu', 'empty']

Exercise 1:

Create a region list, a new list and an existing list. The cumulative list stores three lines of information (Taiwan, Shanxi and Zhejiang) respectively

Exercise 2:

Add the information of the fourth row of data (Guangxi) to the above four lists

Insert line 5 (Hong Kong) in position 1

Exercise 3:

Print epidemic information in Taiwan (xx new people in xx area, xx existing people)

Modify the last two elements of the region list to ["ZJ", "GX"]

Print new list elements (one per line)

Print existing list elements in reverse order (one per line)

Exercise 4:

Delete "Zhejiang" from the list of regions

Delete the first element from the new list

Delete the first 2 elements from the existing list

Delete all elements in the cumulative list

Exercise 5:

Eight planets: "Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus" and "Neptune"

– create a list to store 4 planets: "Mercury", "Venus", "Mars" and "Jupiter"

– insert "Earth" and add "Saturn", "Uranus" and "Neptune"

– print the nearest and farthest planet from the sun (first and last element)

– print the planets between the sun and the earth (the first two planets)

– delete the fourth planet

– print all planets in reverse order (one per line)

5.3.3 deep and light copies

Shallow copy: in the copy process, only one layer of variables are copied, and the objects bound by deep variables are not copied.

Deep copy: copies the entire variable.

Exercise 1: draw the following code memory diagram

list01 = ["Beijing", "Shanghai"]
list02 = list01
list01[0] = "Guangdong"
list03 = list01[:]
list03[-1] = "Shenzhen"
print(list01)#?

Exercise 2: draw the following memory map

list01 = ["Beijing", "Shanghai", "Shenzhen"]
list02 = list01 
list01.insert(0,"Tianjin")
del list01[1]
print(list02)# ?

Exercise 3: draw the following memory map

import copy
list01 = ["Beijing",["Shanghai","Shenzhen"]]
list02 = list01
list03 = list01[:]
list04 = copy.deepcopy(list01)
list04[0] = "Beijing 04"
list04[1][1] = "Shenzhen 04"
print(list01) # ?

list03[0] = "Beijing 03" 
list03[1][1] = "Shenzhen 03"
print(list01) # ?
list02[0] = "Beijing 02" 
list02[1][1] = "Shenzhen 02"
print(list01) # ?

5.3.4 list and string conversion

(1) Convert list to string:

result = "connector" Join (list)

list01 = ["a", "b", "c"]
result = "-".join(list01)
print(result)

practice:

In the terminal, input the string circularly. If the input is empty, it will stop

Print all contents (one string) after stopping entry

effect:

Please enter content: Hong Kong

Please enter content: Shanghai

Please enter content: Xinjiang

Please enter:

Hong Kong_ Shanghai_ Xinjiang

(2) Convert string to list:

List = "a-b-c-d" split("separator")

# Use one string to store multiple information
list_result = "Tang Monk,Sun WuKong,Bajie".split(",")
print(list_result)

Exercise: turn the following English sentences according to the words

To have a government that is of people by people for people

After conversion: people for people by people of is that government a have To

5.3.5 list derivation

(1) Definition:

Use simple methods to convert iteratable objects to lists.

(2) Syntax:

List name = [expression for variable in Iteratable object]
List name = [expression for variable in Iteratable object if condition]

(3) Description:

If the Boolean value of the if truth expression is False, the data generated by the iteratable object will be discarded.

list01 = [9, 15, 65, 6, 78, 89]
# Requirement: select the number that can be divided by 3 in list01 and store it in list02
# list02 = []
# for item in list01:
#     if item % 3 == 0:
#         list02.append(item)
list02 = [item for item in list01 if item % 3 == 0]
print(list02)

# Requirement: all digits in list01 are stored in list03
# list03 = []
# for item in list01:
#     list03.append(item % 10)
list03 = [item % 10 for item in list01]
print(list03)

practice:

Generate a number between 10 and 30 that can be divided by 3 or 5

Results: [10, 12, 15, 18, 20, 21, 24, 25, 27]

Generate the square of the number between 5 – 20

Results: [25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324,
361]

5.4 tuple

5.4.1 definition

(1) An immutable Sequence container consisting of a series of variables.

(2) Immutable means that once created, elements cannot be added / deleted / modified.

5.4.2 basic operation

(1) Create empty tuple:

Tuple name = ()
Tuple name = tuple()

(2) Create a non empty tuple:

Tuple name = (20,)
Tuple name = (1, 2, 3)
Tuple name = 100,200,300
 Tuple name = tuple(Iteratable object)

(3) Get element:

variable = Tuple name[Indexes]
variable = Tuple name[section] # Assigned to the variable is the new list created by the slice 

(4) Traversal tuple:

Forward:

   for Variable name in List name:
​       Variable names are elements

Reverse:

​    for Index name in range(len(List name)-1,-1,-1):
​       Tuple name[Index name]Is the element

demonstration:

# 1. Create
# --Tuple name = (element 1, element 2, element 3)
tuple01 = (10, 20, 30)
# --Tuple name = tuple (iteratable object)
list01 = ["a", "b", "c"]
tuple02 = tuple(list01)

# 2. Positioning
# --Read (index / slice)
print(tuple01[0]) # 10
print(tuple01[:2]) # (10, 20)

# 3. Traversal
for item in tuple01:
    print(item)

for i in range(len(tuple01) - 1, -1, -1):
    print(tuple01[i])

# 4. Special
# Note 1: parentheses can be omitted
tuple03 = 10, 20, 30
# Note 2: if there is only one element in the tuple, there must be a comma
tuple04 = (10,)
# Unpacking: multiple variables = container
# a,b,c = tuple03
# a,b,c = ["A","B","C"]
a,b,c = "Sun WuKong"
*a,b = "Sun WuKong"
print(a) # ['sun', 'Wu']
print(b) # empty

Exercise 1: draw the following code memory diagram

name = "zhang wuji"
names = ["Zhao Min", "Zhou Zhiruo"]
tuple01 = ("Zhang Cuishan", name, names)
name = "Wuji brother"
tuple01[2][0] = "Mina "
print(tuple01) # ?

Exercise 2:

According to the month day, it is the day of the year

Formula: total days of the previous months + days of the current month

For example: May 10

Calculation: 31 29 31 30 + 10

5.4.3 function

(1) Tuples and lists can store a series of variables. Since the list will reserve memory space, elements can be added.

(2) Tuples allocate memory on demand, so if the number of variables is fixed, tuples are recommended because they take up less space.

(3) Application:

The essence of variable exchange is to create tuples: x, y = (y, x)

The essence of format string is to create Yuanzu: "Name:% s, age:% d"% ("tarena", 15)

5.5 dictionary dict

5.5.1 definitions

(1) A variable hash container consisting of a series of key value pairs.

(2) Hash: hash the key to determine the storage location in memory. There is no order for each data storage.

(3) The key must be unique and immutable (string / number / tuple), and the value is unlimited.

5.5.2 basic operation

(1) Create Dictionary:

Dictionary name = {Key 1: value 1, key 2: value 2}
Dictionary name = dict (Iteratable object) 

(2) Add / modify elements:

Syntax:

Dictionary name[key] = data

explain:

Key does not exist, create record.

Key exists, modify the value.

(3) Get element:

variable = Dictionary name[key]  # Error without key

(4) Traverse Dictionary:

for Key name in Dictionary name:
​       Dictionary name[Key name]

for Key name,Value name in Dictionary name.items():
​       sentence

(5) Delete element:

del Dictionary name[key]

demonstration:

# 1. Create
# --{key 1: value 1, key 2: value 2}
dict_wk = {"name": "name of a fictitious monkey with supernatural powers", "age": 25, "sex": "female"}
dict_bj = {"name": "Bajie", "age": 26, "sex": "male"}
dict_xbl = {"name": "Little white dragon", "age": 23, "sex": "female"}
# -- dict(  [(  ,  ),( , )]  )
# Format requirements for converting a list into a dictionary: list elements must be able to "split into two"
list01 = ["Bajie", ("ts", "Tang Monk"), [1001, "Qi Tian Da Sheng"]]
dict01 = dict(list01)

# 2. Add dictionary name [key] = value
dict_wk["money"] = 100000
print(dict_wk) # {'name': 'Wukong', 'age': 25, 'sex': 'female', 'money': 100000}

# Dictionary cannot use index slice
# 3. Positioning: dictionary name [key]
# --Read
print(dict_wk["name"])
# Note: if there is no key, an error will be reported
# Solution: judge by in before reading data
if "money" in dict_wk:
    print(dict_wk["money"])

# --Modify (same syntax as adding data)
# If there is a key, it is modified, and if there is no key, it is added
dict_wk["name"] = "empty"
print(dict_wk) # {'name': 'empty', 'age': 25, 'sex': 'female', 'money': 100000}

# 4. Delete del dictionary name [key]
del dict_wk["sex"]
print(dict_wk) # {'name': 'empty', 'age': 25, 'money': 100000}

# 5. Traversal
# Method 1: for key in dictionary name
for key in dict_wk:
    print(key)

# Method 2: for value in dictionary name values()
for value in dict_wk.values():
    print(value)

# Method 3: for key, value in dictionary name items()
for key,value in dict_wk.items():
    print(key)
    print(value)

# Data type name (...)
#[('name ',' Li Jiahao '), ('age', 25), ('sex ',' female ')]
print(list(dict_wk.items())) # [('name ',' empty '), ('age', 25), ('money', 100000)]

Exercise 1:

Create a dictionary to store the first four columns (region, new, existing and accumulated) information of Taiwan, Shaanxi, Zhejiang and Guangxi

Exercise 2:

Print the current number of people in Taiwan in the terminal

Print the new and existing number of people in Shaanxi in the terminal

The number of new and existing people in Zhejiang increased by 1 respectively

The current and cumulative number of people in Guangxi decreased by 2

Exercise 3:

Delete existing information in Taiwan

Delete new and existing information

Zhejiang cumulative and delete existing information

Delete the reserved key for the number of new people in Guangxi (modify the value through the key)

Exercise 4:

Print all keys in the terminal (one per line)

Print all values in the terminal (one per line)

Print all keys and values in the terminal (one per line)

Find the key name corresponding to 256 in Guangxi dictionary

5.5.3 dictionary derivation

(1) Definition:

Use a simple method to convert iteratable objects into dictionaries.

(2) Syntax:

{key:value for variable in Iteratable object}

{key:value for variable in Iteratable object if condition}

Exercise 1:

Merge the two lists into one dictionary

Name list ["Zhang Wuji", "Zhao Min", "Zhou Zhiruo"]

Room list [101102103]

{101: 'Zhang Wuji', 102: 'Zhao Min', 103: 'Zhou Zhiruo'}

Exercise 2:

Reverse exercise 1 dictionary key values

{'Zhang Wuji': 101, 'Zhao Min': 102, 'Zhou Zhiruo': 103}

5.6 container comprehensive training

Exercise 1: print the following graphics in the terminal

$
$$
$$$
$$$$ 

Exercise 2: 2D list

list01 = [
      [1, 2, 3, 4, 5],
  	  [6, 7, 8, 9, 10],
 	  [11, 12, 13, 14, 15],
] 
  1. Print the first line from left to right

effect:
​ 1

​ 2

​ 3

​ 4

​ 5

  1. Print the second line from right to left

Effect:

​ 10

​ 9

​ 8

​ 7

​ 6

  1. Print the third row one by one from top to bottom

effect:

​ 3

​ 8

​ 13

  1. Print the fourth column row from bottom to top one by one

effect:

​ 14

​ 9

​ 4

  1. Print the 2D list as a table

effect:

​ 1 2 3 4 5

​ 6 7 8 9 10

​ 11 12 13 14 15

Exercise 3: multiple hobbies of multiple people

dict_hobbies = {
  "Yu Qian": ["smoking", "drink", "Hot head"],
  "Guo Degang": ["say", "learn", "Tease", "sing"],
}
  1. Calculate the number of all Guo Degang's hobbies

effect:
4

  1. Print all Yu Qian's hobbies (one per line)

effect:
smoking
drink
Hot head

  1. Print all (one per line)

effect:
Yu Qian
Guo Degang

  1. Print all hobbies (one per line)

effect:
smoking

drink

Hot head

say

learn

Tease

sing

Exercise 4:

dict_travel_info = {
	"Beijing": {
    	"scenic spot": ["the Great Wall", "the Imperial Palace"],
    	"delicious food": ["Roasted Duck", "Bean juice coke ring", "Noodles with Soy Bean Paste"]
  },
  	"Sichuan": {
    	"scenic spot": ["jiuzhaigou", "Mount Emei"],
    	"delicious food": ["Hot Pot", "Rabbit head"]
  }
}
  1. Print the first scenic spot in Beijing

effect:
the Great Wall

  1. Print the second food in Sichuan

effect:
Rabbit head

  1. All cities (one per line)

effect:
Beijing
Sichuan

  1. All delicacies in Beijing (one for each line)

effect:
Roasted Duck
Bean juice coke ring
Noodles with Soy Bean Paste

  1. Print all delicacies in all cities (one per line)

effect:
Roasted Duck
Bean juice coke ring
Noodles with Soy Bean Paste
Hot Pot
Rabbit head

Exercise 5:

Sort the list of numbers in ascending order (small -- > large)

Exercise 6:

# Epidemic information
list_epidemic = [
    {
        "region": "Taiwan", "new": 16,
        "now": 2339, "total": 16931,
    },
    {
        "region": "Shaanxi", "new": 182,
        "now": 859, "total": 1573,
    },
    {
        "region": "Zhejiang", "new": 2,
        "now": 505, "total": 2008,
    },
]
  1. Print the first epidemic information,
    Format: xx new people in xx region, xx existing people, xx accumulated people

  2. Print all epidemic information,

    Format: xx new people in xx region, xx existing people, xx accumulated people

  3. Print all epidemic information with a cumulative population of less than 10000,

    Format: xx new people in xx region, xx existing people, xx accumulated people

  4. Find the names of regions with more than 10 new people (store the results in a new list)

  5. Find information about the region with the largest number of people available (the result is a dictionary)

  6. Arrange the epidemic information in descending order (Large - > small) according to the existing number of people

6 function

6.1 pycharm shortcut key

Ctrl + P parameter information (calling parameters in method)

Ctrl + Q quick view document

6.2 definitions

(1) Used to encapsulate a specific function and represent a function or behavior.

(2) A function is a statement block that can be executed repeatedly and can be called repeatedly.

6.3 function

Improve code reusability and Maintainability (clearer code hierarchy).

6.4 basic grammar

6.4.1 defining functions

(1) Syntax:

def Function name(Formal parameters):
	Function body

(2) Description:

def keyword: the full name is define, which means "define".

Function name: the description of the statements in the function body. The rules are the same as the variable name.

Formal parameter: the information required by the function definer from the caller.

Function body: the statement that completes the function.

(3) In the first line of the function, it is recommended to use the document string to describe the functions and parameters of the function.

# Formal parameters: non specific data of the surface
def attack(count): 
    """
        attack
    :param count:frequency 
    """
    for __ in range(count):
        print("Straight fist")
        print("hook ")
        print("Hook fist")

6.4.2 calling function

(1) Syntax:

Function name(Actual parameters) 

(2) Description: pass content according to formal parameters.

# Actual parameters: real and specific data
attack(5)
attack(2)

Exercise 1: define a function and print a one-dimensional list in the terminal

list01 = [5, 546, 6, 56, 76, ]
for item in list01:
    print(item)
    
list02 = [7,6,879,9,909,]
for item in list02:
    print(item)

Exercise 2: create a function to print a rectangle in the terminal

number = int(input("please enter an integer:")) # 5
for row in range(number):
  if row == 0 or row == number - 1:
     print("*" * number)
 else:
     print("*%s*" % (" " * (number - 2)))

6.4.3 return value

(1) Definition:

The result that the function definer tells the caller.

(2) Syntax:

return data

(3) Description:

If there is no statement after return, it is equivalent to returning None.

The function body has no return, which is equivalent to returning None.

def func01():
    print("func01 Yes")
    return 100

# 1. The caller can receive or not receive the return value
func01()
res = func01()
print(res)

# 2. In Python language,
# The function has no return or there is no data after return,
# Is equivalent to return None
def func02():
    print("func02 Yes")
    return

res = func02()
print(res) # None

# 3.return can exit the function
def func03():
    print("func03 Yes")
    return
    print("func03 Again")

func03()

# 4. return to exit multi-level loop nesting
def func04():
    while True:
        while True:
            while True:
                # break can only exit one layer of loop
                print("Circulatory body")
                return

func04()

Exercise 1: create a function to calculate the healing ratio

confirmed = int(input("Please enter the number of confirmed patients:"))
cure = int(input("Please enter the number of people cured:"))
cure_rate = cure / confirmed * 100
print("The cure rate is" + str(cure_rate) + "%")

Exercise 2: define the function and calculate the kilos and Liang according to the total two numbers

Tip: use containers to wrap multiple data that need to be returned

total_liang = int(input("Please enter two:"))
jin = total_liang // 16
liang = total_liang % 16
print(str(jin) + "Jin zero" + str(liang) + "two")

Exercise 3: create a function to calculate the course name according to the course stage

number = input("Please enter the number of course stages:")
if number == "1":
    print("Python Language core programming")
elif number == "2":
    print("Python Advanced software technology")
elif number == "3":
    print("Web Full stack")
elif number == "4":
    print("Project practice")
elif number == "5":
    print("Data analysis, artificial intelligence")

Exercise 4: create a function to calculate the IQ level

ma = int(input("Please enter your heart age:"))
ca = int(input("Please enter your actual age:"))
iq = ma / ca * 100
if iq>= 140:
	print("genius")
elif iq >= 120:
    print("Supernormal")
elif iq >= 110:
    print("Intelligence")
elif iq >= 90:
    print("normal")
elif iq >= 80:
    print("slow")
else:
    print("low-energy")

Exercise 5: create a function to calculate life stages based on age

age = int(input("Please enter age:"))
if age <= 6:
  print("childhood")
elif age <= 17: # The age of this bank is greater than 6, and the program can be executed
  print("juvenile")
elif age <= 40:
  print("youth")
elif age <= 65:
  print("middle age")
else:
  print("old age")

Exercise 6: define the function and calculate the day of the year according to the month, year and day

If February is a leap year, then 29-28

month = int(input("Please enter month:"))
day = int(input("Please enter the day:"))
days_of_month = (31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
total_days = sum(days_of_month[:month - 1])
total_days += day 
print(f"{month}month{day}Day is day{total_days}day.")
year = int(input("Please enter the year:"))
if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
	day = 29
else:
	day = 28

6.5 differences between variable and immutable types in parameter transmission

(1) Immutable type parameters include:

Numeric type (integer, floating point number)

Boolean bool

None null

String str

tuple

(2) Variable type parameters include:

List list

Dictionary dict

(3) Description of parameter transmission:

When data of immutable type is passed as a parameter, the value of the original data will not be changed inside the function.

When variable type data is passed as parameters, the original data can be changed inside the function.

Exercise 1: draw the following code memory diagram and write the print results.

def func01(p1, p2):
  p1 = "Sun WuKong"
  p2["Bajie"] += 50

a = "name of a fictitious monkey with supernatural powers"
b = {"Bajie": 100}
func01(a, b)
print(a) # ?
print(b) # ?

Exercise 2: draw the following code memory diagram and write the print results.

def func01(p1, p2): 
	p1 = [100, 200] 
	p2[:] = [300, 400]

a = [10, 20]
b = [30, 40]
func01(a, b)
print(a) # ?
print(b) # ?

Exercise 3: create a descending sort function according to the following code.

list01 = [5, 15, 25, 35, 1, 2]

for r in range(len(list01) - 1):
  for c in range(r + 1, len(list01)):
     if list01[r] < list01[c]:
     list01[r], list01[c] = list01[c], list01[r]
    
print(list01)

6.6 function parameters

6.6.1 argument transfer method

6.6.1.1 position transmission reference

Definition: the positions of the arguments and formal parameters correspond in turn.

def fun01(p1, p2, p3):
    print(p1)
    print(p2)
    print(p3)
 
# Position argument: corresponds to the formal parameter according to the order
fun01(1, 2, 3)

6.6.1.2 sequence transmission parameters

Definition: the argument corresponds to the position of the formal parameter after disassembling the sequence with *.

def func01(p1, p2, p3):
    print(p1, p2, p3)

# Sequence argument: disassembled, corresponding to formal parameters in order
list01 = [1, 2, 3]
name = "Sun WuKong"
tuple01 = (4, 5, 6)
# func01(list01)
func01(*list01)  # Remove 1, 2 and 3
func01(*name)  # Dismantle the monkey king
func01(*tuple01)  # Remove 4, 5 and 6

6.6.1.3 keyword transfer parameters

Definition: the argument corresponds to the name of the formal parameter.

def fun01(p1, p2, p3):
    print(p1)
    print(p2)
    print(p3)
    
# Keyword argument: corresponds to the parameter by name
fun01(p1=1, p2=2, p3=3)
fun01(p2=2, p1=1, p3=3)

6.6.1.4 dictionary keyword transfer parameters

(1) Definition: the argument uses * * to disassemble the dictionary and correspond to the name of the formal parameter.

(2) Function: with the default parameters of formal parameters, the caller can transfer parameters at will.

def func01(p1, p2, p3):
    print(p1, p2, p3)
    
# Dictionary argument: disassembled, corresponding to the formal parameter by name
dict01 = {"p2":"B","p1":"A","p3":"C"}
func01(**dict01)

6.6.2 parameter definition method

6.6.2.1 default parameters

(1) Syntax:

def Function name(Parameter name 1=Default argument 1, Parameter name 2=Default argument 2):
​       Function body

(2) Description:

Default parameters must exist from right to left. If a parameter has default parameters, all parameters on the right must have default parameters.

def func01(p1 =0, p2="", p3=100):
    print(p1)
    print(p2)
    print(p3) 
    
func01(p2=2)
func01(p2=2,p3=3)
# Support the simultaneous use of location arguments to participate in keyword arguments
func01(1,p3=3)
# Note 1: position argument first, then keyword argument
# func01(p1 =1,2,3) # error

practice:

Define a function to calculate the total number of seconds according to hours, minutes and seconds

Call: provide hour, minute and second

Call: provide minutes and seconds

Call: provide hours and seconds

Call: provide minutes

6.6.2.2 position parameters

Syntax:

def Function name(Parameter name 1, Parameter name 2, ...):
​	Function body

6.6.2.3 naming keyword parameters

(1) Syntax:

def Function name(*args, Named keyword parameter):
	Function body

def Function name(*, Named keyword parameter):
	Function body

(2) Function:

Force arguments to pass parameters using keywords

# Named keyword parameters:
# Position parameter after asterisk tuple parameter
# The restriction argument must be a keyword argument
def func01(*args, p1, p2):
    print(args)
    print(p1)
    print(p2)


func01(p1=1, p2=2)
func01(1, 2, 3, p1=1, p2=2)


def func02(p1, *, p2=0):
    print(p1)
    print(p2)


# Generally, the named keyword parameters after the asterisk are auxiliary parameters and optional
func02(1)
func02(1, p2=2)

6.6.2. 4-star tuple parameters

(1) Syntax:

def Function name(*Tuple parameter name):
	Function body

(2) Function:

Multiple positional arguments can be combined into a tuple

(3) Description:

It is generally named 'args'

There can be at most one parameter in the formal parameter list

# The number of location arguments can be unlimited
def func01(*args):
    print(args)

func01()  # Empty tuple
func01(1, 2, 34)  # (1, 2, 34)
# Keyword arguments are not supported
# func01(args = 1,a=1)

Exercise: defining a function for numerical multiplication

6.6.2.5 double star dictionary parameters

(1) Syntax:

def Function name(**Dictionary parameter name):
	Function body

(2) Function:

You can combine multiple keyword arguments into one dictionary

(3) Description:

It is generally named 'kwargs'

There can be at most one parameter in the formal parameter list

# Unlimited number of keyword arguments
def func01(**kwargs):
    print(kwargs) # {'a': 1, 'b': 2}

func01(a=1,b=2)
# func01(1,2,3) # report errors

6.6.2.6 order of parameters from left to right

Position parameter -- > asterisk tuple parameter -- > named keyword parameter -- > double asterisk dictionary parameter

Exercise: say the result of program execution

def func01(list_target):
  print(list_target)# ?

def func02(*args):
  print(args)# ?

def func03(*args,**kwargs):
  print(args)# ?
  print(kwargs)# ?

def func04(p1,p2,*,p4,**kwargs):
  print(p1)# ?
  print(p2)# ?
  print(p4)# ?
  print(kwargs)# ?

func01([1,2,3])
func02(*[1,2,3])
func03(1,2,3,a=4,b=5,c=6) 
func04(10,20,p4 = 30,p5 = 40)

6.7 scope LEGB

Definitions

The range in which the variable works.

6.7.2 classification

(1) Local scope: inside the function.

(2) Enclosing external nested scope: function nesting.

(3) Global scope: inside the module (. py file).

(4) Builtin built-in module scope: builtins Py file.

6.7.3 search rules for variable names

(1) From inside to outside: L - > e - > G - > b

(2) When accessing variables, first look for local variables, then variables inside the function that wrap outside the function, then global variables, and finally built-in variables.

6.7.4 local variables

(1) Variables defined inside the function (formal parameters are also local variables)

(2) Can only be used inside a function

(3) It is created only when the function is called, and is automatically destroyed after the function is completed

6.7.5 global variables

(1) Variables defined outside the function and inside the module.

(2) Access within the scope of the whole module (py file) (but it cannot be assigned directly within the function).

6.7.6 global statement

(1) Function:

Modify global variables inside functions.

Define global variables (Global declarations) inside functions.

(2) Syntax:

global variable 1, variable 2

(3) Explain

Directly assigning a value to a global variable within a function is regarded as creating a new local variable.

Local variables cannot be declared first, and then global variables can be declared as global variables.

6.7.7 nonlocal statement

(1) Function:

Modifying variables within an outer nested function in an inner function

(2) Grammar

nonlocal variable name 1, variable name 2

(3) Explain

Used in nested inner functions

# 2. Global scope: internal file
#   Global variables: variables created in all scopes
#   Scope of application: the whole document
data02 = 20
data03 = [30]

def func01():
    # 1. Local scope: internal function
    # Local variable: a variable created within a local scope
    # Scope of application: a function
    data01 = 10
    print(data01)
    print(data02)

def func02():
    # print(data01) # Local variables of other functions cannot be accessed
    print(data02) # Read global variables

def func03():
    # Global variables cannot be modified in a local scope
    # data02 = 200
    # Must be declared with a global statement
    global data02
    data02 = 200

def func04():
    # Global variables were not modified
    # When modifying the list pointed to by the global variable
    # Therefore, there is no need to declare through the global statement
    data03[0] = 300

func01()
func02()
func03()
func04()
print(data02) # 200
print(data03) # [300]

Exercise: draw the following code memory diagram

data01 = 10

def func01(p):
    global data01
    data01 += 1
    p += 1

data02 = 10
func01(data02)
func01(data02)
print(data01)  # ?
print(data02)  # ?

Topics: Python Back-end