First, about the choice of version
Should I use Python 2 or Python 3 for my development activity? Reproduced from the Python website
Short Version:python 2.x are legacy, Python 3.x is the present and future of the language
Python 3.0 is released in 2008. The final 2.x version 2.7 release came out in mid-2010, with a statement of extended support for this end-of-life release. The 2.x branch would see no new major releases after that. 3.x is under active development and have already seen over five years of stable releases, including version 3.3 in 2012, 3. 4 in, and 3.5 in 2015. This means is recent standard library improvements, for example, is only available by default in Python 3.x.
You can see that the last version of Python 2.X is released and will not continue to update.
Scenarios for Python 2.X:
However, there is some key issues that could require you the use Python 2 rather than Python 3.
- Firstly, if you ' re deploying to an environment you don't control, that may impose a specific version, rather than allowing You a-selection from the available versions.
- Secondly, if you want to use a specific third party package or utility that doesn ' t yet has a released version that is CO Mpatible with Python 3, and porting this package is a non-trivial task, your may choose to use Python 2 in order to retain Access to the package.
Second, the basic knowledge of Python
1. Installation
Install Python on your Mac
Since the Mac comes with Python 2.7, it's best to use homebrew to install python3.x, which avoids modifying the python that comes with the system.
Install Homebre First, then brew install python3
install.
But use the time to pay attention to the version!!!
Install Python on Linux
The general Linux distribution default comes with python2.x, also need to download the latest source package, and then remember to modify the environment variables. In order for the system to bring the other software can be used normally, so also need to modify some configuration files and so on, such as common Yum and so on.
After installation, remember to use the Python--version command to verify that the version is correct.
2. How to write and run Python programs
Using Python's interactive command-line write program
Open with the Python command, easy to use, but not saved, but can be used in routine tests. But remember to hit the table key if you want to enter multiple lines, notice the indentation.
Using a text editor
such as notepad++, Sublime Text, Pycham.
Runtime such as Pycham can directly select the "Run" button, Sublime text using F5 and so on.
To save the file, use the end of ". Py" To declare that this is a Python program file.
Running a Python program needs to add executable permissions to the file
chmod +x hello.py
Note, however, that you need to declare the interpreter in the program file, or you will get an error.
There is another way to execute, without the need to add permissions, direct Python hello.py
Third, the Python Foundation
1.1 Data types
integral type, int, integer, such as 1, 20, 100, etc.;
Floating-point numbers, float, decimals, such as 1.1, 100.2, and so on;
String, str, is any text enclosed in single or double quotes, such as ' Tom ', ' haha ', ' 100 ';
Boolean with a Boolean value of only true, false two. Boolean values can be used with and/or/not operations.
1.1 Variables
The variable name must be a combination of uppercase and lowercase letters, numbers, and _, but cannot start with a number;
Commonly used naming methods, such as Name_list and Name_list.
2.1 Inputs and outputs
Python 2.X
On python2.x, raw_input and input two functions have input functions, but there are differences, as shown in:
You can see that input is a variable by default, so when you enter Tom directly, the hint is not defined and you must add a single quotation mark. The output is normal when the input is str.
Python 3.X
Input by default in this version is a character, so you don't need to add single quotes when you enter it.
Because the default input is a character type, so it is necessary to add int to integer type;
Input in Python 2.X is similar to the Eval function in Python 3.X.
2.2 Practice
Require a name and print
#!/usr/bin/env python3name = input ("Please input your name:") print (name)
Execution results
Please input your Name:tomtom
3.1 Article Judgment If...else
If < condition judgment 1>: < execution 1>elif < conditional judgment 2>: < execution 2>elif < conditional judgment 3>: < execution 3>else: < Executive 4>
Based on the indentation rules of Python, if the IF statement evaluates to TRUE, the statement that indents two lines is executed, otherwise nothing is done. If the if is followed by an else statement, it means that if the if is judged to be false, the content of the if is no longer executed, but instead the statement following the else is executed. Be careful not to write a colon less. If you use multiple judgements, you can use Elif.
If the order of execution is judged from top to bottom, if it is true on a certain judgment, the statements corresponding to that judgment are executed, then the remaining elif and else are ignored.
3.2 Practice
Ask for a name and job, if the input name is tom,job for cat, then output "You is tomcat!"
#!/usr/bin/env python3#__author__ = ' Jack ' name = input ("Please input your name: ") job = input ("Please input your job: ") if job = = ' Cat ': print (" You are tomcat! ") elif job = = ' dog ': print ("Your is dog.") else: print ("I don ' t know ...")
#执行结果Please input your name: kittyplease input your job:i don ' t know ... Please input your name: dogplease input your job:dogyour is dog.
4.1 While loop
In Python programming, a while statement is used to loop the execution of a program, which, under certain conditions, loops through a program to handle the same tasks that require repeated processing. Its basic form is:
While judging condition: Execute statement ...
The execution statement can be a single statement or a block of statements. The judging condition can be any expression, and any value other than 0, or non-null (NULL), is true. The loop ends when the condition false false is judged.
code example:
#! /usr/bin/env python3i = 0while i<3: print (i) i + = 1
#执行结果012
The while statement also has two important commands, continue, break to skip the loop, continue to skip the loop, and break to exit the loop.
code example:
# Continue and break usage i = 1while i <: i + = 1 if i%2 > 0: # non-even when skipping output continue print i # output dual Number 2, 4, 6, 8, 10i = 1while 1: # The loop condition is 1 must be set print i # output 1~10 i + = 1 If i >: # When I is greater than 10 o'clock jump out of the loop b Reak
The Else statement is used in the loop, and the statement in else is executed after the normal execution of the loop.
code example:
#!/usr/bin/pythoncount = 0while Count < 5: print count, "is less than 5" count = Count + 1else: PR int count, "is not less than 5" #输出结果0 are less than are less than are less than am less than Not less than 5
4.2 Practice
Ask for a lucky number, then guess, guess the output bingo!
#!/usr/bin/env python3luckey_num = 6while True: choice = int (input ("Please input you want:")) if choice = = Luckey _num: print ("Bingo!!!") Break elif Choice > Luckey_num: print ("Too bigger!!!") else: print ("Too smaller!!!")
#执行结果Please input you want:10too bigger!!! Please input Want:5too smaller!!! Please input Want:6bingo!!!
5. For loop
A Python for loop can traverse any sequence of items, such as a list or a string. code example:
For I in range: print (i) #执行结果0123456789
Circular Print List, code example:
#!/usr/bin/pythonfruits = [' banana ', ' apple ', ' Mango ']for index in range (len (fruits)): print (' Current fruit: ', fruits [index]) Print ("Good bye!") #执行结果当前水果: Banana Current fruit: Apple current fruit: Mangogood bye!
6. List and tuple
One of the data types built into Python is the list: lists. A list is an ordered set of elements that can be added and removed at any time.
For example, to print all the animals, you can use a list to indicate that the code example refers to the 5for loop.
Basic operation of the 6.1 list
Append add
Clear Clear
Copy replication
Count Statistics Element
Extend extension
Index indexes
INSERT Specifies index insertion
Pop Delete last element
Remove deletes the specified element
Reverse Flip
Sort sorts, supports numbers, letters, but does not support mixed rows
Zoo.append () Add an element to the zoo;
Zoo.copy () copy to another list;
Zoo.clear () empty the list;
Zoo.extend () extension, you can merge two lists;
Zoo.count () Number of statistical elements;
Zoo.index () outputs an index of an element;
Zoo.insert () Inserts an element at the specified index;
Zoo.pop () deletes the last element;
Zoo.remove () deletes the specified element;
Zoo.sort (), but in Python 3.x can not be mixed with the number of letters;
Zoo.resverse () Flip;
Slice, similar to a character's slice.
6.2 Tuple
Another ordered list is called a tuple: a tuple. Tuple and list are very similar, but a tuple cannot be modified once initialized
List and tuple are Python's built-in ordered set, one variable, one immutable. Choose to use them as needed.
Iv. file I/O
1.1 Open function
If you want to read and write to a file, you must first open a file with the Python built-in open () function, create a Document object, and the associated helper method can call it for read and write.
File Object = open (file_name [, access_mode][, Buffering])
The details of each parameter are as follows:
- The File_name:file_name variable is a string value that contains the name of the file you want to access.
- Access_mode:access_mode determines the mode of opening the file: read-only, write, append, etc. All the desirable values are shown in the full list below. This parameter is non-mandatory and the default file access mode is read-only (R).
- Buffering: If the value of buffering is set to 0, there is no deposit. If the value of buffering is 1, the row is stored when the file is accessed. If you set the value of buffering to an integer greater than 1, it indicates that this is the buffer size of the storage area. If a negative value is taken, the buffer size of the storage area is the system default.
1.2 Full list of open files in different modes:
R opens the file in read-only mode. The pointer to the file will be placed at the beginning of the file. This is the default mode. RB opens a file in binary format for read-only. The file pointer will be placed at the beginning of the file. This is the default mode. r+ open a file for read-write. The file pointer will be placed at the beginning of the file. rb+ opens a file in binary format for read-write. The file pointer will be placed at the beginning of the file. W opens a file for writing only. Overwrite the file if it already exists. If the file does not exist, create a new file. WB opens a file in binary format for writing only. Overwrite the file if it already exists. If the file does not exist, create a new file. w+ open a file for read-write. Overwrite the file if it already exists. If the file does not exist, create a new file. wb+ opens a file in binary format for read-write. Overwrite the file if it already exists. If the file does not exist, create a new file. A opens a file for appending. If the file already exists, the file pointer will be placed at the end of the file. In other words, the new content will be written to the existing content. If the file does not exist, create a new file to write to. AB opens a file in binary format for appending. If the file already exists, the file pointer will be placed at the end of the file. In other words, the new content will be written to the existing content. If the file does not exist, create a new file to write to. A + opens a file for read and write. If the file already exists, the file pointer will be placed at the end of the file. The file opens with an append mode. If the file does not exist, create a new file to read and write. ab+ opens a file in binary format for appending. If the file already exists, the file pointer will be placed at the end of the file. If the file does not exist, create a new file to read and write.
1.3 Properties of the file object
After a file is opened, you have a files object that you can get various information about the file.
The following is a list of all properties related to the file object:
Property Description File.closed Returns True if the file has been closed, otherwise false is returned. File.mode returns the access mode of the file being opened. File.name returns the name of the file. File.softspace if the print output must be followed by a space character, false is returned. Otherwise, returns True.
The identifier ' R ' indicates read, which opens a file successfully.
If the file does not exist, the open () function runs out a ioerror error and gives the error code and detailed information telling you that the file does not exist:
f = open (' Passwd.txxt ', ' R ') print (F.read ())
F.close () #执行结果Traceback (most recent): File "/users/jack/documents/git/change/demo/s1/ts1.py", line 3, In <module> f = open (' Passwd.txxt ', ' R ') Filenotfounderror: [Errno 2] No such file or directory: ' Passwd.txxt '
If the file opens successfully, the next call to the Read () method reads the entire contents of the file at once, and Python reads the contents into memory, denoted by a str object:
f = open (' Passwd.txt ', ' R ') print (F.read ())
F.close () #运行结果admin
The final step is to call the close () method to shut down the file. The file must be closed after it is used because the file object consumes the resources of the system, and the number of files that the operating system can open at the same time is limited:
F.close ()
Because the file reads and writes the possibility to produce the ioerror, once the error, the later F.close () will not be called. Therefore, in order to ensure that errors can be properly closed files, so you can use try...finally to achieve:
File = open (' Passwd.txt ', ' R ') Try: data = File.read () print (data) finally: file.close () print ( file.closed) #执行结果adminTrue
Each time this is a bit too tedious to write, so you can use the WITH statement to automatically call the Close () method:
With open (' Passwd.txt ') as F: print (F.read ())
The "with" statement invokes a method called "context Manager" in Python for the "F" file object. That is, it specifies "F" as a new file instance that points to the/etc/passwd content. Within a block of code that is open with, the file is open and can be read freely.
However, once the Python code exits from the code snippet that is responsible for "with", the file is automatically closed. Attempting to read content from F after we exit the "with" block causes the same ValueError exception as above. So, by using "with", you avoid explicitly closing the file operation. Python will magically and silently close the file for you in a less Python-style way.
If the file is small, read () One-time read is the most convenient, if the file has dozens of G, memory will be full. So on the safe side, you can call the read (size) method repeatedly, reading the contents of a size byte at a time. Also, call ReadLines () to read all the content at once and return the list by row. So decide how to call as needed.
If it is a configuration file, it is most convenient to call ReadLines ().
With open (' Passwd.txt ') as F: For line in F: print (line) #执行结果adminhahatomjack
With open (' Passwd.txt ') as F: For line in F.readlines (): print (line) #运行结果adminhahatomjack
2.1 Writing Files
When writing a file and reading a file, the only difference is that when the open () function is called, the incoming identifier ' W ' or ' WB ' represents the write text or binary file:
With open (' Passwd.txt ', ' W ') as F: f.write (' Zoo ') #运行结果, view Passwd.txt file Zoo
Note that if the pattern is ' w ', then it cannot be read at the same time, and the file content will be overwritten.
Introduction to Python Basics (i)