To you who want to learn Python well [zero basic teaching] Python from zero to one! Links to detailed learning resources are attached

Posted by mark110384 on Sun, 24 Oct 2021 14:23:53 +0200

A detailed link to Python learning notes is attached at the end of the article.

The goal of this article

Through the study of this article, you can develop programming thinking and master all the basic syntax of Python.

Moreover, after reading it, you can say that you can learn Python!

Part I getting started with Python

Section 1 Introduction to Python language

Python is the most popular programming language in the world. It has occupied the first place in the list of various languages for many years. (not all lists, of course)

It is widely used in various fields, including data analysis, server development, operation and maintenance development, artificial intelligence development, and even children's programming begin to learn Python.

This does not make countless program ape friends sigh: life is short, I use Python!

As for the development history of Python, I won't explain it in detail here. Let's put a picture of the founder!


Founder of Java language

Founder of C + + language

Founder of JavaScript language

Founder of Go language

After reading the founders of various programming languages, I don't need to say more about what language to choose (manual dog head)

Section 2 Python installation and configuration

1.2.1 Python version introduction

Python currently has two versions coexisting, python 2 and python 3. Python officially announced that Python 2 will no longer be maintained from January 1, 2020, so if you start learning Python now, you must learn Python 3.

However, because Python 2 has a long life cycle and has just stopped maintenance, it is still used in many companies. Some interviewers like to ask you during the interview: what is the difference between Python 2 and python 3? Don't worry, their differences are not that big. As long as you master Python 3, you will soon be able to master some of their nuances.

Now you just need to know that there are two versions, and there are some differences between them. In the later process, we will talk specifically.

1.2.2 installing Python environment

  1. Visit Python's official website, https://www.python.org , the Python official website will recognize your operating system through the browser, so you can download the corresponding version as long as you operate as shown in the figure below.

  1. Double click the downloaded installation file and install step by step according to the prompts (except that the address can be changed, other defaults can be used).

  2. Test for correct installation.

    1. Open the console, enter "cmd" in the search bar and press enter. (open the terminal application that comes with the Mac system)

    2. Enter "python" in the console and press enter. If the following interface appears, the installation is successful.

1.2.3 Hello World

Python code is famous for its simplicity and efficiency. For example, the following four lines of code can realize the normal distribution histogram containing 10000 data.

# The following passage will generally report errors when a novice runs it directly. Let's not run it first. It's only for explanation
import matplotlib.pyplot as plt
import numpy as np

plt.hist(np.random.randn(10000), bins=40)
plt.show()

The effects are as follows:


You see, just four lines of code can draw such a picture. Isn't it nice!

Next, let's write a Hello world. The first line of Python code is definitely simpler than you think. In the console opened in the previous step, enter the following code:

print("Hello world")

Then press enter. If "Hello world" is displayed on your monitor, congratulations. Your first Python program has run successfully. Isn't it very simple! Try to replace Hello world with what you want to say and run it again.

Print here is a built-in function. We can ignore the concept of function first. As long as we know that using print function can output the specified content on the screen. The print function can also be written in this way:

print("Hello", "world")
print("Hello", "my", "friends")

Commas separate multiple words. We don't enter spaces, but Python will automatically separate each word with spaces when outputting. In fact, we can enter 100, 1000 and countless words. Please pay attention to the use of commas here, which we will often use later.

Section III interactive programming

In the above steps, we input a line of code and press enter to submit the code to Python's built-in interpreter. After the interpreter runs the code, the running results are printed on the console. This form of one input corresponding to one output is called interactive programming.

Try removing the right quotation mark in the Hello world case to see what will be output.

You will see a sentence like this:

SyntaxError: EOL while scanning string literal

The interpreter tries to run your code, but the missing quotation mark causes an error in the execution process. The interpreter prints the error to you. At this time, the screen displays error (exception or error). An experienced programmer can judge what is wrong after seeing the error information.

And if you follow my blog, you can also become an old driver!

qis interactive programming is not unique to python, but Python's interactive interface is the most powerful. It also has a wealth of plug-ins and provides a series of very powerful functions. I will introduce these in detail later if I have the opportunity.

Section 4 Python development tools

In fact, there are many python development tools, but only in terms of use functions and installation experience, I think pychar is the most suitable for you.

Pychar is actually very easy to install. Click the download address on the official website https://www.jetbrains.com/pycharm/download/ Just click download (the blue download is the paid version. Generally, we can use the community version).

In addition to the installation address, the others can be installed by default.

After installation, open it and click create new project (it should be blank on your left).


In this way, we can run the program on pycharm.

The second part is the core grammar

Section I variables

2.1.1 definition of variables

Variables are variable quantities. For some data that may change frequently, we need to use a symbol in order to use it in calculation, just like "x" in the unary equation we learned in primary school. For example, we input in the console:

x = "world"

In this way, we define a new variable with the value of "world". We slightly modify the example of Hello world. This time, we use the variable x.

print("Hello", x)

The output result after running is the same as our previous example. Here, x is equivalent to "world". For variables, we can understand it as a container with a handle. We can put anything we want in it, and this handle is the variable name. Holding this handle, we can use the things in the container more conveniently.

Let's write a few more examples to consolidate:

name = "Smith"
print("Mr", name)
print("Mrs", name)

In this example, there is a couple of Smiths. Their names should be Mr Smith and Mrs Smith respectively. Note that we only write Smith once in the code, which can be used twice. Another advantage is that if a couple change their names, we just need to modify the value of name. Other codes don't need to be modified at all. Is it very convenient?

Let's think about it. Suppose in the above example, we have to print their names 100 times. If we don't define variables, what should we do when we modify them? Understand the role of variables?

2.1.2 variable name rules

In Python, variable names follow the following rules:

  1. Variable names consist of letters, numbers, and underscores, that is, a-z, A-Z, 0-9, and_

  2. Variable names cannot start with numbers

  3. Variable names are case sensitive. For example, A and A are two different variables.

We don't have to recite this rule. Let's give a few examples and we'll soon understand it.

These are legal variable names:

a = "hello"

MyJob = "analyst"

player1 = "Yao Ming"

_private_name = "ss"

player1_score = 41

_ = "something"

The following are illegal variable names:

1abc   # Cannot start with a number

123

abc-   # Note that this is a bar symbol, not an underscore

In addition, on this basis, we also agreed on some naming conventions for variable names. For example:

  1. Common variables are usually in lowercase letters

  2. It's best not to name variables with words and numbers, especially meaningless random numbers.

  3. There are two styles of variable names: words are separated by underscores; Use capital letters for the first letter of each word.

Note that the above specification is just a conventional rule of programmers, not a mandatory requirement of Python language. However, following these specifications, the variable names written are more readable and more conducive to team cooperation.

2.1.3 keywords

The following words are Python keywords. Each programming language has its own keywords, which constitute the basic syntax rules of the programming language. Don't worry about their functions, just avoid using these names when naming.

False      await      else       import     pass

None       break      except     in         raise

True       class      finally    is         return

and        continue   for        lambda     try

as         def        from       nonlocal   while

assert     del        global     not        with

async      elif       if         or         yield

In fact, if you accidentally define a variable with the same keyword, the code will report an error at run time. For example, the following:

True = 0

The above line of code will output the following information, indicating that the keyword cannot be assigned.

SyntaxError: can't assign to keyword

2.1.4 variable assignment

Variables can be reused and modified. Python variables do not need to be declared first, so the declaration and assignment of variables are completed in the same line of code, such as the name variable declared above

name = "Smith"

In this line, we first define a variable named "name" and then assign it "Smith". In this way, we have a variable "name" whose value is "Smith". Variables must be declared before they can be used. If you use a variable xxx that has never been defined, the Python interpreter will throw you such an error:

NameError: name 'xxx' is not defined

After the variable definition is completed, we can read and modify its value at will, such as:

# Define the name variable and assign the value "Smith"
name = "Smith"
print("Mr", name)

# Modify the value of the variable to "Jones"
name = "Jones"
print("Mr", name)

In the above example, we use the same variable "name", but its value changes, resulting in corresponding changes in the output results of the program twice.

Now that we have mastered how to assign values to variables, let's learn a little more advanced skills to let you enjoy the efficiency of Python. Sometimes we need to define several variables for calculation. For example, now I want to define three variables and set their values to 1, which can be written as follows:

a = b = c = 1

In this way, three variables are defined, and their initial values are all 1. What if the values of the three variables I want to define are different?

a, b, c = 1, 2, 3

You can try to enter such a line of code in the console, and then print the values of three variables a, B and C respectively

Through the test, it can be found that this is actually equivalent to:

a = 1
b = 2
c = 3

This is also the writing method of most other programming languages. Let's compare which writing method is more efficient?

Let's think again. Since multiple variables can be given different values at the same time, can we directly exchange the values of several variables?

# Define two variables, where a = 1 and B = 2
a,  b= 1, 2

# Now a=2, b=1
a, b = b, a

This operation is very elegant and efficient. You can try more variable exchange.

2.1.5 destruction of variables

In Python, we generally do not need to destroy variables manually. Python's garbage collection mechanism will help us dispose of variables that are no longer used. If we want to deliberately destroy and delete a variable, we can use the del keyword, like this

del name

After destruction, this variable is like it has not been defined. If you use it again, an exception will be generated. (but to be honest, I basically don't use this function myself.

Section 2 data types

If you have studied other programming languages, you may want to ask when learning variables. Why didn't you declare its type when defining a variable in Python?

This is the simplicity and efficiency of Python. Variables are not type sensitive in Python, but their values have types. Different values have different types. Let's learn about the following three basic data types:

Numeric values, including integers and floating point numbers
character string
Boolean value

2.2.1 values

There are two types of numeric values in Python, integer (int) and floating point (fl oat). Generally speaking, one does not have a decimal point and the other has a decimal point.

# This is a plastic surgery
a = 100

# This is a floating point variable
b = 3.14

Integer and floating-point values can operate on each other, such as

# c is a floating point variable
c = a + b

It's easy to understand. An integer plus a decimal must still be a decimal. Let's take another example and guess what type it is first.

a = 0.14
b = 3.14 
c = b - a
# c=3.0

The variable c is also a floating-point type, and its value is 3.0. It can be concluded that as long as there are floating-point numbers involved in the operation, its result must also be floating-point numbers.

2.2.2 string

What we use in the Hello world example is the string type

a = "Hello world"

If the string contains special characters, such as double quotation marks, we can add a \ to escape.

print("Buddha: \"What we think, we become.\"")

# The output result is: Buddha: "what we think, we come."

So far, we have used double quotation marks when defining strings. In fact, Python also supports single quotation marks. They are no different.

a = "Hello"
b = 'world'

print(a, b)
# The output is still Hello world

This flexible writing method gives us convenience. For example, in the above example where the string contains double quotation marks, we can use single quotation marks to define the string, so there is no need to escape the string in the character. Does it look much refreshing.

print('Buddha: "What we think, we become."')

Sometimes the string we want to define is too long and exceeds the length of one line. When writing, use a backslash "" to connect multiple lines:

sentence = "This's a very long long long \
long long sentence............"

print(sentence)

The above code will still be displayed as a whole line when outputting. If there is a longer string, similar to an entire paragraph, we can use three quotation marks

zen = """Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense."""

print(zen)

Of course, the double quotation marks above can also be replaced by single quotation marks.

2.2.3 Boolean (bool)

There are only two Boolean values: True and False. As the name suggests, True represents True and False represents False. We generally use Boolean values for conditional judgment. In Python 3, True and False are keywords, so we can't define them as variable names.

2.2.4 null value None

The null value none is a special value in Python. It represents null value and means "nothing". None is also a keyword. None has many uses. For example, you want to define a variable, but you haven't decided what value to assign to it, or even what type to use. You can use none first.

temp = None
print(temp)

When none is output, it is displayed as a string "None"

2.2.5 type conversion

2.2.5.1 Boolean conversion

To convert other values to Boolean values, you need to use a built-in function bool(). We enter the following codes in order on the console:

Python
# The following values are True
bool(1)
bool(-1)
bool(255)
bool(0.0000001)
bool(-99.99)

# The following value is False
bool(0)
bool(0.0)

Through the above code, it is not difficult to conclude that for numeric types, all non-zero values are converted to True, and only zero values are converted to False. Strings can also be converted to Boolean values

# This is an empty string and the conversion result is False
bool("")

# The conversion result is True
bool("abc")

# This is a string containing only one space, and the conversion result is True
bool(" ")

For any non empty string, the conversion to a Boolean value is True. Note the first and third lines of code.

Converting null values to Boolean values is always False (knocking on the blackboard)

# The result is False
bool(None)

2.2.5.2 string conversion

First, let's introduce that we can use str() to convert other types to strings,

The conversion of true, false and none values into strings is their word itself. In fact, in actual programming, we rarely need to convert them into strings to use.

str(True)
str(False)
str(None)
# The result is'True' # The result is'False' # The result is' None '

For numeric types, we can also convert them to strings with str(),

print("My age is", str(18))

In the above example, we use str() to convert 18 to "18" and then output it. In fact, in this example, if no coercion is performed, there will be no error, because the print function will automatically convert the value into a string and then output it.

2.2.5.3 numerical conversion

Numerical conversion is often used in the process of data analysis, because the numbers we read from any file are strings at the beginning, and they need to be converted into numerical values for operation.

If you want to convert an integer string to type int, use int();

num = "1"
int(num) + 1

If you remove int(), this code will report an error, because num is a string and you can't add the string and the value.

Values with spaces before and after can also be converted successfully:

int(" 100 ")
# The result is 100

Signed numbers can also be converted successfully

int("-1")  # The result is - 1 
int("+1")  # The result is 1

If you want to convert a string with a decimal point to the "oat" type, use "oat() pi =" 3.1415926 "

float(pi)

int type and "oat" type can also be converted to each other

int(3.14)  #The result is 3
int(9.9)  # The result is 9
float(100)  # The result is 100.0

Note that in the second line, 9.9 is not converted to 10. Although this is more in line with our common sense and rounding, in the process of converting "oat" to int, its decimal precision will be discarded and only the integer part will be taken. So always be careful when converting "oat" to int.

What if you want to convert by rounding? After all, this is more in line with our needs. Python provides us with a built-in function: round

round(9.9)  #The result is 10 
round(9.5)  #The result is 10
round(9.49) #The result is 9

Even, the round function allows us to specify how many decimal places to keep:
Keep two decimal places. Since the third digit is 1, the result is 3.14 round(3.1415926, 2)
Keep three decimal places. Since the fourth digit is 5, the result is 3.142 round(3.1415926, 3)

Boolean values can also be converted to int or "oat"

int(True)  # The result is 1
int(False)  # The result is 0

float(True) # The result is 1.0
float(False)# The result is 0.0

Observe that it is exactly the opposite process of converting a numeric type to a boolean type.

Section 3 operators

2.3.1 arithmetic operators

The symbols required for numerical operations in Python are as follows. Let's learn them one by one.

operator	describe	    example
+	    plus	    1 + 1; a + b
-	    reduce	    10 - 5; a - b -c
*	    ride	    4 * 2 Quite 4 × 2
/	    except	    4 / 2 Equivalent to 4 ÷ 2
//	    Take and divide 	 10 / / 4 the result is 2
%    	Take mold		10 % 4 Equivalent to 10 - (10 // 4) × 4
**	    index		2 ** 3 Equivalent to 2 * 2 * 2,That's the third power of 2
()	    parentheses	Increase operation priority, such as: (2 + 8) * 3

Let's look at a few examples:

print(1 + 1) 
print(10 - 5) 
print(4 * 2) 
print(4 / 2)  # The result is 2.0

The above examples are simple addition, subtraction, multiplication and division. We can observe the results with the naked eye. It should be noted that the division operation. When we use the single slash division operator, even if the divisor and dividend are integers, its return result is also a floating point number.

print(5 / 2)  # The result is 2.5 
print(5 // 2) # the result is 2

When we need to divide two integers, and the decimal precision of the result is not high, we generally use the double slash to perform the operation, so as to ensure that the result is also an integer without type conversion.

print(10 / 3)  # The result is 3.3335

,

The result of the above line of code is very interesting. We all know that the result of 10 ÷ 3 is 3.333... Infinite circular decimal, but infinite circular decimal is a mathematical concept after all, which can not be expressed by computer, so it can only be displayed to a certain number of digits. Careful, you may find why the last one is 5? It should be 3 if rounded. This is due to the finiteness of decimal in binary form, which is the reason of the underlying mechanism of the computer. You can ignore the details here, but remember that there is a problem of accuracy in floating-point operation.

print(10 % 4)  # The result is 2
print((2 + 8) * 3)  # The result is 30

Modulo operator can be understood as remainder for the time being. Remember the following rules:

  1. When two numbers can be divided, the result of modular operation is 0. For example, the result of 8% 4 is 0

  2. When 0 < a < B, a% B = a, for example, the result of 3% 8 is 3

  3. When there are negative numbers in two numbers, the result may be different from what we expected. Just remember this formula: a% B is equivalent to a - (a // b) * b

2.3.2 manipulating strings with arithmetic operators

Yes, there is no mistake. Strings can also be "operated" in Python. There are two operations. Let's look at addition first.

print("Hello " + "world")

The plus sign can splice two strings into one string or multiple strings together:

print("apple " + "apple " + "apple ")

What if there are too many "apple s"? It can't be added all the time. At this time, we can use the "*" operator to repeat the string several times and splice it into a string.

print("apple " * 5)

When using the plus sign to splice strings, it should be noted that strings and values cannot be added together. For example, we want to find a message for users to query integral:

print("Your account points are:" + 500)

This will report an error, so we need to convert 500 into a string before splicing, and use the knowledge we learned above to modify it as follows:

print("Your account points are:" + str(500))

2.3.3 assignment operator

In fact, we have already used the assignment operation. We will use the equals sign when defining variables earlier.

num = 1
name = "Smith"

Combined with the above operators, we can do more assignment operations:

operator	describe				example
+=		Additive assignment operator	c += a  Equivalent to c = c + a
-=		Subtraction assignment operator	c -= a  Equivalent to c = c - a
*= 		Multiplication assignment operator	c *= a  Equivalent to c = c * a
/=		Division assignment operator	c /= a  Equivalent to c = c / a
//= 		 Integer division assignment operator 	 c //= a is equivalent to c = c // a
%=		Modulo assignment operator	c %= a  Equivalent to c = c % a
**=		Power assignment operator		c = a   Equivalent to c = c a

In our daily programming, the most commonly used are addition assignment and subtraction assignment, such as setting a counter and + 1 each time

count = 0
count += 1
count += 1

After performing the addition assignment twice, the value of count becomes 2.

2.3.4 comparison operator

The comparison operator is used to operate Boolean values, compare two values together, and finally get True or False.

operator	describe		example
==		be equal to		100 == 100
!=		Not equal to	100 != 99
>		greater than		2 > 1
<		less than		1 < 2
>=		Greater than or equal to	3 >= 2
<=		Less than or equal to	2 <= 3

We can enter some comparison operations in python in the console cmd to see what their return values are

100 == 100  # True
100 == "abc"  # False
1 != 2  # True
2 != 2  # False
3 > 3  # False
3 >= 3  # True
2 < 3  # True
2 <= 3  # True

This is all in line with our common sense. You can understand it by trying to knock it once in the console. Here are some special examples:

100 == "100"   # False
100 == 50 * 2  # True
str(100) == "100"  # True
1.0 != 1  # False
int(1.9) == 1  # True

It should be noted that the value 100 and the string "100" are not equal. Be especially careful. This hidden bug is difficult to find.

2.3.4 logical operators

In real programs, the conditions that need to be judged are often complex, so we need logical operators to connect multiple comparison operations.

operator	Logical expression	describe	 
and		x and y		Either one is False,The result is False	True and False The result is False
or		x or y		Either one is True,The result is True;	True or False The result is True
not		not x		Invert condition	not False The result is True

Let's look at a few examples:

# Define two variables 
a, b = 1, 2 

a > 0 and a < b  # True

a % 2 == 0 or b % 2 == 0  # True

not a > b  # True

and, or, not they are also keywords in Python. These are three keywords that are often used. Mastering logical operators is the basis of learning any programming language well.

Logical operators can be combined with assignment operations to make your code more sophisticated:

a = 0 or 100   # a=100
b = 1 or 2  # b=1

Section IV process control

After studying the previous three sections, we have a preliminary understanding of Python programming language. If Python is a python, variables, data types and operators are its muscles and skeleton, and process control is equivalent to its nervous system. Mastering the knowledge of process control can make Python swim flexibly.

Python's process control is relatively simple, which is mainly divided into two parts: condition judgment and loop control.

2.4.1 condition judgment

2.4.1.1 if... else... Statement

Here we will introduce two important keywords, if and else. You can guess from their literal meaning that they mean "if"... "Otherwise"... Let's see how to use them in the code

num = 3

# Determine whether num can be divided by 2 by modulo operation
if num % 2 == 0:
   print(str(num) + "Is an even number")
else:
   print(str(num) + "Is an odd number")

This band code is a complete logic. In the future, the program we write will be more complex, but it is just the repetition and combination of this code.

2.4.1.2 elif

The above example is a very simple logic, an integer, which is either even or odd. If the condition is more complex, how should we write it? For example, to judge a student's test score, those with less than 60 points are failed, those with 60 ~ 90 points are qualified, and those with more than 90 points are excellent. There are three conditions.

score = 59

if score < 60:
   print("You failed the exam")
elif score < 90:
   print("You passed the exam")
else:
   print("Your test results are excellent")

In this example, a new keyword "elif" is used, which can only be used after if judgment and before else.

2.4.1.3 if conditional nesting

Let's take students' test scores as an example. Now we want to make a more detailed division of 60-100 points. 60-70 points are qualified, 70-90 points are good, and more than 90 points are excellent.

score = 100

if score >= 60:
	if score < 70:
       print("Your test result is qualified")
   elif score < 90:
       print("Your test score is good")
   else:
       print("Your test score is excellent")
else:
   print("You failed the exam")

Nested loops can be nested in countless layers, but usually we recommend reducing the number of nested layers as much as possible to increase the readability of the code.

2.4.1.3 combination with logical operators

age = 22
if age > 18 and age < 60:
   print("You are no longer a child. It's time to go to work")

The above example shows that if you are older than 18 and younger than 60, you can also write as follows:

age = 22

if 18 < age < 60:
   print("You are no longer a child. It's time to go to work")

Such code is more concise and readable, which is a unique concise writing method of Python.

2.4.1.4 automatic type conversion

if and elif are always followed by an expression. The result of this expression must be True or False. if the result calculated by the expression is not a Boolean value, the result will be automatically converted to a Boolean value, no matter what type of value it is. The result of the transformation follows the Boolean transformation law we learned before.

count = 0

if count:
	print("Conditions established")
else:
	print("The condition is not tenable")

Try to change the value of count to 1, and the condition holds.

result = None
if result:
   pass
else:
   print("Nothing")

Remember: 0, None, and empty strings are False when converted to Booleans

pass is a Python keyword that means doing nothing.

2.4.2 cycle

When we see the cycle, we first think of some objects, such as rotating fans and wheels, a circular shape. A round track, if we run along it, there will never be an end unless we stop by ourselves, but we can calculate how many laps we have run. Suppose we set a goal for ourselves before running, stop running after 10 laps, and then run 10 laps one by one, stop. This process is much like a loop statement in code.

2.4.2.1 while loop

lap = 0

while lap < 10:
   lap += 1

   print("I finished the second race" + str(lap + 1) + "circle")

Run the above code and you will get the following output:

I finished the first lap
 I finished the second lap
 I finished the third lap
 I finished the fourth lap
 I finished the fifth lap
 I finished lap 6
 I finished the seventh lap
 I finished lap 8
 I finished lap 9
 I finished lap 10

2.4.2.2 for loop

The for loop can be used to traverse a sequence. A sequence refers to an iterative and ordered set. For example, a string is a sequence. Next, we use the for loop to print all the characters in a string.

seq = "hello"

for s in seq:
   print(s)

The output of this code is as follows:

h
e
l
l
o

You can also use the for loop to print a series of numbers. Here you need to use a new built-in function: range.

for i in range(5):
   print(i)

The range function is to provide an iterator from 0 to 4, and for can traverse this iterator. Note that it starts from 0. A total of 5 numbers are printed in the whole cycle.

The output is:

0
1
2
3
4

We can modify the while loop of running circles written before, and use the for loop and range function to implement it:

for lap in range(10):
   print("I finished the second race" + str(lap + 1) + "circle")

By contrast, which is more concise and elegant? It's obviously a for loop. There is a detail to note. Since the value of lap starts from 0 to 9, we need to give it + 1 when outputting.

2.4.2.3 nested loops

Now that we have mastered the two circular writing methods, we can combine them. Let's write an example to print a rectangular or square pattern with a specified side length in the console.

# Specifies the width and height of the rectangle
width, height = 10, 5

# Because it starts printing from top to bottom, traverse the height first

for i in range(height):
	for j in range(width):
		print("*", end="")

Here, the print function has the second parameter. End means that after printing the specified content, a specified string will be printed at the end. By default, a newline character "\ n" will be added at the end of each print statement to pass an empty string to it, indicating that no output content will be added after printing the asterisk.

If the second print function does not have any parameters, it will output a newline character.

Therefore, the logic of the whole program is to output a newline character after outputting 10 asterisks. The final output pattern is as follows:

**********
**********
**********
**********
**********

Since we can print a rectangle, we can also print a right triangle:

*
**
***
****
*****

The code is as follows

for i in range(5):
   for j in range(i + 1):
       print("*", end="")

Let's take a slightly more complicated case and print out such a 99 multiplication table:

1*1=1
1*2=2 2*2=4
1*3=3 2*3=6 3*3=9
1*4=4 2*4=8 3*4=12 4*4=16
1*5=5 2*5=10 3*5=15 4*5=20 5*5=25
1*6=6 2*6=12 3*6=18 4*6=24 5*6=30 6*6=36
1*7=7 2*7=14 3*7=21 4*7=28 5*7=35 6*7=42 7*7=49
1*8=8 2*8=16 3*8=24 4*8=32 5*8=40 6*8=48 7*8=56 8*8=64
1*9=9 2*9=18 3*9=27 4*9=36 5*9=45 6*9=54 7*9=63 8*9=72 9*9=81

The code is as follows:

for i in range(1, 10):
   for j in range(1, i + 1):
       print("%s*%s=%s" % (j, i, i * j), end=" ")

2.4.2.4 break and continue

Sometimes inside a loop, we need to skip a loop temporarily or jump out of the whole loop. At this time, we need to use break and continue.

In the following example, we use the for loop and continue to print out the sum of all odd numbers within 10 and find their sum.

total = 0

for i in range(10):
   if i % 2 == 0:
       continue
   print(i, end=" + ")
   total += i

print(" = %s" % total)

The keyword break is used to break the entire loop and jump out. Look at this example. Give a string. This string is a decimal. It is required to print the integer part of the decimal.

s = "238.9237834829"

for i in s:
   if i == '.':
       print()
       break

   print(i, end='')

The integer part of the decimal point is to the left of the decimal point, and we traverse the string from left to right, so when we encounter the decimal point, we stop traversing, which just realizes the printing of the integer part of the decimal point.

2.4.3 demonstration: intelligent password lock program

In recent years, the popular intelligent password lock program, in addition to fingerprint unlocking and face recognition unlocking, will have the function of password unlocking, just in case. The password unlocking function is as follows: first set the password, and then each time you unlock, as long as the entered number contains the set password, it will be regarded as successful unlocking. This setting is to prevent others from snooping and has higher security.

First, since input is involved, let's learn about Python's built-in input function: input

password = input("Please set your password")

When this line of code is executed, the console will become the cursor flashing state. The user can input characters with the keyboard. After the input is completed, enter a carriage return to indicate the end of the input, and the input string is assigned to the variable to the left of the equal sign.

# Set initial password
password = "123"

while True:
	pwd = input("Please enter the password you want to set:")
   	# If no password is entered, the initial password is used as the password
   	if not pwd:
       	break
   	confirm_password = input("Please enter your password again:")
   	if pwd == confirm_password:
       	password = pwd
       	break
   	else:
       	print("The passwords you entered twice are inconsistent. Please re-enter them.")

print("Your initial password has been set to:" + password)
print("Enter the unlocking procedure...")

# Unlock
while True:
   	input_pwd = input("Please enter your password:")
   	# Judge whether the entered password contains a password
   	if password in input_pwd:
       	print("Unlock successfully!")
       	break
   	else:
       	print("The password you entered is incorrect. Please re-enter it")

Note password in input_pwd this line of code, the keyword in indicates that if a value is found in the specified sequence, it returns True, otherwise it returns False.

Part III data structure

Section 1 string

In any programming language, string is the most basic and important data structure. We have learned the basic usage of strings before. Now we continue to learn more in depth.

3.1.1 formatted output of string

3.1.1.1 formatting operators

In the previous example of a while loop, there is such a line of code:

print("I finished the second race" + str(lap + 1) + "circle")

Here we use two plus signs to splice strings, and convert the shaping into a string. Now we introduce a better way to print this sentence using formatted output.

print("I finished the second race%d circle" % 1)

The percent sign here is the formatting symbol, which is the same as the modulus operator, but it is used differently in different places.% d is a placeholder, indicating that it is an integer to be displayed here. There are several common placeholders:

placeholder 	describe
%d		Integer placeholder
%f		Floating point placeholder
%.f		Floating point placeholder for specifying precision
%s		String placeholder
%%		Output percentage sign%

If you pass in a floating point number to% d, it will automatically convert it to an integer

print("%d" % 3.14)  # Output 3
print("%d" % 3.99)  # Output 3

The rules for converting to integers are the same as those for type conversion, and are not rounded.

%There are two uses of f. one is direct use, such as

print("%f" % 3.14)

It will output "3.140000", and the following 0 is automatically supplemented. If we only want to output two decimal places, we can write this: Print ("%. 2F"% 3.14)

print("%.2f" % 3.1415926)

The output of the above two lines of code is "3.14", "%. 2f" specifies the number of digits after the decimal point. Even if the decimal part after the floating point number exceeds 2 digits, only two digits will be output. If it is less than two digits or an integer, it will automatically fill in zero to two digits.

print("%.2f" % 3)  # 3.00
print("%.2f" % 3.1) # 3.10
print("%s" % 100) print("%s" % 3.14)  # Output 100 # Output 3.14
print("%s" % "python")  # Output python

%s is the most extensive placeholder, which can correspond to any type of variable.
Multiple placeholders can be used simultaneously in the same string:

report = "%d year%s The company's revenue increased by percent%.2f" % (2019, "tencent", 20.28) 
print(report)

When we need to output a percentage in the string, we need to use%%, for example:

report = "%d year%s The company's revenue increased%.2f%%" % (2019, "tencent", 20.28)
print(report)

3.1.1.2 format function

In addition to the% operator, Python also provides us with a rich format for the format function of strings. For example, when outputting a long number, according to international practice, every three digits are separated by commas:

print('{:,}'.format(1234567890))  # 1,234,567,890

The format function can also format multiple parameters like%:

report = "{0}year{1}The company's revenue increased{2}%".format(2019, "tencent", 20.28)
print(report)

{0} represents the first parameter, {1} {2} represents the second and third parameters, and so on. The advantage of this is that if a parameter appears multiple times in the string, it can be passed in without repetition.

'{0}'s GDP is {1:,}... Although its GDP is only {1:,} US dollars, its per capita GDP is as high as 180000 US dollars'. format("Monaco", 7100000000)

Assuming that this GDP data is quoted in many places in the report, we only need to modify one place in case it needs to be revised.

3.1.2 subscript and slice of string

In fact, a string is also a sequence, which can be understood as a string of neat characters lined up in order to form a string. Each character has its own position in the queue, which is a subscript, also known as an index.

CHINA
12345

As shown in the table above, each character of "CHINA" string corresponds to a subscript (index) from left to right. It should be noted that in computer programming, all subscripts start from 0. When we want to access the first character of a string, the subscript used should be 0.

"CHINA"[0]

Use square brackets and numbers to indicate the specific position of the character to be accessed.

"CHINA"[1]  # 2nd character "H"
"CHINA"[4]   # 5th character "A"

The fifth character "A" is the last character of the string. We can also access it in this way:

"CHINA"[-1]  # Last character "A" 
"CHINA"[-2]  # Penultimate character "N"

The negative subscript can be accessed from right to left. This writing method is unique to Python and is very fast. For strings of any length, we can use - 1 to obtain its last character. Note that the negative subscript starts from - 1, because - 0 is also 0, resulting in repetition.

Slicing is also a feature of Python, which greatly simplifies sequence access and operation,

"CHINA"[0:3]

The above slice will get "CHI". The slice operation is to separate two subscripts with a colon. The left of the colon represents the start subscript and the right represents the end subscript. In particular, the end subscript represents the subscript intercepted at the previous position of the subscript. That [0:3] intercepts a total of 3-0 = 3 characters, starting from 0, 0, 1, 2, exactly three.

So if we use [0:0], we will get an empty string,

"CHINA"[0:0] "CHINA"[0:-1]  # Empty string # CHIN

If you want to slice the whole string, you can write it like this

"CHINA"[0:6]  # CHINA

But we usually write like this. The omission to the right of the colon indicates that it has been intercepted to the last character.

"CHINA"[0:] # CHINA

In fact, the preceding 0 can also be left blank, and the left of the colon is empty, indicating that it is intercepted from the first character.

# From 0 to end   
"CHINA"[:]  # CHINA
# From 0 to 3
"CHINA"[:3] # CHI  
# From 3rd to end
"CHINA"[2:] # INA

If you want to take one every other character, you can write # to take one every two characters

"CHINA"[::2]  # CIA

The second colon indicates the interception step size. Here, 2 means one for every two characters. If it is not transmitted, it is taken for each character by default. The step size can also be negative. If a negative number is passed, it means that it is intercepted from right to left.

# Intercept one every two characters from right to left
"CHINA"[::-2]    # AIC

Therefore, if you want to output a string in reverse order, you can write it like this

"CHINA"[::-1]  # ANIHC

3.1.3 string function

There are many functions in the string itself. In fact, we have learned a format function before. Let's introduce several other common functions: 3.1.3.1 function to remove white space characters

Let's first understand what white space characters are. White space characters include spaces, line breaks (\ n), and tabs (\ t).

print("A\tB\tC\nD\tE\tF")

It will be output neatly in the console as follows:

A B C
D E F

There is a newline character after C, so D appears on the second line. The blank between ABC and DEF is caused by the Tab character. Pressing the space bar on the keyboard will produce a space, pressing the Enter key will produce a line break, and pressing the Tab key will produce a Tab. Users often mistakenly enter these characters when entering data, so when processing the data entered by users, the blank characters at the beginning and end should be removed first.

password = "123"
input_password = " 123"
print(password == input_password)

The print output is False. Because there is a space in front of 1, the password verification fails. Therefore, the user's input must be processed first. Password = "123"

input_password = " 123"
print(password == input_password.strip())

We are in input_ A function strip() is added after password, and now the output becomes True. The strip function removes all white space characters at the beginning and end of a string.

" abc ".strip()
"\t abc \n".strip()

The result will be the string "abc", but the strip function does not remove the white space between strings

" a   b   c ".strip()

The result is "a b c", only the beginning and end blank characters are removed, and the middle blank characters are retained. In addition, there are lstrip and rstrip functions, which remove the white space characters on the left and right of the string respectively.

3.1.3.2 case operation

This is relatively simple. Let's look at the code directly.

# Make all characters uppercase 
"china".upper()  
# CHINA

# Capitalize the first letter of the string 
"china".capitalize() 
# China

# Make all characters lowercase
"CHINA".lower()
# china

# Capitalize the first letter of each word 
"i have a dream".title()
# I Have A Dream

3.1.3.3 string judgment

Determines whether the string starts or ends with the specified string

function			explain
startswith	Whether to start with the specified string
endswith	Whether to end with the specified string
isdigit		Is it a string of numbers
islower		Are all lowercase letters
isupper		Are all capital letters

3.1.3.4 find and replace

In the previous case of smart password lock, we used in to judge whether a string is contained in another character. Password = '123'

input_pwd = '456123789' 

print(password in input_pwd)  # True

In this way, it can be determined that it is input_ Whether there is a password in PWD, but if you want to know the password in input_ For the exact location in PWD, you need to use the "nd" function

input_pwd.find(password)  # The result is 3

The result is 3. In input_ Find the password in PWD, find it, and its position is 3, that is, the fourth character. If not found, - 1 is returned

input_pwd.find("notexists")   # The result is - 1

In addition to the "nd" function, the index function also has the same function. The only difference is that the index function will report an error if it does not find the corresponding string

input_pwd.index(password)  # The result is 3
# This line of code will report an error input at run time_ pwd.index("notexists")

The count function can find out how many times the specified string appears. If it does not appear, it returns 0.

"abba".count('a')  # 2
 'abba'.count('c')   # 0

The replace function provides the ability to replace parts of a string

"abba".replace('a', 'b')  # The result is' bbbb '
'apple banana'.replace('apple', 'orange')  # The result is' orange banana '

3.1.3.5 string length

There is no function to measure the length of the string itself. You need to use a Python built-in function len.

len("China")  # 5
len("")  # 0
len("a")  # 1

The len function is very important. It can measure not only the length of a string, but also all other objects with length. r = range(10)

len(r)  # 10

3.1.4 comprehensive case: abnormal number data analysis

Combined with the above character operation knowledge, we can develop a telephone number recognition program. The user inputs a string of numbers, and the program identifies whether it is a valid telephone number. If it is a valid telephone number, we can identify whether it is a fixed telephone number, mobile phone number or 400 number. After the user enters "exit", the program exits.

This is a slightly complex requirement. Before writing code, let's analyze the requirement first. First, let's list several common forms of phone numbers. The mobile phone number is 11 digits, starting with 1. The first three digits of different operators are different. Because there are too many three digits, we will judge from the first two digits, including 13, 15, 17, 18 and 19

Let's look at the fixed number, area code + telephone number. The area code may be three digits (010) or four digits (0888). The telephone number is 8 digits, which adds up to 11 or 12 digits.

The most obvious feature is the 400 phone. It starts with 400 and has 10 digits in total.

The implementation code is as follows:

cellphone_number_start = "13,15,17,18,19"
telephone_number_start = "010,021,022,025,0888,0555"

while True:
	num = input("Please enter a phone number: \n")
	if num == 'exit':
		break
	if not num:
       	print("Phone number cannot be empty")
   	num = num.strip()
   	if not num.isdigit():
       	print("You have entered an invalid phone number")
       	continue

   	if num.startswith('1') and len(num) == 11 and num[0:2] in cellphone_number_start:
       	print("This is a cell phone number")
       	continue
   	elif num.startswith('400') and len(num) == 10:
       	print("This is an advertising call")
       	continue
   	elif num.startswith("0"):   # When the code is too long, it can be divided into multiple lines with backslashes.
       	if (len(num) == 12 and num[0:4] in telephone_number_start) or \
(len(num) == 11 and num[0:3] in telephone_number_start):
           	print("This is a fixed line telephone")
           	continue
           
   	print("The number is not recognized")

Section 2 tuple

3.2.1 defining tuples

Now we know that a string is a sequence, which can be iterated, accessed by index or sliced. However, its members can only be a single character. Now let's introduce a more diversified sequence: tuple, which is called tuple in English. A tuple can be defined in this way:

t = ('My', 'age', 'is', 18)

This tuple contains three strings and an integer number. Each item in the tuple is called an element, and the four elements are arranged from left to right. Can be accessed by subscript index:

t[0]  # 'my'
t[-1]  # 18

You can also access it through the slice. Note that the slice returns a new meta group containing slice fragments.

t[0:2]  # ('My', 'age')

In fact, you can also define a metagroup without parentheses

t = 'My', 'age', 'is', 18

However, when there is only one element in a tuple, a comma must be added:

t = ('solo',)

# Or without parentheses
t = 'solo',

You can cast a sequence to a tuple

tuple('abc')  # ('a', 'b', 'c')

tuple(range(5)) # (0, 1, 2, 3, 4)

The following comma indicates that this is a tuple, otherwise it will be considered a string.

3.2.2 tuple operation

Now let's introduce another function join of string. With it, sequences such as tuples can be spliced into a whole string.

# Notice the last element
t = ('My', 'age', 'is', "18")
print(" ".join(t))  # Output result: 'My age is 18'

Note the last element. This time we set it to a string, because the join function requires that each element in the parameter sequence must be a string.

Like strings, tuples also have count and index functions, and the same method is used:

t = ('a', 'b', 'b', 'a')

t.count('a')   # 2
t.index('b')   # 1
t.index('c')   # Error

# View length 
len(t)  # 4

Tuples also support in operations. To determine whether a tuple contains an element:

'a' in t  # True

'x' in t  # False

Finally, remember that tuples and strings are read-only, that is, they cannot be modified. We cannot change an element in a tuple or a character in a string alone.

3.2.3 epoch group

Tuples belong to sequences, so you can traverse them like strings:

lst = ('a', 'b', 'c', 'd', 'e')

for i in lst:
	print(i)

Using the for loop can easily and quickly traverse tuples. The above example will print out each element in tuples. You can also use while to traverse the epoch group, although it is not often used.

lst = list(range(10))
i = 0

while i < 10:
	print(lst[i])
 	i += 1

3.2.4 comprehensive case: sales data statistics - sales crown

In real projects, data structures are usually complex, and nested tuples or even multi-layer nesting are often encountered. Let's take an example:

# When there are many and long tuple elements, it can be written like this 
sales = (("Peter", (78, 70, 65)), ("John", (88, 80, 85)), ("Tony", (90, 99, 95)), ("Henry", (80, 70, 55)), ("Mike", (95, 90, 95)))

This is a tuple containing the sales performance of all salespeople of a company in the first quarter. The unit is 10000 yuan. Each element corresponds to the information of a salesperson. The personnel information is also a tuple, including name and performance. The performance is another tuple, which is the sales in January, February and March respectively. Demand: find out the employee with the highest total sales, and output the TA's name and total sales.

champion = ''
max_amount = 0

for sale in sales:
   name = sale[0]
   quarter_amount = sale[1]
   total_amount = 0
   for month_amount in quarter_amount:
       total_amount += month_amount
       
   if total_amount > max_amount:
       max_amount = total_amount
       champion = name

print("What was the top sales in the first quarter%s, TA Our total sales are%d Ten thousand yuan" % (champion, max_amount))

The above code can also be further optimized to make the number of lines of code less and the structure simpler.

champion = ''
max_amount = 0

for name, quarter_amount in sales:
   total_amount = sum(quarter_amount)

   if total_amount > max_amount:
       champion, max_amount = name, total_amount

print("What was the top sales in the first quarter%s, TA Our total sales are%d Ten thousand yuan" % (champion, max_amount))

A sum function is used here. It is a Python built-in function that can calculate the sum of all values in a sequence.

Section III list

3.3.1 definition list

A list can be understood as a variable tuple. Its use is similar to that of a tuple. The difference is that a list can dynamically add, modify and delete elements.

Take a look at the definition of the list:

# Define an empty list
lst = []
lst = list()

# Define a list with initial values
lst = [1, 2, 3]
lst = ["a", 1, 2, 3, "b", "c"]
lst = list(range(5))
lst = list("abc")
lst = list((1, 2, 3))

You can define a list in any of the above ways. Note that the variable name uses lst and deliberately avoids list. Although list is not a keyword, we should not use these built-in names when naming variables, otherwise unpredictable errors may be caused.

3.3.2 addition, deletion, modification and query

The access of list is the same as that of string and tuple. Index or subscript can be used.

lst = ['a', 'b', 'c', 'd', 'e']
lst[0]  # 'a'
lst[1:3]  # ['b', 'c']

Can the list be modified, or take the lst above as an example:

lst.append('x')

Added an element to lst, and now the list becomes

['a', 'b', 'c', 'd', 'e', 'x']

Note that the append function always adds elements after the list, and the length of the list has also increased by 1. Therefore, the value of the original list[-1] has changed from 'e' to 'x',

len(lst)   # 6
lst[-1]  # 'x'

Modify elements in the list

lst[-1] = 'f'

# After modification, the list becomes:
# ['a', 'b', 'c', 'd', 'e', 'f']

Delete elements from the list

del lst[0]
# After deletion, the list becomes:
# ['b', 'c', 'd', 'e', 'f']

Note that since we deleted the first element, the indexes of all the remaining elements have changed. The first lst[0] has become 'b', and the following ones have moved forward. But lst[-1] hasn't changed. It's still 'f'. When it comes to delete operations, be careful to prevent the use of wrong indexes.

3.3.3 list function

List is also a sequence. It also has index and count functions and supports len functions. The usage of these functions is the same as tuples, and its loop traversal is the same as tuples. I won't repeat it. Let's introduce some list specific functions.

insert

Like the append function just introduced, the insert function is used to add a new element to the list. The difference is that append is added at the end, and insert can be added anywhere.

lst = ['a', 'c', 'e']

# Insert a string 'b' before the second element 'c'
lst.insert(1, 'b')

# The current value of lst is ['a ',' B ',' C ',' e ']

# Insert a string'd 'before the last element' e '
lst.insert(-1, 'd')

# The current value of lst is ['a ',' B ',' C ','d', 'e']

pop

Each time the pop function is called, an element will "pop up" from the list, followed by the above lst operation

temp = lst.pop()

print(lst)  # ['a', 'b', 'c', 'd']
print(temp)  # 'e'

We found that the last element 'e' of the list was missing and printed out on the console. If you want to "pop up" elements in other locations, you can pass a location parameter to the pop function, like this:

temp = lst.pop(2)

print(lst)  # ['a', 'b', 'd']
print(temp)  # 'c'

remove

Previously, we have learned to use the del keyword to delete list elements. The del operation can delete the elements of the specified subscript index. If we want to delete the elements of the specified content, we need to use the remove function.

lst = [1, 2, 1, 'a', 'b', 'c']

lst.remove('a')
print(lst)  # The value of lst is [1, 2, 1, 'b', 'c']

lst.remove(1)  # Note that 1 here is the element value, not the index
print(lst)  # The value of lst is [2, 1, 'b', 'c']

The remove function finds the first element that matches the specified value from left to right and deletes it. When using, you need to distinguish between del, pop and remove.

clear

The clear function clears all elements in the list.

lst = [1,2,3,4]

lst.clear()
print(lst)  # The result is []

extend

The extend function is a bit like the append function, but the append function can only add one element at a time, while extend can add a group. lst = []

lst.extend(range(5))
print(lst)  # [0, 1, 2, 3, 4]

lst.extend([5, 6, 7])  
print(lst)  # [0, 1, 2, 3, 4, 5, 6, 7]

reverse

Reverse the entire list. Take the lst in the previous step as an example

lst.reverse()
print(lst)  # [7, 6, 5, 4, 3, 2, 1, 0]

sort

Reorder the elements in the list according to certain rules. For numerical values, they are arranged from small to large by default. lst = [3, 5, 2, 1, 4]

lst.sort()

print(lst)  # [1, 2, 3, 4, 5]

If you want to arrange the list from large to small, you can add the reverse parameter. lst = [3, 5, 2, 1, 4]

lst = [3, 5, 2, 1, 4]
lst.sort(reverse=True)

print(lst)  # [5, 4, 3, 2, 1]

For strings, they are arranged in the order of their ASCII values. ASCII is a computer coding system based on Latin letters. All programming languages support ASCII coding. ASCII values have 128 characters, including numbers 0 ~ 9, letters a-z, A-Z, and some common symbols. Each character corresponds to a number. For example, the letter 'a' corresponds to 65, the letter 'B' corresponds to 66, and so on. In Python, you can use built-in functions to convert a character to its ASSCII value.

ord('A')  # 65

chr(66)  # 'B'

The sort function compares the first character of each string, if the first character is the same, the second character, and so on.

fruits = ['apple', 'banana', 'orange', 'blueberry']

fruits.sort()
print(fruits)  # ['apple', 'banana', 'blueberry', 'orange']

Note the order of "banana" and "blueberry".

If the elements of the list are not simple characters or numbers, how to sort them? For example, there is a list below, which stores the monthly revenue of the company in the first quarter.

revenue = [('1 month', 5610000), ('2 month', 4850000), ('3 month', 6220000)]

Note that each element in the list is a tuple. The first item of the tuple is month and the second item is sales. Now we want to sort it from high to low according to its sales. If you call the sort function directly, it sorts according to the string order of the first item in the tuple.

revenue.sort(reverse=True)  # After sorting, it is [('march ', 622000), ('february', 4850000), ('january ', 5610000)]

This is obviously wrong. The income in February is lower than that in January and should be ranked last. The key parameter should be passed

revenue.sort(reverse=True, key=lambda x:x[1])  # After sorting, it is [('march ', 622000), ('january', 5610000), ('february ', 4850000)]

The key parameter receives a function. Here we pass an anonymous function to it. We will learn about the use of the function later. Here we need to understand that through the key parameter, we specify the basis for sort sorting, which is the second item in each tuple.

copy

lst1 = [1, 2, 3]
lst2 = lst1
lst1.append(4)

After the above code is executed, the values of LST and lst2 become [1, 2, 3, 4], but we only modify lst1 in the code, and the value of lst2 also changes, which is not in line with my expectations and may lead to bug s. So if we want as like as two peas and lst1, we can use the copy function:

lst1 = [1, 2, 3]
lst2 = lst1.copy()

lst1.append(4)

print(lst1)  # [1, 2, 3, 4]
print(lst2)  # [1, 2, 3]

3.3.4 list expression

List expression is a quick expression to create a list. You can omit multiple lines of code into one line. For example, list all even numbers within 20

[i * 2 for i in range(10)]  # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

Of course, we can also implement the above code in this way

[i for i in range(0, 20, 2)]

The range function can receive three parameters: the first is the starting value (including), which can be omitted. It starts from 0 by default; The second is the end value (not included); The third is the step size, which can be omitted. It defaults to 1. Is it a bit like slicing?

The above code is equivalent to:

even_nums = []

for i in range(0, 20, 2):
	even_nums.append(i)

In contrast, the list expression is indeed more concise and elegant. Take another example, print out 26 uppercase letters.

# 65 is the ASCII value of the capital letter 'A'
print([chr(i) for i in range(65, 65 + 26)])

3.3.5 comprehensive case - sales data statistics - ranking list

Further, remember the example of finding the sales champion written earlier?

sales = (("Peter", (78, 70, 65)), ("John", (88, 80, 85)), ("Tony", (90, 99, 95)), ("Henry", (80, 70, 55)), ("Mike", (95, 90, 95)))

Now we will calculate the total sales per person and store it in a list according to the sales from more to less.

top_sales = []

for name, quarter_amount in sales:
   total_amount = sum(quarter_amount)
   top_sales.append((name, total_amount))

top_sales.sort(key=lambda x:x[1], reverse=True)
print(top_sales)

Get the following list

[('Peter', 213), ('John', 253), ('Tony', 284), ('Henry', 205), ('Mike', 280)]

Tip: this case is developed with list expression, which will be very fast.

top_sales = [(sale, sum(amount))for sale, amount in sales]
top_sales.sort(key=lambda x:x[1], reverse=True)

print(top_sales)

List expression is a very powerful and convenient writing method, which does not require everyone to master. If you can't write list expression, you can also write it in the way of for loop or while loop, but at least you can understand it.

Section 4 dictionary dict

Similar to this data structure of sales information, we can use tuple or list storage.

top_sales = [('Peter', 213), ('John', 253), ('Tony', 284), ('Henry', 205), ('Mike', 280)]

You can easily take out the sales data of the first, second or any one in the list. But it has a disadvantage. It will be troublesome if we want to get the data of a specific salesperson. For example, if you want to find Mike's data, you can only cycle through it and compare it one by one.

for sale, amount in top_sales:
   if sale == 'Mike':
       print(sale, amount)

This is not only troublesome to write, but also inefficient to execute. Assuming this is a huge sales database, how much time will it take to find it? So you have to use a dictionary.

3.4.1 definition of dictionary

Using curly braces, you can define a dictionary directly

sales = {
 'Peter': 213,
 'John': 253,
 'Tony': 284,
 'Henry': 205,
 'Mike': 280
}

On the left of each line of colon is the key, and on the right is the value, which is called the key value pair and separated by commas. Here, we deliberately write one key value pair per line. In fact, we don't require one key value pair per line, just separated by commas. Keys cannot be repeated, and values can be repeated.

For top_sales, a group of two and one-to-one corresponding list, can be directly converted into a dictionary.

sales = dict(top_sales)  # The value of sales now becomes
{
 'Peter': 213,
 'John': 253,
 'Tony': 284,
 'Henry': 205,
 'Mike': 280
}

3.4.2 addition, deletion, modification and query

With a dictionary, you can quickly retrieve any person's data now

sales['Mike']

sales['Henry']

Note that key names are case sensitive, 'mike' and 'mike' correspond to different keys respectively.

sales['mike']  # KeyError: 'mike'

This line of code will report an error because the 'mike' key does not exist. Before accessing, you need to add data corresponding keys to the dictionary:

# The value can be set to None or 0 first
sales['mike'] = 0

To modify data in a dictionary:

sales['mike'] = 300

Delete data from dictionary

del sales['mike']

3.4.3 traversal dictionary

Dictionary traversal is different from list, tuple and string. Because each item is a key value pair, you should also pay attention to it when traversing.

for key_value in sales.items():
   	print(key_value)

Note that sales.items() is a general way to write when traversing the dictionary. The items function converts the contents of the dictionary into an iterative sequence for the for loop to traverse. Each item traversed is a tuple, including keys and values. So we usually write it directly as follows:

for key, value in sales.items():
   	print(key, value)

Note the comma in the middle and the final print result.

If the items function is not used, all the key s in the dictionary will be traversed.

for key in sales:
   	print(key)

3.4.4 dictionary function

Some functions in the dictionary are the same as those in the list, such as clear and copy. These two functions are not introduced. Let's take a look at other functions.

get

If you directly access a nonexistent key in the dictionary, an error will be reported. Therefore, generally, if we are not sure whether a key exists, we will judge it first:

if 'mike' in sales:
	print(sales['mike'])

else:
 	print('mike', 0)

The in keyword is used again. Here, use in to check whether the dictionary contains the key "mike". If so, it returns True, regardless of whether the value corresponding to "mike" is empty. This way of writing is very troublesome. You have to judge first and then query every time. At this time, the get function comes in handy.

sales.get('mike', 0)

This short line of code realizes the function of the above four lines of code. It means to query the value corresponding to the 'mike' key in the dictionary. If the 'mike' key does not exist, it returns 0. The 0 here can be replaced with any other default value, which greatly simplifies the code logic.

keys/values

If you only want to list all sales personnel separately, you can write this:

sales.keys()

It can be traversed

for sale in sales.keys():
 print(sale)

If you only want to calculate the total sales of all salespeople, that is, the total sales of the company, you can directly take out the value part and sum it: sum(sales.values())

Section 5 set

In Python, a set is an unordered and non repetitive sequence, which is generally used to delete duplicate data, and calculate intersection, union, etc.

3.5.1 definition of set

Both methods can define a set

nums = {1, 2, 3, 4, 5}

nums = set([1, 2, 3, 4, 5])

Note that the set is disordered. Although we write in the order from small to large, and sometimes it is traversed in order, we can't regard it as order and use it as the basis of some logic.

The most common use of collections is to eliminate duplicate elements in lists or tuples

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

list(set(lst))

There are two 1s in the list. First convert lst into a set, then convert the set into a list, and finally get a list without duplicate elements [1, 2, 3, 4, 5]. Note that the order of the final list may be different from the original.

3.5.2 traversal set

The traversal of a set is very similar to that of a list and tuple. Again, it is not ordered.

for n in nums:
 	print(n)

You can also measure its length through the len function, which is mathematically called the cardinality of the set.

len(nums)  # 5

You can use in to determine whether there is a specific element in the collection

5 in nums  # True

3.5.3 addition, deletion, modification and query

Add an element to the collection

nums.add(5) # do nothing

nums.add(6)

If there is already this element in the collection, do nothing. Like the first line of code above, nothing is done. The elements that have been added to the set cannot be modified, but can only be deleted. Delete the elements in the set:

nums.remove(5)
nums.remove(5)  # Error

The remove function will delete the specified element from the collection, but if the element does not exist, an error will be reported, and the second line of code above will report an error. If you don't want to report an error, you can use the diicard function.

nums.discard(5)

Delete and return an element from the collection:

num = nums.pop()

If the collection is empty, an error will be reported. Sometimes, we use the pop function to iterate over a collection.

while len(nums) > 0:
	print(nums.pop())

The advantage is that each element can be used only once and will not be reused.

3.5.4 set function

# Define two sets
s1 = {1, 2, 3}
s2 = {3, 4, 5}

# Find intersection
s1.intersection(s2)  # {3}

# Union set
s3 = s1.union(s2)   # {1, 2, 3, 4, 5}
print(s3)

# Is it a subset
s1.issubset(s3)   # True

# Is it a parent set
s3.issuperset(s2)  # True

Part IV advanced Python

Section I function

In the previous learning process, we have been in contact with functions many times. Now let's get to know this important little partner. Function is a piece of code that can be called repeatedly. In Python, function is a very important concept, which is almost everywhere in programming.

4.1.1 function definition and call

In Python, we use the def keyword to define functions

def hello(name):
	print("Hello", name)

The above code defines the simplest function. Its function is to print out "Hello" and add a name. Let's look at its structure:

Calling the hello function will print "Hello, Python"

hello("Python")

What happened in the process? This is actually passing name to the hello function, that is, setting the value of name to "Python" and executing the code in the function body.

4.1.2 parameters of function

A function can have one or more parameters, or no parameters. This depends on how the parameter part is defined when defining the function. The function we defined just now has only one parameter. Now we define a function with two parameters.

def hello(name, sex):
	if sex == 'male':
		print("Hello, Mr", name)

   	elif sex == 'female':
   		print("Hello, Miss", name)

This function has two parameters, name and sex, which represent the user's name and gender respectively, so as to display different honorific names. When we call, we should pay attention to the order of parameters and not reverse them. Call function:

hello("Zhang", "male")

hello("Wang", "female")

If you have too many parameters and can't remember their order, you can write the parameter name, so you don't have to worry about the order.

hello(sex='male', name='Zhang')

If most users are women and only a few are men, this function can be modified. Let's make its sex parameter "women" by default:

def hello(name, sex='female'):
	if sex == 'male':
		print("Hello, Mr", name)
	elif sex == 'female':
		print("Hello, Miss", name)

Compared with the above function, only a default value is added after the sex parameter, so that when the user does not fill in gender information, it will default to female.

hello("Wang")

If each parameter has a default value, it can even be called without passing parameters.

def hello(name='Anonym', sex='female'):
 	if sex == 'male':
 		print("Hello, Mr", name)
	elif sex == 'female':
		print("Hello, Miss", name)

hello()  # Hello, Miss Anonym

Now this function has the ability to process data with incomplete information.

4.1.3 return value of function

If we compare the function to an employee, we are the boss who calls the function. The boss gives the employee some specific instructions, and the employee does things according to the specified process. There are some things. For example, when the boss said to clean the toilet, the employees went to work silently and finished it. If something needs to be answered, for example, the boss asked the employees to calculate the company's income last year, the boss must mean to know the final figure. The same is true for functions. There are some functions that we need to know the execution results.

def multiply(num1, num2):
	return num1 * num2

n = multiply(2, 4)
print(n)  # 8

The function of multiply function is to calculate the multiplication of two numbers. We pass in two numbers as parameters, hoping to get a result of the multiplication of these two numbers. The last line of multiply returns the result using the return keyword. Usually the result is returned on the last line of the function, but sometimes there are many possibilities.

def permit(age):
   	if age >= 18:
       	print("Permission to enter")
       	return True
   	else:
       	print("No entry")
       	return False

   	print("end")

Above, we defined a function that only allows adults to enter. If the age is greater than or equal to 18, it returns True, indicating that it is allowed to pass; Not allowed if less than 18 years old. Although there are two return statements, only one result is returned, either True or False. Note that after the return statement is executed, the function will end execution, and any statements after it will not be executed again, so the "end" in the above example will not be printed anyway.

If there is no return statement in a function, its return value is None.

def do_nothing():
   pass

print(do_nothing())  # None

4.1.4 anonymous functions

Sometimes when we need a function temporarily and its logic is relatively simple, we can define an anonymous function.

lambda n: n * n

This defines an anonymous function. The anonymous function receives a numerical parameter, calculates the square value of the number and returns it, which is equivalent to the following function.

def square(n):
	return n * n

lambda is a keyword in Python. Its function is to define anonymous functions. The function body of anonymous functions generally has only one line of code, and the function name and return value statements are omitted.

What is the function of such a function? When do I need to use anonymous functions instead of functions? Recall that we used an anonymous function when learning list sorting, and now it's time to revisit it.

revenue = [('1 month', 5610000), ('2 month', 4850000), ('3 month', 6220000)]

revenue.sort(reverse=True, key=lambda x:x[1])

The sort function key parameter of the list, which can only receive the value of one function type. Take a separate look at this anonymous function:

key = lambda x: x[1]

Now key is a function. Let's call it. x[1] this index operation shows that x must be a sequence with a length of at least 2.

key([1, 2])   # 2
key("abcd")  # 'b'

The key function returns the second element in the sequence. When sorting by sort, the second element of each element will be used as the basis for comparison. In this example, the second element is monthly income, so has the purpose of ranking by monthly income been achieved?

For such a simple function, we don't need to define a function separately, that is, use and throw, just like disposable gloves. This is the use scenario of anonymous functions.

Section 2 object oriented

4.2.1 basic concepts of object-oriented

Process oriented: write code from top to bottom according to business logic.

Object oriented: bind variables, functions and attributes together, classify and encapsulate them. As long as each program is responsible for the functions assigned to it, it can develop the program faster and reduce repeated code.

The code we wrote earlier is process oriented, which is easier for beginners to accept. Moreover, for relatively simple requirements, it is really easier to implement with process oriented.

What is the object? We can understand it as actual objects, such as a user, an ATM machine, a building, or virtual concepts generated in software business processes, such as orders, shopping carts and user accounts. We find that both entities and virtual products have something in common. They are nouns, have their own behavior and properties. For example, user objects have the same attributes, such as name, age, gender, registration time, last login time, etc. However, the values of these attributes are different for different users. Let's look at a few examples. If you want to describe a dog to another person, what are the characteristics of the dog?

varieties
 colour
 body size 

What do dogs do?

Eat something
 running
 bark

These are the characteristics and behaviors of dogs summarized based on common sense. The attribute of an object can accurately describe the characteristics of things, and the function of an object is the behavior of things.

4.2.2 categories and examples

Now let's use code to implement the "dog" object. First, we introduce an important concept in Python: class, which is also the basis of interview object programming.

class Dog:
	pass

In this way, we define a class, use the class keyword and add a class name, so we define an empty class.

Class names generally use nouns and hump nomenclature.

A class is a template for creating an object, and an object is an instance of a class. Classes are like a production line. With classes, you can produce many identical objects. Use the above Dog class to create a dog object:

dog = Dog()

print(type(dog))

Here, dog is an instance of dog. You can view the classes of any object through the built-in type function.

print(type(1))

print(type('abc'))

print(type([]))

These are the data types we have learned. We see that they are integers, strings and lists. The type of dog is dog. If we don't know whether an object is of a certain type, we can use type to judge.

print(type('abc') == str)  # True
print(type(dog) == Dog)  # True
print(type(1) == int)  # True

You can also use the built-in function isinstance to judge the relationship between objects and classes

print(isinstance('abd', str))  # True
print(isinstance(1, int))  # True
print(isinstance(dog, Dog))  # True

4.2.3 object attributes and methods

Now let's fully implement the Dog class:

class Dog:
	def __init__(self):
		self.breed = None
		self.color = None
		self.size = None
	def eat(self):
		print("I like bones")
	def run(self):
		print("I'll catch you.")
	def bark(self):
		print('Wang! Wang!')

You should note that the first parameter of each method of the class is self, but you don't need to pass parameters to it when calling. It is the difference between class methods and ordinary functions. This self represents the instance itself, which means "mine". Now let's create an instance of Dog

dog = Dog()
dog.eat()
dog.run()
dog.bark()

print('One%s type%s Colored%s' % (dog.size, dog.color, dog.breed))

Calling different methods can print different contents and reflect different behaviors. However, the printed content of the last sentence is None, because we have not set the corresponding properties.

dog.breed = 'Siberian Husky'
dog.color = 'black and white'
dog.size = 'large'

print('One%s type%s Colored%s' % (dog.size, dog.color, dog.breed))  # A large black and white husky

It will be troublesome to set properties one by one after each object is created. We can use the init function to receive initialization parameters, so that we can pass the value of the attribute as a parameter to it when initializing the object. You should also notice that the init function looks different. It is a Python class used to initialize the constructor of an object. Its name is fixed and must be written like this. It will be called first when creating an object. After changing the constructor, the code is as follows:

class Dog:
	def __init__(self, size, color, breed='Earth dog'):
		self.breed = breed
		self.color = color
		self.size = size
	def eat(self):
		print("I like bones")
	def run(self):
		print("I'll catch you.")
	def bark(self):
		print('Wang! Wang!')

Now create the object:

dog = Dog('in', 'yellow')

print('One%s type%s Colored%s' % (dog.size, dog.color, dog.breed))

The third parameter, feed, is given a default value, so you don't need to pass it.

All functions of string and list that we learned before are actually methods that call string objects and list objects.

The attributes of the object itself can be directly used in the method. For example, we can modify the bark method so that the dog can introduce himself class Dog:

	def __init__(self, size, color, breed='Earth dog'):
		self.breed = breed
		self.color = color
		self.size = size
	def eat(self):
		print("I like bones")
	def run(self):
		print("I'll catch you.")	
	def bark(self):
		print('I am a%s type%s Colored%s' % (self.size, self.color, self.breed))

The self used in the bark method here, like the self in the constructor, points to the object itself.

dog = Dog("Small", "Brown", "Teddy Dog")

dog.bark()

4.2.3 class attributes and methods

Objects are created from classes. Although the properties and methods of objects are defined in classes, their values are unique to each object and cannot be shared with each other. Classes also have properties and methods, and they can be shared with all objects created by the class. Let's define a class first

class Goods:
	def __init__(self):
		self.name = ''
		self.price = 0
		self.discount = 1

The Goods class has three object attributes. Each commodity has its own name, price and discount. I can create products at will

g1 = Goods()

g2 = Goods()

But how do you know how many products have been created? We can add a counter to the Goods class.

class Goods:
	count = 0
	def __init__(self):
		Goods.count += 1
		self.name = ''
		self.price = 0
		self.discount = 1

We add a count attribute to the Goods class, and increase it by 1 whenever we call the init function, so that we can know how many commodity objects have been created. This count is a class attribute, which can be accessed through objects or classes.

g1 = Goods()
g1.count # 1

g2 = Goods() 
Goods.count # 2

Even if there is no object defined, you can directly access the count attribute, which is the class attribute. Similarly, the class method does not need to create an object and can be accessed through the class name. Let's transform the Goods class and add an attribute id to it to represent the unique serial number of the commodity. In order to ensure that the id is not repeated, we use a counter and add 1 to each commodity created.

class Goods:
	id_count = 0
	@classmethod

	def generate_id(cls):
		cls.id_count += 1
		return cls.id_count
	
	def __init__(self):
		# The zfill function indicates that "0" is used to make up 5 digits of a number
		self.id = str(self.generate_id()).zfill(5)
		self.name = ''
		self.price = 0
		self.discount = 1

Generate here_ ID method is a class method. There is a @ classmethod in the upper line, which declares that it is a class method. Its parameter is no longer self, but cls, pointing to the class itself, which is used to access class member properties and methods inside the class method. This method sets the ID each time_ The count attribute is incremented by 1 and returned.

This @ symbol is called decorator. Decorators are used to decorate functions. Different decorators give different special functions to functions. For the classmethod decorator, you only need to know that it is used to define class methods.

Now let's try again:

g1 = Goods()
g2 = Goods()

g1.id  # 00001
g2.id  # 00002

Goods.id_count  # 2

4.2.4 all objects

In Python, everything is an object. The numbers, strings, functions and even the class itself we use are objects. All objects can use the type function to determine its type, and the dir function to view its properties and methods.

dir(dog)

All the attributes and methods of the dog object, including those just defined, will be displayed. For an object, you can also use the help function to view its help documentation.

help(sum)

help(print)

These help information can be written into the code at the time of definition:

def bark(self):
"""A dog's self introduction"""
 	print('I am a%s type%s Colored%s' % (self.size, self.color, self.breed))

After adding this document, we can use the help function to view the help information of the bark method, which helps others use our method.

help(dog.bark)

help(Dog.bark)

All objects are simple words, but its spirit is very profound. Try the following code, can you understand it?

lst = []
lst.append(Dog)
dog = lst[0]('in', 'yellow')
lst.append(dog)
lst[1].bark()
lst[1].sleep = lambda: print('Good night.')
lst.pop().sleep()

Sometimes two objects have exactly the same value. We can say that the two objects are equal, but we can't say that they are the same object.

l1 = [1, 2, 3]
l2 = [1, 2,]

l1 == l2  # False
l2.append(3) 

l1 == l2  # True

print(l1 is l2)  # False

The last line of operation uses the is keyword to determine whether the two objects are the same object, and the result is False. It indicates that l1 and l2 are different objects, which can be seen by using the id function:

id(l1)

id(l2)

Two different strings of numbers are returned respectively. This long string of numbers represents the memory space address pointed to by the object.

4.2.5 comprehensive case - Statistical Analysis of e-commerce shopping cart goods

Item demand: you can set the name, price and discount rate of each commodity. After adding the commodity to the shopping cart, you can immediately display all commodities, total price, discount status and the actual amount to be paid, that is, the amount after discount. The product name, price and discount rate can be modified at will, and after modification, the relevant information and amount in the shopping cart will also be changed.

Requirement analysis: in this requirement, two virtual products, commodity and shopping cart, are mentioned, that is, two classes need to be defined.

class Goods:
	"""Commodity category"""
	id_count = 0
	@classmethod
	def generate_id(cls):
		cls.id_count += 1
		return cls.id_count
	def __init__(self, name, price, discount=1):
		self.id = str(self.generate_id()).zfill(5)
		self.name = name
		self.price = price
		self.discount = discount

   	def calc_price(self):
   		"""Calculate the actual price after discount"""
       	return self.price * self.discount

This is a commodity class. It has four attributes: ID, commodity name, price and discount. In addition, it has a function to calculate the price of the commodity after discount. Next, let's create several commodity objects:

g1 = Goods('iPhone 11', 6000, 0.9)
g2 = Goods('U Disc 32 G', 100, 0.8)
g3 = Goods('Huawei P40', 5000)

In this way, we have created three commodity objects and set their name, price and discount. Next, let's write a shopping cart class:

class Cart:
	"""Shopping Cart"""
   	def __init__(self):
   		self.cart = {}
   		self.goods_list = []

   	def add(self, goods, num=1):
   		"""Add items to cart"""
		if goods in self.goods_list:
			self.cart[goods.id] = self.cart[goods.id] + num
		else:
			self.goods_list.append(goods)
			self.cart[goods.id] = num

   	def remove(self, goods, num):
   		"""Reduce or delete items from shopping cart"""
   		if goods not in self.goods_list:
   			return
		
		self.cart[goods.id] -= num
		
		if self.cart[goods.id] <= 0:
			del self.cart[goods.id]
           	self.goods_list.remove(goods)

   	def get_goods_by_id(self, id):
   		"""Find products by product name"""
   		for g in self.goods_list:
   			if g.id == id:
				return g

   	def get_total_amount(self):
   		"""Get the total price in the current shopping cart"""
		amount = 0
		for name, num in self.cart.items():
			goods = self.get_goods_by_id(name)
			amount += goods.price * num
		return amount

   	def get_pay_amount(self):
   		"""Get the total price actually to be paid"""
   		amount = 0
   		for name, num in self.cart.items():
   			goods = self.get_goods_by_id(name)
   			amount += goods.calc_price() * num

       	return amount

   	def show(self):
   		"""Displays the quantity, price, and total price of all items in the current shopping cart"""
   		title = ('commodity', 'Unit Price', 'quantity', 'Price (yuan)')

       	def show_row(row):
       		"""Internal function to display a line in the shopping cart"""
       		for col in row:
       			print(str(col).ljust(12), end='\t')
           	print()
       	print("-" * 70)
       	show_row(title)

       	for id, num in self.cart.items():
           	goods = self.get_goods_by_id(id)
           	price = '%.2f' % goods.price

           	if goods.discount < 1:
           		price = '%.2f (%d fracture)' % (goods.price, goods.discount * 10)            
           	show_row((goods.name, price, num, '%.2f' % (goods.calc_price() * num)))

       	total_amount = self.get_total_amount()
		pay_amount = self.get_pay_amount()

       	discount_amount = total_amount - pay_amount
		show_row(('', '', '', 'Total amount: %.2f' % total_amount))

       	if discount_amount > 0:
       		show_row(('', '', '', 'Discount: %.2f' % discount_amount))

       	show_row(('', '', '', 'Paid in amount: %.2f' % pay_amount))

This is a shopping cart class. It seems that its code is very long. There are two properties and six methods. In fact, this class mainly provides three functions:

  1. Add item add

  2. Reduce product remove

  3. Show product show

Other functions are auxiliary to realize these three main functions. Cart is a dictionary used to store the corresponding relationship between commodity and quantity. Its key name is commodity ID (string); goods_list is a list that holds the details of all goods in the shopping cart (commodity class instances). Pay attention to their data structure.

With Goods and Cart, we can add and delete Goods at will, and check the situation in the shopping Cart at any time.

cart = Cart()
cart.add(g1)
cart.add(g2, 3)
cart.show()

We can continue to add or delete, view the goods in the shopping cart and calculate the total amount at any time. If the quantity of the item is zero, it will be deleted from the shopping cart

cart.remove(g2, 2)
cart.show()
cart.remove(g2, 1)
cart.show()

If the name, price or discount of a product changes, we only need to modify the product object. Other codes do not need to be modified. The information in the shopping cart will be adjusted in real time.

cart.add(g3)
cart.show()
g3.name = 'Huawei P40 pro'
cart.show()

It can be seen that after modifying the commodity name of the g3 object, the shopping Cart is changed when it is displayed again, and our Cart class does not need to modify any code. In this way, the operation isolation between different entities is achieved. Do you feel the convenience of object-oriented?

4.2.6 user defined property

These two get functions in the Cart class_ total_ Amount and get_pay_amount. Each time they are called, they are called directly without passing any parameters. Finally, a value is returned. For this method, you can actually turn them into properties:

@property
def total_amount(self):
       	"""Get the total price in the current shopping cart"""
       	amount = 0

       	for name, num in self.cart.items():
			goods = self.get_goods_by_id(name)
			amount += goods.price * num

       	return amount

   	@property
   	def pay_amount(self):
       	"""Get the total price actually to be paid"""
       	amount = 0
       	for name, num in self.cart.items():
       		goods = self.get_goods_by_id(name)
       		amount += goods.calc_price() * num

       	return amount

We added a property decorator in front of the function name, modified the method name and removed get_, In fact, the method name can not be changed. It is modified here to make the code more readable and smooth. After the transformation, when using these two methods, you can use the common attributes as follows:

cart.total_amount

cart.pay_amount

Is it more concise and elegant to use this way?

In addition, there is a part about inheritance, which I will add later when I have time. This part is a little difficult. Don't hurry to learn first.

Section III module and package management

Python has rich standard libraries and third-party libraries. It is particularly important to learn and master the concepts of modules and packages, which determines whether we can make use of these rich resources and how to properly organize our own code.

4.3.1 module import

First, let's import a built-in module

import math

math is a module in the Python standard library for mathematical operations. We imported it with the import keyword above. Now we can use its functions.

# Find the square root of a number
math.sqrt(4)

Now we can use all the functions in the math module. We can use dir to see which functions are available

dir(math)

We can also use the statement from... Import... To import a sub module or function

from math import sqrt
sqrt(4)

This method imports a function more accurately, which is more convenient to use, but pay attention to the problem of duplicate names. If our code has a function called sqrt, we can use the as keyword to alias the module

from math import sqrt as squarte

squarte(4)  # 2

Or this:

import math as math2

math = 0
math2.sqrt(4)  # 2

Sometimes you need to import multiple modules at once. You can write this as follows

import sys, os
from math import sqrt, pow

Note that you must import before actually calling the module, otherwise an error will be generated.

# NameError will be generated
math.sqrt(4)
import math

If you import a module that does not exist, an error will also be generated.

# Modulenotfounderror will be generated: no module named 'Maht'
import maht

4.3.2 user defined module

A very simple part. I won't talk about it first. Anyway, you won't use it at the beginning. You will naturally use it later.

4.3.3 common built-in modules

In addition to the math module used above, Python has about 100 built-in modules. Let's introduce some common modules.

Datetime - datetime type

The datetime module contains several commonly used date time classes, of which the most commonly used are datetime and timedelta.

Note that the datetime we use below refers to the datetime class rather than the datetime module.

from datetime import datetime, timedelta

# Returns the datetime object of the current time
now = datetime.now()
type(now)

# View the year, month and day of the current time
print(now.year, now.month, now.day)

# View the timestamp of the current time, accurate to microseconds
now.timestamp()

The starting point of time in the computer is 00:00:00 on January 1, 1970. The timestamp is the total number of seconds from 00:00:00 on January 1, 1970 to the present. Therefore, if the value of timestamp A is smaller than that of timestamp B, it means that a precedes B.

Datetime also provides the operation of converting datetime objects and strings to each other, which is often used when processing data.

# Returns the date string in the specified format, and the following returns "2020-08-10 20:29:41"
datetime.now().strftime('%Y-%m-%d %H:%M:%S')

# Converts a string in the specified format to a datetime object
datetime.strptime('2020-01-01 00:00:00', '%Y-%m-%d %H:%M:%S')

%Y is the format code of date and time. Here are some common code meanings:

code	meaning										Example
%Y	A year with a century represented by a decimal number.				2019,2020
%m	The month displayed as a decimal number after zeroing.				01, 02, ..., 12
%d	The day of the month displayed in decimal numbers after zeroing.		01, 02, ..., 31
%H	The hour (24-hour system) expressed as a decimal number supplemented by zero.	00, 01, ..., 23
%M	Minutes displayed in decimal after zero padding.				00, 01, ..., 59
%S	The number of seconds displayed in decimal after zero padding.				00, 01, ..., 59

As long as we get the datetime object, we can convert it into various formats. Similarly, as long as there is a relatively standardized format, we can convert it to a datetime object.

After you get the datetime object, you can modify it to display the current time of last year:

now = datetime.now()
last_year = now.replace(year=2019)
print(last_year.strftime('%Y-%m-%d %H:%M:%S'))

If we want to know the time difference between two datetime objects, we can subtract the two objects

delta = now - last_year
type(delta)

The obtained object is a timedelta object. We can know how many days, minutes and seconds the two times differ according to the timedelta object.

delta.days

delta.seconds

Now delta is a timedelta object, which represents 366 days. We can also add a datetime object and a timedelta object to get a new datetime object:

now + delta

Add 366 days to the current time to make tomorrow next year. The timedelta class provides a very convenient way to help us deal with date and time. For example, we want to construct:

# Time after 20 days from the current start
datetime.now() + timedelta(days=20)

# Two and a half hours ago
datetime.now() - timedelta(hours=2, minutes=30

Time - access and conversion of time

There is also a frequently used time module, time

import time

# Returns the current timestamp
time.time()

# Returns a formatted string of the current time
time.strftime('%Y-%m-%d %H:%M:%S')

In fact, we often use another function of the time module, which can make our program sleep for a while

print("I'm so tired. I'll take a nap for three seconds")
time.sleep(3)
print("Well, I'm full of strength again!")

The sleep function pauses the current program for a number of seconds.

Random - generate random numbers

To be exact, it is a mathematical problem to generate pseudo-random numbers. The default random module will seed the random number according to the current system time, so it can ensure that the generated random number will not be repeated.

# Generate a random floating-point number, range [0.0, 1.0)
random.random()

# Generate random integers between 1 and 100, including 1 and 100
random.randint(1, 100)

# Randomly extract an element from the sequence
random.choice(['a', 'b', 'c', 'd', 'e', 'f', 'g'])

# Randomly extract k elements from the sequence. Note that the extracted elements may be repeated
random.choices(['a', 'b', 'c', 'd', 'e', 'f', 'g'], k=2)

# It is similar to the choices function, but it is a random sampling without repetition
random.sample(['a', 'b', 'c', 'd', 'e', 'f', 'g'])

# Randomly disrupt a sequence. Note that this sequence cannot be read-only
lst = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
random.shuffle(lst)

os - operating system interface

os module provides a convenient way to use the functions related to the operating system. You need to know some knowledge of the operating system.

# Gets the path to the current directory
os.getcwd()

# Create the specified directory
os.mkdir(path)

# Similar to mkdir(), but automatically creates the intermediate directory needed to reach the last level of directory.
os.makedirs(path)

# Returns a list containing the names of all files and directories in the path.
os.listdir()

Another common sub module is os.path, which provides common path operations.

# Displays the absolute path of the current directory
os.path.abspath('./')
os.path.abspath("__file__")

In most operating systems, the current directory is generally represented by. And the parent directory is represented by

Relative path: the path relative to the current directory

Absolute path: the path starting from the root directory (the root directory of windows is different from that of Mac and Linux)

Directory separator: Yes for windows, yes for Mac and Linux/

# Returns True if path is an existing directory.
os.path.isdir(path)

# Returns True if path is an existing regular file.
os.path.isfile()

# Directory separator
os.sep

# Reasonably splice one or more path parts.
os.path.join(path, *paths)

# Returns the directory name of the path path
os.path.dirname("/tmp/test.txt")  # '/tmp'

# Returns the basic name, file name, or last level directory name of the path
os.path.basename("/tmp/test.txt")  # 'test.txt'


os.path.basename("/tmp/test")  # 'test'

sys - system related parameters and functions

The first thing to look at is sys.path, which returns a list containing several paths. It represents the path sequence for Python to find packages. The first is an empty string, which represents the current directory. That's why we can import modules using the import statement.

sys.path

sys.argv indicates the command line parameters passed to the Python script at startup.

import sys

if __name__ == '__main__':
   	print("Hello", end=' ')
   	if len(sys.argv) > 1:
       	print(' '.join(sys.argv[1:]))

The above is the code of a Python script hello.py. Now let's try to start it in different ways

python hello.py

python hello.py Bill

python hello.py Mr Gates

We will see that the output is different each time. Add two lines of code to see what sys.argv is?

# sys.argv is a list
type(sys.argv)
print(sys.argv)

You can see that sys.argv is a list, and its first element is the file name of the script. Therefore, the startup parameters passed will be placed after the list. We can use this method to receive the parameters passed by the user.

Conclusion

Finally, I'll give you some small benefits. I'll put the information I've learned python on the online disk. After you try the blog code of this article, you can also look at these to help you consolidate the foundation and advance. (of course, the blog code of this article is also included)

Link: https://pan.baidu.com/s/1UPDlpr8SnyUE3X_XQRrMYA
Extraction code: 1024


CSDN@Report, I also have to study hard today

Topics: Python Programming Data Analysis