Simplest Python language teaching materials

Source: Internet
Author: User

Concise Python textbooks for non-programmers.
The Chinese meaning of python is Python.

Concepts of computer programming ¶

The main content of computer programming is numbers, text, loops, formulas, and variables.

Number of words: 1, 2, 3, 5.6, 120, 32.4, 3.1415926,-3,-0.123
Text: Hello, I am so good, you are too good, very yellow and violent, such words. It is usually enclosed by double quotation marks (") or single quotation marks. The term is called a string, which is a bunch of characters in string.
Loop: loop is a repetitive task. A computer is a very stupid machine. Basically, it only performs simple operations such as addition, subtraction, multiplication, division, greater than, less than, equal to, and loop. Programming is to split complex questions into simple units for repetition.
Thanks to the formula mentioned below, many complicated problems have already been solved. We just need to repeat other people's solutions, so we don't have to take them too fine.
The biggest advantage of the Python language is that it contains a large number of formulas to solve common problems. What you want to do is basically done by someone who helps you. You just need to organize them, bind it. For example, download the file formula, analyze the formula of the webpage content, compress the file, and process the email.
Formula: it is like a mathematical formula (a + B) 2 = a2 + 2AB + B2. Include a specific value, for example: (3 + 4) 2 = 32 + 2*3*4 + 42 = 9 + 24 + 16 = 49. The above (a + B) 2 is our formula name (of course, when programming, we will use phrases that are easy to understand as the formula name, such as the square of "and, english or pinyin). He needs two parameters A and B. The following A2 + 2AB + B2 is the specific calculation step. This is our formula.
In computers, formulas are called "functions" or "methods ". We define a function, that is, to define a formula. When we use it, we will use the parameters A and B. Just set the formula.
To make the program structure clear, we often define many functions. Divide complex problems into many small problems. Put each small problem into a function, and then use these small problem functions to solve the big problem. More importantly, we can use a lot of functions written by others to solve our own problems.
The function is used to make the program structure clear and can be applied repeatedly in different places.
Variable: it is the above a. B can represent any value and can be placed into words with an indefinite value. We use variables to store various numbers, texts, and formulas used in our programs. The so-called parameter is the variable used to define the formula. It is called the parameter. Change the vest.
In terms of terminology, we have:

Number => Number
String (string) => text
Loop => Loop
Function/method => Formula
Variable (variable) => variable

Basically, there is nothing to learn about programming. The rest is to master the specific functions and loop writing formats of various programming languages, and then to master the usage of functions that have been written by others, and then combine them.

Basic Programming ¶

The most basic Python program:

Print ("world, hello! ") Save it to the file hello. py, and enter Python hello. py in the command line to see the result.

Here we use functions and strings to output a line on the screen: World, hello!

In python, functions are used as function names (parameter 1, parameter 2)

Print is a function; print the content on the screen. "Hello, world! "Is a parameter.

I learned how to use functions, and then I learned how to define the format of functions.

Define a function ¶

Def a_ B _pingfang (A, B): c = A ** 2 + 2 * a * B + B ** 2 Return C we define a (a + B) 2 function, def is short for define, which means defining a function and a formula.

The row 1st defines a function named a_ B _pingfang. When using this function, two arguments A and B are required. There is a colon on the tail, which means: "The following section is the formula definition. Pay attention to it ".

In computer programming, * represents multiplication,/Represents division, ** represents multiplication, and B ** 2 represents the second of B.
Note: In python, indentation spaces are used to represent paragraphs, and colons (:) are used to indicate the beginning of a paragraph.

The first line of the second line indents four spaces, indicating that the four cells are indented below, all of which are the same paragraph. Used to calculate the formula defined above. Put the calculation result of A2 + 2 * a * B + B2 in C.

C is similar to a and B. It represents a variable and can be used to store numbers, texts, and even functions. Here it stores the results calculated using a and B. Because it is not in the function name, the term is "variable". In the function name, it is called a parameter.

A variable is a word used to represent a variable volume. A word can contain letters, numbers, and hyphens (_). Numbers cannot start.

Row 3: returns the result that exists in C to the user of the function.

The return command ends the execution of the function immediately. It passes the value after return to the caller and can return multiple values.

Now we can use this formula. We call this function:

Ping2 = a_ B _pingfang (2, 3) ping2 stores the result of a_ B _pingfang (2, 3), that is, the return C statement above, sent to ping2 outside.

Print the result:

Print (ping2) the entire program is:

Def a_ B _pingfang (A, B): c = A ** 2 + 2 * a * B + B ** 2 Return cping2 = a_ B _pingfang (2, 3) print (ping2) save it to test2.py and run Python test2.py to view the output 25.

Loop )¶

Of course there is a loop. How can we repeat the program? We have the while (when...), for (for...) command for loop control.

A = 0 while a <100: A = a + 1 indicates that when a <100, increase a by 1 and then repeat it. When a is equal to 100, it is over.

We have <,>, =, <=,> = ,! = To determine whether the value is greater than, less than, equal to, less than or equal to, greater than or equal to, not equal.

There are also and, or, not for logical operations. The so-called logical operation is to test the relationship between existing judgments:

A = 1 and B! = 2 to test whether the two judgments are true at the same time. A = 1 or B! = 2 to test whether at least one of the two judgments is true. Not a = 1 to test whether the result is correct. Wrong is true, right is wrong, black and white are reversed.
We also have break to interrupt the loop, and continue to immediately return to the beginning of the loop. We can also use the IF (whether) command to judge:

A = 0 while true: A = a + 1 if a> = 100: In break, true indicates that it is always correct, and false indicates an error. This section is to say that it is always executed, because while is always correct. Next we will judge whether a is greater than or equal to 100 at the if clause. If yes, we will execute the section under the IF clause. Here we interrupt the loop.

The for loop uses the list data structure described below to loop the list.

Python data concepts ¶

The following is specific to the special provisions of Python. It has several special data storage formats.

Column table: List
Tuples: tuple
Dictionary: dict (dictionary)
List objects )¶

List: stores many variables in a list, which is the meaning of a column, because it is like a train, a carriage, and a variable in each compartment. The format is B, C, 1, 3, 5, 'Grape ', 'Grape pier'. You can see that specific numbers and texts can be placed in square brackets, you can also put variables separated by commas.

The content is in a fixed position and can be extracted through their location:

Alist = [1, 3, 5, 'silly ', 'Grape', 'Grape pier', A, var1] print (alist [0]) # print "1" in Python, the number starts from 0, starts from 0, and then 1, 2, 3, 4, 5. Therefore, the first content of the alist in the list above, you can use alist [0] for extraction, and the second one uses alist [2] for extraction.
Print (alist [4]) # print 'Grape'

Here, we can introduce how to use a for loop to access all the content in this list:

For me in alist: Print (me) above, print all contents in alist.

In this loop, for the list of alist, from 0, access each of its locations, put the value at this location into me, and then for different me values, repeat the content of the following section.

In indicates that me is in alist and can also be used to judge:
If "grape" in alist: Print "grape in alist! "The content of this list can be changed. We can set the 4th positions to" Naive ":

Alist [3] = alist [3] + 'naive 'print (alist [3]) # print 'silly naive' tuples (tuple) )¶

Tuples: tuples are lists, but their contents cannot be changed. The content can only be set at the beginning. However, functions can be used between tuples and lists to change the content of a list.

Tuples are represented by parentheses, so they are called tuples.

Atuple = (2, 3, "Lao Tzu") alist = List (atuple) # changes to [2, 3, "Lao Tzu"] alist [0] = 0tuple2 = tuple (alist) # Change back (0, 3, "Lao Tzu") in Python, a string is also a special tuples, that is, the character list with immutable content.

TXT = 'abcdefg' print (txt [1]) # 'B' Dictionary (dict) Encoding )¶

Dictionary: a dictionary is like a general dictionary. A word, an explanation, another word, and another explanation. Braces:

Adict = {1: "I am explaining", 2: "I am interpreting 2", "I am 3": 3, "I am 4 ": 4} the words above are called keys or indexes, and the subsequent explanations are called "values ". The index cannot be repeated and must be unique.

We can see that the preceding words and explanations can be numbers, texts, functions, or tuples. However, the previous word cannot be a list, because the content of the list is variable, and everything that is variable cannot be indexed.

We use indexes to extract values, instead of using locations:

Adict [1] # "I am explaining" adict ["I Am 3"] #3 module modules )¶

Python contains many functions and methods written by others for direct use. For example, functions for writing network programs, functions for data computing, functions for analyzing email files, and encryption functions.

These functions are divided into modules. A module contains many functions. In specific implementation, a module is a python program file.

If the module still needs to be subdivided into more layers, each layer is a file directory. There are many Python files used as modules.

To use the module, run the "import" command: Import

Import timenow = time. Clock () print (now). We first use the time module and then use the function clock () in the time module to get the current time and print it out.

Use a period to indicate the clock function in the module time: Module name. Function Name

In python, we will use a lot of modules written by others. Can we write less source code, write less as much as possible, or be lazy?

Class callback )¶

In programming, classes are not necessary, but because many modules provided by python, the functions in them are included in the class, we need to introduce the class.

Object-Oriented Programming is now a popular programming model. individuals have to use the idea of "face object" to program. Basically, it is to package similar functions into something called a class.

This "category" is generally based on specific things as a model, such as species: Humans, cats; items: Furniture, electrical appliances. The functions in the package are basically for this class, such as talking, eating, catching mouse, and household wear.

When using a class, we first embody it and turn the class into an individual. Humans become people, cats become a cat, and furniture becomes a piece of furniture. This concrete class is called "object )". Then we can use the functions of this specific person, cat, and home to operate on specific people and things.

Define category ¶
Class renlei: def _ init _ (self, mingzi): # self is a fixed parameter, representing the object itself. Self. mingzi = mingzi # Save the name to the mingzi variable of the object. Def shui2 (Self): return self. mingzi in the class definition, each function, its first parameter, must be self. Self indicates the object itself. The variables and functions of this object are all accessed by themselves.

You can call it wo3. you and me. You can use whatever name you like, but the first one represents the object itself.
Def _ init _ (wo3. mingzi): wo3.mingzi = mingzi.
When calling a function in a class, the program automatically adds self without providing the self parameter. We only need to provide other parameters.

The _ init _ () function is a special function. It represents the required parameters when a function is created. When a function is created through a class, the program automatically calls the _ init _ () function.

Concrete class to create object metadata ¶
# Create an object. The provided function corresponds to the _ init _ () function, which is automatically provided by the Self parameter program. Xiaozhang1 = renlei ("Xiao Zhang") mingzi = xiaozhang1.shui2 () # use the format of "Object Name. Function Name ()" to call functions in the class. Print mingzi <-- "Xiaozhang" string's object property Encoding ¶

Strings, lists, tuples, and dictionaries in Python all face object classes. Therefore, they own many functions that can operate on themselves, for example:

A = "handshake is not necessarily friendship ". split () split is a string function that segments A string at a given position. When we do not give it a parameter, it is split in all spaces and a list is returned, it is a split string.

As a result, the content of A is ["handshake", "not necessarily", "is", "friendship"], which is a list of four elements.

For operations such as strings, column tables, and dictionaries, please read their instructions in the Instruction Manual. Python programming mainly relies on strings, lists, and dictionaries.

Python programming habits ¶

To write a python program, follow these steps:

All input ports will be used in the module Import
Define our own classes and functions. The functions used in each function are generally defined before the called function. In this way, when we read the program, we will know how to define the called function, what functions, what parameters are required, and what values are returned.
At the bottom of the file, call the functions and classes defined above to start working.
Try to use the built-in functions and functions in the module provided by python, so we should be familiar with the python module instruction manual.
Python runs from the top of the file. You can see that the command is executed until the last line. When we define functions and classes, they only define but do not execute them. Therefore, if Python sees them, it first saves them until it sees specific commands outside the definition. If this command calls the above function, execute the stored function.

In python, the annotation symbol is "#". That is to say, the line of text after the # symbol is used as an explanation, not as a program command.

Print ("soy sauce! ") # Print (" off my ass ") only prints" Soy Sauce ", and the rest, because it is behind #, so the program automatically ignores them as a comment language.

Complete example: Split a two-column file, input.txt, into two files: col1.txt, col2.txt, and one file and one column. Input.txt content:

A1 Ah aai1 evict ao2 evict mastiff process content:

Def split_file (filename): # divide the file into two columns: col1 = [] # store the first column col2 = [] FD = open (filename) # Open function is used to open the file, returns the object text = FD. read () # FD. read the content of file FD. Lines = text. splitlines () # split the read content into lines in lines: # split one line by repeating each line part = line. Split (none, 1. Col1.append (part [0]) # place the first part of the split after col1. Col2.append (part [1]) return col1, col2 # Return col1, col2def write_list (filename, alist): # write the text list content to the file FD = open (filename, 'w ') # Open the output file col1.txt and 'w' to specify the write mode. For line in alist: FD. write (LINE + '/N') def main (): # main function, the entry point of the program, habitually called Main () filename = 'input.txt '# Put the input file name input.txt into a variable col1, col2 = split_file (filename) # Call the segmentation function and save the result to col1, col2 write_list('col1.txt', col1) # Call The Write function write_list('col2.txt ', col2) Main () # unique off-FUNCTION command. The program starts to execute and calls the preceding main () function. In this case, the input file name is the dead input.txt. We can use the optparse module to read the files provided by the user through the command line, which is more flexible.

References ¶

For more functions and functions, refer to the official Python instruction and manual.

First familiar:

Built-in functions
Built-in data type (string, number, list, Dictionary, file object)
SYS module
Re Module
OS Module
Optparse Module
Familiar with this, basically programming is okay.

Going deep into python is a classic reference book. Although it does not cover all the content of Python modules, it is basically enough for beginners. Moreover, it is a free file, which is legal and free, and has a Chinese translation version, which is rare.

You can also refer to the Chinese description in the concise Python manual.

If you need network programming, you must be familiar with network-related modules. If you want a graphical interface, we recommend using the pygtk or pyqt graphic interface function library. At this time, you must be familiar with the concept of object programming.

For people with poor English, it is recommended to buy a Chinese document introduced by the python function module. As a reference book, you can compile and flip books while programming.

The Chinese meaning of python is Python. However, the specific source of this language is an English TV series named Monty Python.

 

This article from the csdn blog, reproduced please indicate the source: http://blog.csdn.net/suiyc/archive/2010/06/24/5692844.aspx

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.