No offense to the title, but I thought the AD was fun and the mind map above is yours to take, because I can’t learn that much anyway
Okay, cut to the chase
The article directories
-
- preface
- Overview of the Python language
-
- Origins of the Python language
- The data type
-
- Number data type
- Container data type
- STR string
-
- Yuan string
- String formatting
- List phenotype ([])
-
- List modification
- Tuple type (())
- Set set type ({})
- Dict dictionary ({“aaa”:” BBB “,})
- supplement
- arithmetic
- String splicing
- Cast casting
-
- str()
- int()
- float()
- To summarize
- Standard input output
-
- The print () function
- The input () function
-
- Pay attention to the point
- Control statements
-
- Conditional control statement
-
- If judgment
- If… else…
- The if… elif… the else
- If the nested
- For…… in circulation
-
- The range () function
- Loop through the else statement
- The while loop
- other
-
- break
- continue
- pass
- Compare the two cycles
- Practice small projects
- Long tail flow optimization
preface
This series of articles assumes that you have some basic knowledge of C or C++, because I started Python after learning a little C++. Thank you qi Feng for your support. This series of articles default you will baidu, will use the online compiler, because I am a surprise learning Python, the previous compilation environment has been deleted, but, I found that online compilation is really fun, waste that time to build that environment to do what, learn Python, will be poor that point to invite people to build environment money?
I don’t want much, just click on it. And then, the catalogue for this series, to be honest, MY preference is for the two Primer Plus books, so I’ll stick with their catalogue structure.
This series will also focus on cultivating your ability to do things on your own. After all, I cannot tell you all the knowledge points, so the ability to solve your needs by yourself is particularly important. Therefore, please do not regard the holes I have buried in the article as holes.
Image source: Black image of this article from “Wind Change Programming”
Overview of the Python language
Origins of the Python language
It’s a cliche, but sometimes there’s an unexpected benefit to going back to your roots, and it’s all in your personal savvy.
The author of Python, Guido von Rossum, was indeed Dutch. In 1982, Guido received a master’s degree in mathematics and computer science from the University of Amsterdam. But although he was a mathematician, he enjoyed computers more. In his words, despite his qualifications in mathematics and computer science, he always tended to do computer work and was keen to do anything related to programming.
At that time, he was exposed to and used languages such as Pascal, C, and Fortran. The basic design principle of these languages is to make machines run faster. The core of all compilers is to optimize the program so that it runs. To increase efficiency, languages also force programmers to think like computers in order to write programs that are more machine-friendly. It was a time when programmers wanted to wring every inch of computer power from their hands.
This way of thinking, however, troubles Guido. Guido knows how to write a feature in C, but the whole process takes a lot of time. His other option is the shell. However, the essence of the shell is to invoke commands. It’s not really a language. For example, shells have no numeric data types, and addition operations are complicated. In short, the shell does not fully mobilize the functions of the computer.
Guido hopes to have a language, this language can be like C language, can fully call the functional interface of the computer, but also like shell, can be easily programmed. Guido began writing a compiler/interpreter for Python in 1989 to pass the Christmas holidays. Python comes from Guido’s beloved Monty Python’s Flying Circus. He hopes the new language, called Python, will fulfill his vision of a fully functional, easy-to-learn, extensible language between C and shell. As a language design enthusiast, Guido has made (unsuccessful) attempts at designing languages. This time, too, it was pure hacking.
In 1991, the first Python compiler (and interpreter) was created. It is implemented in C and can call the C library (.so files). Since its birth, Python has had classes, functions, exceptions, core data types including lists and dictionaries, and an extended system based on modules.
The data type
Number data type
Int integer (positive integer 0 negative integer)
A float is a decimal number
Bool Boolean (True True False False)
Insert a complex type (which I haven’t used in over two years of writing code)
# 1.complexvar =5 + 6jcomplexvar =3 - 2j
print(type(complexvar))print(id(complexvar))
# 2.
complex(real, imaginary) res =complex(14.2)print(res) = > (14.2)
Copy the code
Container data type
STR string
"" is a string caused by quotation marks, three kinds of quotation marks: single quotation marks double quotation marks triple quotation marks" "Escape character: \(1) to turn meaningful characters into meaningless characters (2) to turn meaningless characters into meaningful \n or \r\n: represents"Line"Meaning \ T: Stands for"One indent"Meaning \r: indicates that all characters after \r are placed at the beginning of the lineCopy the code
Other escape characters are not covered here
Features: Can be obtained, but can not be modified, order to obtain the data in the string: listlisttuplestupleIs exactly the same (forward subscript, reverse subscript)Copy the code
Yuan string
Meta strings can invalidate escape characters
String formatting
“%d %f %s” syntax: “String” % (actual value)
The %d placeholder d represents integer data, and %nd represents n positions
Result: XXX bought 3 inflatable dolls
%f placeholder f indicates that floating point data is reserved with 6 decimal points by default. If f is preceded by a value, the corresponding decimal point is reserved according to the value
Result: Today Chinese cabbage 2.35 yuan a catty
Result: today Chinese cabbage 2.3 yuan a catty
The %s placeholder represents a string
List phenotype ([])
Features: Data can be retrieved and modified in order
List modification
Tuple type (())
Characteristics: Data that can be retrieved but cannot be modified, in an orderly order
Get data from a tuple: same value as list (forward subscript, reverse subscript)
Set set type ({})
The setvar = {} data type displays a dict dictionary
Features: Cannot be obtained, nor can be modified, unordered, automatically remove duplicate data
Dict dictionary ({” aaa “:” BBB “,})
To the left of the colon are the keys and to the right are the values, separated by commas
Features: The underlying hash algorithm is used to store the data as hashes, and the stored data is retrieved from the dictionary by key-value pairs. You can change it, just by replacing the key with the value that you want to change. In general, when you name dictionary keys, it's recommended to use strings, strings that are named by variables.Copy the code
supplement
Function to get data type: type() Function to get variable address: id()
arithmetic
However, with so many arithmetic operators, I suggest you look through them first to get an idea. You can save this picture first, and then look it up when you need it.
Let’s say the same thing again — computation priority: The Python world’s computation priority is the same as our usual computation priority.
String splicing
One great thing about Python that I really like is its string concatenation. Someone once said that programming is all about manipulating strings, and I think he’s right. Despite all the bells and whistles, it’s all about manipulating strings.
Anyway, I’ve had enough of the string manipulation in C/C++.
String concatenation in Python is simple. It uses the string concatenation symbol [+] to concatenate the variables to be concatenated.
But, since it’s string concatenation, the limitation is pretty obvious, you have to concatenate strings.
What if the pieces I have to put together are uneven? How to do? Don’t worry
Cast casting
There are three types of functions that convert data types: STR (), int(), and float().
str()
The STR () function converts data to its string type, whether int or float, by placing it in parentheses. This data can be transformed into a string. Isn’t that easy? We can convert integer type [153] into string type [153] by just one step of STR (number), successfully completing data concatenation.
int()
The method of converting data to an integer type is also simple: the int() function. It is used the same way as STR (), just putting what you want to convert in parentheses, like this: int(what to convert). Int () casts only string data that meets the integer specification. Int () casts only string data that meets the integer specification. Although it is only one sentence, it actually has three meanings:
First of all, integer strings like'6'and'1'That can beint() function cast. Secondly, writing forms, such as Chinese, Martian or punctuation, cannot beint() function cast. Finally, decimal strings cannot be used because of Python syntax rulesint() function cast.Copy the code
The int() function cannot be used, though, for floating-point strings. But floating-point numbers can be cast by int().
float()
First of all,floatThe () function also places the data to be converted in parentheses, like this:float(Data). Second,floatThe () function can also convert integers and strings to floating point types. But at the same time, if the data inside the parentheses is a string, it must be a number.Copy the code
So, after the previous STR () and int() exercises, is the float() function a little clearer?
To summarize
Standard input output
Okay, so some of you might be wondering, why don’t you say I/O? Don’t worry!
The print () function
In parentheses are the numbersprint(520) in parentheses are single quotes.print('Let's play.') in parentheses are double quotation marks.print("Let's play.") when both single and double quotation marks exist in parentheses.print("Let's play"(Of course, the parentheses can also be triple quotation marks, refer to the above situation.Copy the code
Print can print various types of data. See print() earlier in this article and print() later in this article.
The input () function
First, let’s take a look at how the input() function is used:
input('Please enter the name of the house you wish to attend in the following four boxes: gryffindor, Slytherin, Ravenclaw, Hufflepuff.')
Copy the code
The input() function is the input function. In the example above, it would require you to enter the name of the house you would like to go to: in the following four boxes: gryffindor; Slytherin; Ravenclaw; Hufflepuff. So, when you write a question inside the function’s parentheses, the input() function displays the question as it is on the screen and waits for your answer to the question in the terminal area.
But why do we type the answer at the terminal? How about not typing? In fact, we can think of the input() function as a door between the real world and the code world. When a question is passed to us from the code world and we don’t answer it, the input() gate stays open, waiting for you to send an answer.
Pay attention to the point
For input(), the input value (the collected answer) will always be forcibly converted to string regardless of what answer we enter, whether you enter the integer 1234 or the string “Invisibility cloak is the magic I most want to have.”
Choice = int(input(‘ Please enter your choice: ‘))
Control statements
Conditional control statement
If judgment
One detail you might notice here is that there are several empty Spaces after the colon: and before the next line in the conditional code, but why? First of all, in computer language, the technical term for space is indentation. For example, when we write an essay, we should leave two Spaces blank. This is called the first line indentation. icon
With Python, colons and indentation are syntax. It helps Python distinguish between layers of code and understand the logic and sequence of conditional execution. [Note: indent is four Spaces] Here do not use TAB, on the matter of four Spaces, young people so lazy why, after forming a habit of many places are restricted.
If… else…
Most of the time, we can not put all our eggs in one basket, we should be prepared to do two things: if the conditions are not met, we will do. Python helpfully lets us borrow if… The else… If… is not satisfied,…
In the if… Else conditional statements, if and else are grouped together to form two separate code blocks. Represents a mutually exclusive relationship between a condition and another condition — if the if condition is not satisfied, the else condition is executed.
The if… elif… the else
For three or more conditions, we use Python’s multidirectional judgment command: if… Elif… The else… .
When more than three conditions are judged, elIF can be used for all intermediate conditions.
Elif is not followed by else
If the nested
How do we write this rule in Python and evaluate it when there are ifs underneath?
The answer is nested conditions.
For…… in circulation
The Python for loop can iterate over any sequence of items, such as a list or a string.
The syntax for the for loop is as follows:
for iterating_var in sequence:
statements(s)
Copy the code
for letter in 'Python': # First instance
print ('Current letter :', letter)
fruits = ['banana'.'apple'.'mango']
for fruit in fruits: # second example
print ('Current fruit :', fruit)
print ("Good bye!")
Copy the code
As you can see, there is no pre-assignment for iterating_var in the template.
The range () function
Using the range(a,b) function, you can generate a sequence of integers. Such as:
for i in range(13.17) :print(i)
Copy the code
Results: 13, 14, 15, 16
The range() function has another use, which we’ll try directly:
for i in range(0.10.3) :print(i)
Copy the code
This is a slicing method, and the third parameter is called “step size”, which is a number of intervals. The result of this code execution is: 0, 3, 6, 9
Loop through the else statement
In Python, for… The for statement is the same as the normal statement. The else statement is executed when the loop completes normally, while… Same thing with else.
for num in range(10.20) :Iterate over numbers between 10 and 20
for i in range(2,num): # Iterating by factor
if num%i == 0: # determine the first factor
j=num/i # Compute the second factor
print ('%d = %d * %d' % (num,i,j))
break # exit the current loop
else: # else part of the loop
print (num, It's a prime number.)
Copy the code
The while loop
The while loop is similar to the for loop, except that the count variable is initialized:
a = 0 Define the variable a and assign it to it
while a < 5: # Set a release condition: A must be less than 5
a = a + 1 When the condition is met, do the job: add a+1
print(a) # Get on with business: Print out the result of a+1
Copy the code
Obviously, the while loop has two main points: 1. Release conditions; 2. Process.
As with the for loop, colons and indentation of internal code are essential.
other
break
Let’s look at the break statement first. Break means “to break” and is used to end a loop, usually written as if… Break. It’s written like this:
The # break statement is accompanied by a for loop
for.in. :...if. :break
The # break statement is accompanied by a while loop
while. (Condition):...if. :break
Copy the code
Here, if… Break means to end the loop prematurely if one of the conditions is met. Remember, this can only be used inside the loop.
continue
Continue means’ to go on ‘. This clause is also used inside the loop. When a condition is satisfied, the continue statement is fired, which skips the rest of the code and goes straight back to the beginning of the loop.
The # continue statement is accompanied by a for loop
for.in. :...if. :continue.The # continue statement is accompanied by a while loop
while. (Condition):...if. :continue.Copy the code
pass
The pass statement is very simple. It means “skip” in English.
Compare the two cycles
The biggest difference between a for loop and a while loop is whether the workload of the loop is determined. A for loop is like an empty room, and you don’t leave until you’ve done all the work. But a while loop is like a checkpoint pass, working until the checkpoint is not met
Practice small projects
Next, I’d like to talk to you about how a project is usually completed. More specifically, how do programmers think and solve problems?
I think one of the most important skills is problem solving. Problem disassembly refers to the disassembly of a matter or a problem into multiple steps or layers to gradually implement and solve the problem until the final effect is achieved.
What about a little project?
Let’s write a number guessing game for you:
Function requirements: to realize a small game to guess numbers, randomly generate a 0~100 data, by the player to guess, after each guess the computer tells the player is a big guess or a small guess, a total of 5 chances, 5 times can not guess the announcement of game failure.
That’s easy.
You can also post them in the comments section
Long tail flow optimization
The suggestion collects, otherwise paddling paddling can not find to.
I created a Python learning q & A group, interested friends can know: what is this group
The portal of the straight group:portal