python study notes

python3.8.5 download address:
64 Bit: https://www.python.org/ftp/python/3.8.5/python-3.8.5-amd64.exe
32 Bit: https://www.python.org/ftp/python/3.8.5/python-3.8.5.exe
installation:
Double-click to install after downloading, pay attention to distinguish between 32-bit and 64-bit systems
Note: When installing "Add Python 3.8.5 to PATH" in front of the tick, other suggestions are installed by default

2020 The latest zero-based Python
Link: https://pan.baidu.com/s/1hqsKyV1ztnkrw9U2xKOhdg 
Extraction code: 20w2
Shangxuetang Season One
Link: https://pan.baidu.com/s/1i_d9oolHdAqz6WaK_XuVFQ 
Extraction code: 20w2
Shangxuetang Season 2
Link: https://cloud.189.cn/t/NbEjArraqa2a(Access code:h44k)
Shangxuetang Season 3
Link: https://pan.baidu.com/s/18nYAc68Fx325NCufkSwFjA 
Extraction code: 20w2
Shangxuetang Season 4
Link: https://pan.baidu.com/s/1UJyMi7mxtmG59TyLXvEgSg 
Extraction code: 20w2

01 variable:
Variables are abstract concepts that can store calculation results or represent values in computer languages.
Variable naming convention:
1. Composed of letters, numbers, and underscores
2. Cannot start with a number
3. Cannot use Python keywords
4. Distinguish the case of English letters
5. Try to make variable names easy to remember
The difference between functions and reserved words:
1. There are 35 reserved words: and, as, assert, async, await, break, class, continue, def, del, elif, else, except, finally, for, from, False, global, if, import, in, is, lambda, nonlocal, not, None, or, pass, raise, return, try, True, while, with, yield2.See built-in functions
www.runoob.com/python/python-built-in-functions.html
Add after the built-in function(), Example print()02Value:
Numerical types in python are divided into integer types(Integer)(int)And decimal type (floating point type)(float)
Numerical data supports arithmetic operations, comparison operations and bit operations
1 . Arithmetic operation: add+,Less-, Multiply*,except/, Divisible//Qiu Yu%, Power**2. Comparison operation: greater than>, Less than<,greater or equal to>=, Less than等于、等于==,not equal to!=3. Bit operation:

03 String:
String(str)Is a continuous sequence of characters. Usually enclosed in single, double or triple quotation marks'''、"""。其中单引号和双引号中的String必须在一行上,三引号String可以分布在连续的多行上。
Common escape characters:\n newline character;\t tab
slice[]
Individual elements of the string can be extracted.
[] Extract characters in a string by index.
usage:[(starting point):(End position):(Stride)]
example:
s ="Life is short, I use python"
Corresponding position value:
From left to right:
Life is short, I use python
0123456789101112
From right to left:
 Life is short, I use python
-13-12-11-10-9-8-7-6-5-4-3-2-1
# Extract the 3rd to 8th strings
  Command print(s[3:9])        #Contains the start position, does not include the end position, the default step size is 1, which can be omitted
The running result is short, I use py
# Extract the 3rd to the last string
  Command print(s[3:])        #Contains the starting position, can be omitted to the end, the default step size is 1, which can be omitted
The running result is short, I use python
# Extract the string from the beginning to the 8th
  Command print(s[:9])        #It can be omitted from the beginning, not including the end position, the default step size is 1, which can be omitted
It turns out that life is short, I use py
# Extract all characters
  Command print(s[:])        #It can be omitted from the beginning, and can be omitted from the end. The default step size is 1, which can be omitted
It turns out that life is short, I use python
# If the step size is negative, it means extracting from right to left. At this time, the starting position is on the right and the ending position is on the left.
# Extract from right to left
  Command print(s[-3:-7:-1])        #Stride-1. Extract from right to left
Operation result htyp
Or command print(s[10:6:-1])        #Stride-1. Extract from right to left
Operation result htyp
# The step size is 2, count two to extract one, namely interval extraction
# Extract all singular characters
  Command print(s[::2])   #Explain yourself
The result of running is hard, use yhn
# Extract all double-digit characters
  Command print(s[1::2])  #Explain yourself
The result of the operation is short, I pto
# Output the string backwards (backwards like a stream)
  Command print(s[::-1])  #Explain yourself
The result of the operation is that nohtyp uses me, short and miserable

04 Format usage of python formatted output
format usage
Relatively basic formatted output adopts&#39;%&#39;Method, format()The function is more powerful. This function treats the string as a template, formats it with the passed parameters, and uses braces&#39;{}&#39;As a special character instead&#39;%’
There are two ways to use: b.format(a)And format(a,b)。
1、 Basic usage
(1) Without serial number, namely &quot;{}”
(2) With digital numbers, the order can be changed, that is, &quot;{1}”、“{2}”
(3) With keywords, namely &quot;{a}”、“{tom}”
example:
>>> print('{} {}'.format('hello','world'))  #Without fields
hello world
>>> print('{0} {1}'.format('hello','world'))  #Number with numbers
hello world
>>> print('{0} {1} {0}'.format('hello','world'))  #mess up the order
hello world hello
>>> print('{1} {1} {0}'.format('hello','world'))
world world hello
>>> print('{a} {tom} {a}'.format(tom='hello',a='world'))  #With keywords
world hello world
2、 Advanced usage
Talk about it later
3、 Multiple formatting
Talk about it later
Match parameters by position
example:
>>>'{0}, {1}, {2}'. format('a','b','c')'a, b, c'>>>'{2}, {1}, {0}'.format(*'abc')  #Can be shuffled
' c, b, a'>>>'{0}{1}{0}'.format('abra','cad')  #Repeatable
' abracadabra'
Match parameters by name
example:
>>>' Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')'Coordinates: 37.24N, -115.81W'>>> coord ={'latitude':'37.24N','longitude':'-115.81W'}>>>'Coordinates: {latitude}, {longitude}'.format(**coord)'Coordinates: 37.24N, -115.81W'
There are many other usages below, which are not required

05 Data type conversion:
int(a)       #Convert variable a to integer type
float(b)   #Convert variable b to decimal type
str(c)       #Convert variable c into string type
type(d)    #View the data type of variable d
Exercise:
a =12
b =34
c =56
d =420104200405064321
# Use the above variables, write appropriate code, and output the following results
Results: 46
Code:
Results: 1234#Numerical
Code:
Result: 3456#Text type
Code:
Result: My birthday is May 16, 2004
Code:
# The code remains unchanged, change the ID number to 420104200412134321
Thinking:
" A">"a"
What is the result of the operation? why?
Not running on the computer, try to write the following results:
"1">"0" operation result:
"1">" A"operation result:
"1">" a"operation result:
" ">" "( Two spaces are greater than one space)operation result:
"1">" " operation result:
" A">" "operation result:
" a">" "operation result:

Quiz:
1. Please write the following mathematical expressions in Python programs and calculate the results:

x =5
y =7
a =9
b =11
m =2
pai =3.14  #π

  

Two, programming questions

1 . Input a positive integer, judge whether it is odd or even, and output &quot;odd&quot; or &quot;even&quot;
2 . Input any data, judge the data type, and output the corresponding Chinese, such as integer, decimal, string, Boolean
while True :try:
  x =eval(input(":"))ifstr(type(x))=="<class 'int'>":print("Integer")ifstr(type(x))=="<class 'float'>":print("Decimal")ifstr(type(x))=="<class 'bool'>":print("Boolean")
 except:print("String")3. Enter an ID number and output the date of birth, format: May 5, 2005
4 . Input a paragraph of text, output backward
5 . Enter a value and output backwards
6 . Enter a paragraph of text, if there is the word &quot;Hanwu&quot;, automatically correct it to &quot;Wuhan&quot; and output the text

Three, thinking questions

1 . Enter a positive integer and output all its factors. For example: input 8, the factors are 1, 2, 4, 82. There is a number whose sum of all factors is exactly equal to itself. For example, the factors of 6 are 1, 2, 3, and 1+2+3=6. Please find all numbers within 1000 that meet this condition.
for x inrange(1,1000):
 # x =int(input(":"))
 s =0for i inrange(1,x):if x % i ==0:
   # print(i)
   s = s + i
 if x == s :print(x)06 program flow chart:

Start and end box: indicates the beginning or end of the program logic
Judgment box: indicates a judgment condition
Processing box: indicates the processing process
Input and output box: indicates data input or result output
Comment box: the left is a dotted line, the right is a half box, I don’t want to draw anymore
Flow line: indicates the program execution path
Connection point: indicates the connection method of multiple flowcharts

In the past, I was poor, so I could only do it on paper. Now it is recommended to learn how to write a simple program first, then draw a flowchart, and finally run the program manually.
First understand, practice this after you finish learning if, for, and while.

example:

Extension: exception handling
try:……
except :
 ……

1 . Single branch structure: if
How to use:
If <condition>:<Statement block 1><Statement block 2>
Among them: add after if: ,<Statement block>缩进四格是语法的一部分。Statement block可一条或多条,但不能没有,如果没有需要执行的语句,可加pass
< Statement block>Is a sequence of one or more statements executed after the if condition is met, indented<Statement block>Containment relationship with if.
file:///C:/Users/ADMINI~1/AppData/Local/Temp/msohtmlclip1/01/clip_image002.png<condition>必须产生一个逻辑结果True或False。当condition为True时执行<Statement block>, Otherwise skip<Statement block>。
flow chart:

example:
# Determine the parity of the entered number
s =int(input(&quot;Please enter an integer:&quot;))if  s%2==0:print(s,&quot;Is an even number&quot;)if  s%2!=0:print(s,&quot;It&#39;s an odd number&quot;)<condition>可以是多个condition,多个condition间采用and或or进行组合。
and: when both conditions are met,<condition>的结果是True,只满足一个condition或两个condition都不满足时,<condition>The result is False
or: Indicates that as long as one of the two conditions is met,<condition>的结果是True,只有两个condition都不满足时,<condition>The result is False
example:
# Enter 6 first, then 8, 9 to see the results. If there is no result, please think for yourself.
x =int(input(&quot;Please enter an integer:&quot;))if  x%2==0  and  x %3==0:print(x,&quot;Either divisible by 2 and divisible by 3&quot;)if  x%2==0  or  x %3==0:print(x,&quot;Either divisible by 2 or divisible by 3&quot;)

Thinking: What results will be output if three or more and and or are mixed together? Add parentheses and mix them up?
Example: previous question<condition>What is the difference between the following two types?
x %2==0 or  x %3==0  and  x%4==0  or  x %5==0(x %2==0 or  x %3==0)and(x%4==0  or  x %5==0)
Program exercise:
#1 . Enter a positive integer greater than 2 to determine if it is a prime number
#2 . Enter a positive integer greater than 2 to determine if it is a composite number
#3 . Enter two integers and compare the sizes
#4 . Enter the ID number to determine whether you are an adult (18 years old)
#5 . Enter a paragraph of text to determine whether there are keywords in it, such as Wuhan
#6 . Enter a paragraph of text to determine whether there are keywords in it, such as Wuhan and Shanghai
#7 . Enter a paragraph of text to determine whether there are keywords in it, such as Wuhan or Shanghai
#8 . Enter Alipay balance to determine whether it is a rich person
#9 . Enter the height to determine whether the height is normal
#10 . Enter the appearance to judge whether it is handsome or beautiful
#11 . Enter Alipay balance, height, appearance, all three conditions are met, and output &quot;earth person&quot;
#12 . Enter Alipay balance, height, appearance, all three conditions are not met, and output &quot;Saturnian&quot;
#13 . Enter Alipay balance, height, appearance, Alipay balance meets the conditions, the other two do not meet the conditions, output &quot;Martian&quot;
#14 . Enter Alipay balance, height, appearance, height meets the requirements, and output &quot;Jupiter&quot;
#15 . Enter Alipay balance, high, appearance, appearance meets the conditions, output &quot;alien&quot;
#16 . Enter Alipay balance, Xiang Gao, appearance, only one of the three conditions is met, and output &quot;strange person&quot;

Practice crazy, consolidate and improve

0922 Exercise:
1. Calculation questions (written examination questions, computer operation is prohibited)
1+2=
“1”+“2”=int(1)+float(2)=
True + False ="True"+"False"=int(1)+int(2)=str(int(1))+str(int(2))="China"+&quot;Wuhan&quot;=1*2=
“1”*2=
Two, slice questions
a ="People have sorrows and joys, and the moon is cloudy and clear. This is hard to come by. Nung, moon and new moon."
b =420104200506074321
Output: People have joys and sorrows, and the moon is cloudy and clear.
Statement:
Output: People are sorrowful, there is sunshine and lack of this ancient whole, but people have been together for a long time.
Statement:
Output:. Juanchan has a total of thousands of miles. It’s hard for the ancients, lack of roundness, sunny and cloudy, and moon, reunion, joy and sorrow
Statement:
Output:. Chanli, long wish. Difficult things, the round cloudy moon acacia has
Statement:
Output: 20050607
Statement:
Output: Xiao Ming is 15 years old
Statement:
Three, if branch
1 . Enter grades to determine whether you pass
2 . Enter the length of three sides to determine whether it can form a triangle
3 . Enter three company lengths. If they can form a triangle, determine whether they form an obtuse, right or acute triangle
4 。

0923 Exercise:
1 . Enter a positive integer, if it is odd, then output: the cube of this number is**, If it is an even number, output: the square of this number is**2. Enter four positive integers. If the sum of the first two numbers is equal to the sum of the last two numbers, the output is: What a coincidence. Otherwise output: we are not familiar
3 . Input two positive integers, assign the larger number to a, and the smaller number to b, and finally output: a=**,b=**4. Enter three positive integers, assign the largest number to a, and assign the smallest number to c,Assign the number in the middle to b, and finally output: a=**,b=**,c=**5. Enter the month and output the corresponding number of days, regardless of leap years. Such as: input 2, output: there are 28 days in February
6 . Enter the year to determine whether the year is a normal year or a leap year. Such as: input 2020, output: 2020 is a leap year
7 . Enter two positive integers and output the absolute value of the difference between the two numbers.
8 . Enter a positive integer, judge whether the number is a multiple of 3, if yes, output YES, if not, output NO
9 . Enter a three-digit number to determine if the number is a daffodil number, if yes, output YES, if not, output NO. Explanation: The number of daffodils is the sum of the cubes of each number of a number equal to this number. Such as: 153. . 1**3+5**3+3**3=15310. Convert the percentile system to ABCDE, if you enter 90 or more, output A; enter 80-89, output B; input 70-79, output C; input 60-69, output D; input below 60, output E
11 . Judge whether the input value is 5 digits, if yes, output YES, if not, output NO
12 . Input a number and judge whether its hundreds digit is 3, if yes, output YES, if not, output NO
13 . Enter three numbers and output from small to large
14 . Input three subjects: Chinese, Mathematics, and English. All three are passed and the output is &quot;excellent&quot;; one fails and the output is &quot;good&quot;; if there are two failed, the output is &quot;pass&quot;; three fail, the output is &quot;repeat&quot; &quot;
15 。

0924 Exercise:
1 . Enter four integers a,b,c,d, output according to the way from big to small
2 . Enter an integer less than 1000 to determine whether it is a one-digit, two-digit or three-digit number
3 . Enter student name**, Enter the test score, if it is 100 points, output: congratulations**, Full marks passed! If it is greater than or equal to 80 points and less than 100 points, output:**,you are excellent. If it is greater than or equal to 60 points and less than 80 points, output:**Good grades. If it is greater than or equal to 50 and less than 60, output:**Just a little bit. If it is less than 50, output:**Are you asleep?
4 . Enter integers a and b, if a**2+b**2 is greater than 100, then output a**2+b**2, otherwise output a+b
5 . Enter a value to determine whether it is an integer or a decimal
6 . Quadratic equation in one variable a*x**2+b*x+c=0. Enter a,b,c Three numbers, judge whether the equation has two real roots, one real root or no real root
7 . Standard weight: Men&#39;s weight=height-100, women&#39;s weight=height-110。
xb =str(input("Please enter gender (male or female):"))
sg =int(input("Please enter height (cm):"))
tz =int(input("Please enter weight (kg):"))
。。。
Determine whether the weight is overweight, standard, or thin
8 . Commodity name: 1. Hamburg; 2. French fries; 3. Chicken nuggets; 4. Drumsticks; 5. Chicken Rice Flower
Please enter the number of the product item you selected, and output the corresponding product
Such as: input 1234, output: hamburger, french fries, chicken nuggets, chicken legs
Such as: input 135, output: hamburger, chicken nuggets, chicken rice crackers
Such as: input 11, output: hamburger, hamburger
This question is a bit difficult
9 . Input an integer, the number of digits is not limited, if it is an odd number, output the middle one digit, if it is an even number, output the middle two digits
Such as: input 123, output 2
Such as: input 4564, output 56
This question is also a bit difficult
10 . Your dog is 5 years old. How old is a 5-year-old dog?
It’s actually very simple. Each year for the first two years of a dog is equivalent to 10 of a human’s.Five years old, and then four years old for every additional year. So a 5-year-old dog is equal to the age of a human being should be 10..5+10.5+4+4+4=33 years old
Write a program to get the age of the dog entered by the user, and then display the age equivalent to that of a human through the program.
11 . Enter your test scores for a total of seven subjects, of which the full score of Chinese, Mathematics, and English is 150 points, the full score of politics, history, and geography is 100 points, and the full score of sports is 30 points. The passing score is based on the full score of 60 for each subject%Calculation.
If you pass all your homework, reward a BMW;
If you fail any two, a horse is awarded;
If you fail any of four, reward a donkey;
If there are more than 4 failings, a goose will be rewarded
# reference:

yw =eval(input("Language:"))
sx =eval(input("mathematics:"))
wy =eval(input("foreign language:"))
zz =eval(input("political:"))
ls =eval(input("history:"))
dl =eval(input("geography:"))
ty =eval(input("physical education:"))

s = yw//90+sx//90+wy//90+zz//60+ls//60+dl//60+ty//18if  s ==7:print("All pass, reward a BMW")if7> s >=5:print("Reward a horse")if5> s >=3:print("Reward a donkey")if3> s >0print("A pig")else:print("Reward a dumb goose")

Recommended Posts

python study notes
Python study notes (3)
Python notes
Ubuntu Linux study notes
SkyWalking study notes (CentOS environment)
Python entry tutorial notes (3) array
Python introductory notes [basic grammar (on)]
Container study notes CentOS7 install Docker
Python CookBook
Python FAQ
Python3 module
python (you-get)
Python string
Python basics
Python basics 2
Python exec
Python3 tuple
CentOS + Python3.6+
Python advanced (1)
Python decorator
Python multithreading
Python toolchain
Python3 list
Python multitasking-coroutine
Python overview
python introduction
Python analytic
Python basics
07. Python3 functions
Python basics 3
Python multitasking-threads
Python functions
python sys.stdout
python operator
Python entry-3
Centos 7.5 python3.6
Python string
python queue Queue
Python basics 4
Python basics 5