The title is not intended to offend, but I think this ad is fun
. Take the above mind map if you like it. I can’t learn so much anyway.
Okay, let's get to the point
Article Directory
Preface
This series of articles assumes that you have a certain C or C++ foundation, because I started with Python after learning a little bit of C++. I also want to thank senior Qi Feng for the support.
In this series of articles, you know Baidu and use online compilers by default. Because I learned Python as a surprise, the previous compilation environment has been deleted, but I found that online compilation is really cool. I wasted that time to build that environment. What, if you learn Python well, will you almost pay for the environment?
I don't want much, just click and pay attention.
Then, the catalog of this series. To be honest, I personally prefer the two Primer Plus, so I just follow their catalog structure.
This series will also focus on cultivating your self-initiated ability. After all, I cannot tell you all the knowledge points, so the ability to solve needs by yourself is particularly important, so I am buried in the article, please do not regard them as pits , That is the exercise opportunity I left for you, please show your magic and solve it by yourself.
Python language overview
The origin of the Python language
It’s a cliché, but tracing the origin can sometimes have unexpected benefits, all in personal understanding.
The author of Python, Guido von Rossum, is indeed Dutch. In 1982, Guido received a master's degree in mathematics and computer science from the University of Amsterdam. However, even though he is considered aMathematicianBut he is moreEnjoy the fun of computer. In his words, although he possesses both mathematics and computer qualifications, he tends to do computer-related work and is keen to do any programming-related work.
At that time, he was exposed to and used languages such as Pascal, C, Fortran, etc. The basic design principle of these languages is to make machines run faster. The core of all compilers is to optimize so that the program can run. In order to increase efficiency, language also forces programmers to think like computers so that they can write programs that are more in line with machine tastes. In that era, programmers could not wait to squeeze every inch of computer power with their hands.
However, this way of thinking makes Guido feel distressed. Guido knows how to write a function in C language, but the entire writing process takes a lot of time. His other option is shell. However, the essence of the shell is to invoke commands. It is not a real language. For example, the shell has no numeric data types, and addition operations are very complicated. In short, the shell cannot fully mobilize the computer's functions.
Guido hopes that there is a language that can fully call the computer's functional interfaces like C language, and can be easily programmed like a shell.
In 1989, in order to pass the Christmas holiday, Guido began to write a compiler/interpreter for the Python language. Python comes from Guido's beloved TV series Monty Python's Flying Circus. He hopes that this new language called Python can realize his idea (A language with comprehensive functions, easy to learn, easy to use, and expandable between C and shell). As a language design lover, Guido has already had (not very successful) attempts to design languages. This time, it was just a pure hacking behavior.
In 1991, the first Python compiler (also an interpreter) was born.It is implemented in C language,And be able to call the C library (.so file). From birth,Python already has: class (class), function (function), exception handling (exception), core data types including list and dictionary (dictionary), and module-based expansion system。
type of data
Number data type
int integer (positive integer 0 and negative integer)
float floating point type is decimal
bool Boolean (True true False false)
Insert a
complex plural type (I have written this code for more than two years, and I haven't used it)
#表达方式一:
complexvar = 5 + 6j
complexvar = 3 - 2j
print(type(complexvar))
print(id(complexvar))
#表达方式二:
complex(实数,虚数)
res = complex(14,2)
print(res) => (14,2)
Container data type
str string type
'''用引号引起来的就是字符串,三种引号:单引号 双引号 三引号'''
转义字符:\ (1)把有意义的字符转变为无意义的字符
(2)把无意义的字符转变的有意义
\n 或者 \r\n : 代表"换行"意思
\t : 代表"一个缩进"意思
\r : 代表将\r后面得所有字符拉到该行首
As for other escape characters, I won’t repeat them here.
特征:可以获取,但不可以修改,有序排列
获取字符串中的数据:跟列表list 元组tuple的取值一模一样(正向下标,反向下标)
Metastring
'''Metastring can invalidate escape characters'''
String formatting
"%D %f %s" Syntax: "string"% (actual value)
%d The placeholder d represents integer data, and %nd represents n positions.
Result: XXX bought 3 inflatable dolls
%f The placeholder f represents that floating-point data retains 6 decimal points by default. If there is a value in front of f, the corresponding decimal point is retained according to the value.
Result: Today's Chinese cabbage is 2.35 yuan per catty
Result: today Chinese cabbage is 2.3 yuan a catty
%s placeholder represents a string
list list type ([])
'''Feature: data can be obtained and modified, arranged in order'''
Modification of the list
tuple type (())
'''Feature: data can be obtained but not modified, arranged in order'''
Get the data in the tuple: exactly the same as the value of the list (forward subscript, reverse subscript)
set collection type (())
setvar = {} The data type shows a dict dictionary
Features: unavailable, unmodifiable, disorderly arranged, and automatically remove duplicate data
dict dictionary( {"aaa":"bbb",})
The left side of the colon is the key, the right side is the value, and the key-value pairs are separated by commas
特征 : 可以获取,可以修改,无序排列
底层使用了哈希算法,储存的数据是散列,键值对储存的数据
获取字典当中的数据:可以获取,直接输入冒号左边的键即可取值的数据
修改字典当中的数据:可以修改,直接将要改的值替换掉 键 就可实现修改
一般在命名字典的键时,推荐使用字符串,按照变量命名的字符串.
supplement
Function to get data type: type()
Function to get variable address: id()
Arithmetic
However, for so many arithmetic operators, I suggest you read them first to get a general impression. You can save this picture first, and then find it out when you use it.
Let's talk about the same thing again-computing priority: the computing priority in the Python world is the same as our usual computing priority.
String splicing
Python has an excellent point that I like very much, that is its string concatenation.
Someone once said that programming, in the final analysis, is the manipulation of strings. I think what he said makes sense. Don't look at the bells and whistles. In the final analysis, they are all manipulation of strings.
Anyway, the string operations in C/C++ have made me drink a few pots, but I haven't had enough.
The method of string splicing in Python is simple, just use the string splicing symbol [+] to connect the variables that need to be spliced together.
However, since it is string splicing, its limitation is actually very obvious. You have to use string to splice.
What if the things I want to fight are uneven? How to do? Don't worry
Forced type conversion
There are three types of functions responsible for converting data types: str(), int() and float().
str()
The str() function can convert data into its string type, no matter whether the data is of int type or float type, as long as it is placed in parentheses. This data can be transformed into a string type.
Isn't it simple? We only need one step through str(number) to convert the integer type [153] to the string type [153], and successfully complete the data splicing.
int()
The method to convert data to integer type is also very simple, that is, the int() function. Its usage is the same as str(), just put the content you need to convert in parentheses, like this: int (converted content).
But for the use of the int() function, we should pay attention to one point: only string data that conforms to the integer specification can be coerced by int().
Even though it only has one sentence, it actually has three meanings:
首先,整数形式的字符串比如'6'和'1',可以被int()函数强制转换。
其次,文字形式,比如中文、火星文或者标点符号,不可以被int()函数强制转换。
最后,小数形式的字符串,由于Python的语法规则,也不能使用int()函数强制转换。
Although the string in floating point form, the int() function cannot be used. But floating-point numbers can be coerced by the int() function (removal method)
float()
首先float()函数的使用,也是将需要转换的数据放在括号里,像这样:float(数据)。
其次,float()函数也可以将整数和字符串转换为浮点类型。但同时,如果括号里面的数据是字符串类型,那这个数据一定得是数字形式。
So, after practicing str() and int() before, is the float() function easier to understand?
in conclusion
Standard input and output
Okay, some people may murmur, why not talk about input and output. Don't worry
print() function
括号内是数字的情况
print(520)
括号内是单引号的情况。
print('一起玩吧')
括号内是双引号的情况。
print("一起玩吧")
括号内单双引号同时存在的情况。
print("Let's play")
当然,括号内也可以是三引号,参考上面单双同时出现的情况就知道了。
The reason why I talk about input and output now is because it can contain too many things. Don't be confused by the above examples. Print can print various data types. Refer to the print() that appeared earlier in this article and the following Print() that will appear
input() function
First, let us go through a piece of code to see how the input() function is used:
input('请在以下四个选项【格兰芬多;斯莱特林;拉文克劳;赫奇帕奇】中,输入你想去的学院名字:')
The input() function is an input function. As for the above example, it requires you to enter the name of the school you want to go to in the following four options [Gryffindor; Slytherin; Ravenclaw; Hufflepuff]: 's answer.
So, when you write a question in the parentheses of the function, the input() function will display the question as it is on the screen and wait for your answer to the question in the terminal area.
But why do we need to enter the answer at the terminal? Doesn't it work?
In fact, we can think of the input() function as a door linking the real world and the code world.
When the question is passed to us from the code world, but we do not answer, the input() door waiting for input will always be open, waiting for you to send an answer inside.
important point
For the input() function, no matter what the answer we input, whether you input the integer 1234, or the string "The invisible cloak is the magic I most want to have", the input value of the input() function (collected Answer), will always be [mandatory] converted to [string] type.
At this time, it is necessary to force type conversion on the input data:choice = int(input('请输入您的选择:'))
Control statement
Conditional control statement
if judgment
Here, you may have noticed a detail: after the colon: in the conditional judgment code and before the next line of content, there will be a few spaces, but why?
First of all, in the communication language of computers, the scientific name of the space is called indentation. For example, when we write an article, we must have two spaces, which is called first line indentation.
icon
For Python, colon and indentation are a kind of syntax. It will help Python distinguish the levels between codes and understand the logic and sequence of conditional execution. [Note: The indentation is four spaces] It is recommended not to use tabs here. Just four spaces. Why are young people so lazy? Many places are restricted after they develop a habit.
if···else···
In many cases, we cannot put eggs in one basket, and we have to prepare with both hands: what should we do if the conditions are not met.
Python is very intimate, let us borrow the if...else... statement, so that coders have another choice-[if... not satisfied, just...]
In the if...else conditional statement, if and else are grouped together to form two different code blocks. It represents the mutually exclusive relationship between the condition and other conditions-if the if condition is not satisfied, the else other conditions are executed.
if···elif···else
When judging 3 or more conditions, we need to use the multi-directional judgment command in Python: if...elif...else....
When the judgment conditions exceed 3, elif can be used for multiple conditions in between.
After elif, you can not pick up else
if nested
If there is a if there is a if (that is, there is a condition in the condition) like this, how do we use Python to write the above rules and get an evaluation?
The answer is-nested conditions.
for···in···loop
The Python for loop can traverse any sequence of items, such as a list or a string.
The syntax format of for loop is as follows:
for iterating_var in sequence:
statements(s)
for letter in 'Python': # 第一个实例
print '当前字母 :', letter
fruits = ['banana', 'apple', 'mango']
for fruit in fruits: # 第二个实例
print '当前水果 :', fruit
print "Good bye!"
It can be seen that the in the template iterating_var
does not need to be assigned in advance.
range() function
Using the range(a,b) function, you can generate a sequence of integers [take the head but not the tail].
E.g:
for i in range(13,17):
print(i)
Results: 13, 14, 15, 16
,
The Range () function there is a usage, we directly experience:
for i in range(0,10,3):
print(i)
This is a slicing method. The third parameter is called the "step size", that is, the interval is a number.
Then the result of this code execution is: 0, 3, 6, 9
Loop the else statement
In python, for… else means this. The statement in for is no different from ordinary ones. The statement in else will be executed when the loop is executed normally (that is, for is not interrupted by break out), while… The same is true for else.
for num in range(10,20): # 迭代 10 到 20 之间的数字
for i in range(2,num): # 根据因子迭代
if num%i == 0: # 确定第一个因子
j=num/i # 计算第二个因子
print '%d 等于 %d * %d' % (num,i,j)
break # 跳出当前循环
else: # 循环的 else 部分
print num, '是一个质数'
while loop
The while loop is similar to the for loop, but the count variable here needs to be initialized:
Li:
a = 0 #先定义变量a,并赋值
while a < 5: #设定一个放行条件:a要小于5,才能办事
a = a + 1 # 满足条件时,就办事:将a+1
print(a) # 继续办事:将a+1的结果打印出来
Obviously, the while loop has two main points: 1. Release conditions; 2. Work flow.
Like for loops, colons and indentation of internal code are essential.
other
break
Let's take a look at the break statement first. Break means "break" and is used to end the loop, usually written as if...break. It is written like this:
# break语句搭配for循环
for...in...:
...
if ...:
break
# break语句搭配while循环
while...(条件):
...
if ...:
break
Here, if...break means that if a certain condition is met, the loop ends early. Remember, this can only be used inside the loop.
continue
Continue means "continue". This clause is also used inside the loop. When a certain condition is met, the continue statement is triggered, the following code will be skipped, and the loop will be returned directly to the beginning.
# continue语句搭配for循环
for...in...:
...
if ...:
continue
...
# continue语句搭配while循环
while...(条件):
...
if ...:
continue
...
pass
The pass statement is very simple, it means "skip" in English.
Compare two cycles
The biggest difference between the for loop and the while loop is [whether the workload of the loop is determined], the for loop is like an empty room to handle business in turn, until [all the work is done] do not leave work. But the while loop is like a checkpoint release, [when the condition is met, it keeps working], and the checkpoint is closed until the condition is not met.
Practice small project
Next, I want to talk to you about how a project is generally completed. More specifically, how do programmers think and solve problems?
icon
I think one of the most important capabilities is [Problem Resolution]. Problem dismantling refers to when doing a thing or facing a problem, disassemble it into multiple steps or multiple levels, and gradually implement and solve the problem until the final effect is achieved.
What small project should I write?
So, if you have played the number guessing game, write a number guessing game:
Functional requirements:
Implement a guessing number game, randomly generate a data within 0~100, the player guesses, after each guess, the computer tells the player whether the guess is bigger or smaller, a total of 5 chances, 5 guesses Do not come out to announce the game has failed.
It's very simple.
You can also post it in the comment area if you write it
Long tail flow optimization
It is recommended to collect, otherwise you will not find it if you paddle it.