The first feeling of Python learning

Source: Internet
Author: User
Tags arithmetic operators html form mathematical functions

After graduating from college to find a job, after the resignation of a job after the confusion! Get to know Python from a friend in a chance. Speaking of Python has to talk about a person, Guido van Rossum He is really not simple, very powerful a creator!!! Let me introduce you to the famous Guido van Rossum.

The founder of Python is Guido van Rossum. During the Christmas of 1989, in Amsterdam, Guido was determined to develop a new script interpreter as an inheritance of the ABC language in order to get rid of the boredom of Christmas. Python was chosen as the name of the program because he was a fan of the comedy community called Monty Python.

ABC is a language of instruction designed by Guido. As far as Guido himself is concerned, the language of ABC is very graceful and powerful and is designed specifically for non-professional programmers. However, the ABC language did not succeed, the reason, Guido think is caused by non-open. Guido is determined to avoid this error in Python. At the same time, he wanted to achieve something that had flashed in ABC but had never been realized.

In this way, Python was born in the hands of Guido. In fact, the first implementation is on a Mac machine. It can be said that python evolved from ABC and was largely influenced by the Modula-3 (another rather beautiful and powerful language designed for small groups). and a combination of Unix shell and C habits.

With further understanding, I am more and more interested in Python! Python was later known to be a powerful language, combining the virtues of c,c++,jave and its own characteristics. Python is designed with a clear, consistent style, which makes Python an easy-to-read, easy-to-maintain, widely-used language that is popular with many users. The overall guiding ideology of designer development is that, for a particular problem, there is only one best way to solve it. This is stated in the Python motto (known as the Zen of Python) written by Tim Peters: there should be one--and preferably only one--obvious the-do it. This is exactly the opposite of the central idea of the Perl language (another feature-like advanced Dynamic language), TMTOWTDI (there's more Than one-way-to-do It). Python authors intentionally design restrictive grammars that make bad programming habits (such as the next line of an if statement not indented to the right) fail to compile. One of the most important is the Python indentation rules.

The difference between one and most other languages, such as C, is that the bounds of a module are determined entirely by the position of the first character of each line in that line (and the C language is explicitly defined by a pair of curly braces {} to define the bounds of the module, which has no relation to the position of the character). This has been controversial. Since the birth of a language such as C, the grammatical meaning of the language is separated from the arrangement of the characters, which was once thought to be the progress of a programming language. It is undeniable, however, that Python does make the program clearer and more beautiful by forcing programmers to indent, including if,for and function definitions, where all the modules need to be used.

Later in my study I first came into contact with Python's first syntax: Hello,world. What is Hello,world? This is true in Python: print ("Hello,world"). Is such a simple grammatical rule, listen to the teacher said that many of the Python programming language is "Hello,world" and derived! I am very excited ah, this seemingly simple sentence of a grammar hidden so many mystery Ah! I am looking forward to the future study!

In Python I touch the second syntax: The IF statement, which is simply as follows:

                          

Many beginners in Python will ask: Which version of Python should I learn? For this question, my answer is usually "first choose the Python tutorial that best suits you, which version of Python you use in the tutorial, and you use that version." Study the difference between the different versions. " But if you want to develop a new project in Python, how do you choose the Python version? I can responsibly say that most python libraries support both Python 2.7.x and 3.x versions, so whichever version you choose is possible. But in order to avoid some common pitfalls in some versions when using Python, or to port a Python project, it is still necessary to understand the main differences between Python's two common versions. In the memory of learning Python has learned the difference between Python2.0 and Python3.0. There is a sentence in English that is very accurate, it is: Python2.0 is legacy. PYTHON3.0 is the present and the future of the language. That's a very clear statement!!!

Like most beginners, we have to install Python's unique environment before learning Python. All CGI programs receive the following environment variables,

Variable name

Describe

Content_Type

The value of this environment variable indicates the MIME type of the information being passed. Currently, the environment variable content_type is generally: application/x-www-form-urlencoded, who says the data comes from an HTML form.

Content_length

If the server and CGI program information is passed as post, this environment variable can be read from the standard input stdin bytes of valid data. This environment variable must be used when reading the input data.

Http_cookie Client, inside, COOKIE, content
Http_user_agent Provide customer browser information that contains a version number or other proprietary data
Path_info

The value of this environment variable represents the other path information immediately following the CGI program name. It often appears as a parameter to a CGI program.

Query_string

If the server and CGI program information is passed in a get, the value of this environment variable even if the information is passed. This information is followed by the CGI program name, with a question mark '? ' in between. Separated.

Remote_addr

The value of this environment variable is the IP address of the client sending the request, such as 192.168.1.67 above. This value is always present. And it is a unique identifier that Web clients need to provide to the Web server, which can be used in a CGI program to differentiate between different Web clients.

Remote_host

The value of this environment variable contains the host name of the client that sent the CGI request. If you do not support the query, you do not need to define this environment variable.

Request_method

Provides the method that the script is called. For scripts that use the http/1.0 protocol, only get and POST make sense.

Script_filename The full path of the CGI script
Script_name The name of the CGI script
server_name This is your WEB, server hostname, alias, or IP address.
Server_software The value of this environment variable contains the name and version number of the HTTP server that called the CGI program, for example

Like most languages, Python has its own grammatical rules. One of the design goals of Python is to make the code highly readable. It is designed to use punctuation and English words often used in other languages to make the code look neat and tidy. Unlike other static languages such as C and Pascal, it does not have to be repeated to write declarative statements, nor does it often have special circumstances and surprises like their syntax.

Indent in

Python developers intentionally make it impossible for a program that violates indentation rules to compile, forcing programmers to develop good programming habits. And the Python language uses indentation to represent the start and exit (Off-side rules) of a statement block, rather than using curly braces or some kind of keyword. Increasing the indentation represents the beginning of the statement block, and decreasing the indentation indicates the exit of the statement block. Indentation becomes part of the syntax. For example, if statement:

Note: The above example is the Python 3.0 version of the code, @ represents a space

According to THE PEP rules, you must use 4 spaces to represent each level of indentation (it is unclear how the 4 spaces are defined, and you can customize the number of spaces in the actual writing, but to satisfy the equal number of spaces per level of indentation). Using the tab character and the other number of spaces can be compiled through, but not in accordance with the encoding specification. Support for tab characters and other numbers of spaces is just for compatibility with very old Python programs and some problematic editing programs.

Process Control Statements

If statement, run the statement block when the condition is set. Often used in conjunction with else, elif (equivalent to else if).

For statement, iterate through the list of columns, strings, dictionaries, collections, and so on, and sequentially process each element in the iterator.

While statement that loops through the statement block when the condition is true.

Try statement. Use with except,finally to handle exceptions that occur during program operation.

Class statement. Used to define the type.

def statement. The method used to define functions and types.

Pass statement. Indicates that this line is empty and does not run any operations.

Assert statement. Used in the program tuning phase when test run conditions are met.

With statement. Python2.6 The syntax that is defined later, running a block of statements in a scene. For example, the statement block is encrypted before it is run and then decrypted after the statement block runs out.

Yield statement. Used within an iterator function to return an element. Since Python version 2.5. This statement becomes an operator.

The Raise statement. Make a mistake.

Import statement. Import a module or package.

From import statement. Import a module from a package or import an object from a module.

Import as statement. Assigns the imported object to a variable.

In statement. Determines whether an object is in a string/list/tuple.

An expression

Python's expressions are written in a similar style to C + +. Only in some of the wording of the differences.

The main arithmetic operators are similar to C + +. +,-, *,/,//, * *, ~,% respectively means addition or taking positive, subtraction or negative, multiplication, division, divisible, exponentiation, take-up, modulo. >> << represents right and left shifts. &, |, ^ denotes binary and, OR, XOR operations. <, = =,! =, <=, >= the values used to compare two expressions, respectively, are greater than, less than, equal to, not equal to, less than equals, greater than or equal to. Inside these operators, ~, |, ^, &, <<, >> must be applied to integers.

Python uses and, or, not to represent logical operations.

Is, are not used to compare whether two variables are the same object. In, no in is used to determine whether an object belongs to another object.

Python supports list comprehension, such as calculating the sum of squares of 0-9:

>>> sum (x * x for x in range (10))

285

Python uses lambda to represent anonymous functions. An anonymous function body can only be an expression. Like what:

>>> Add=lambda x, y:x + y

>>> Add (3,2)

5

Python uses y if cond else x to represent the conditional expression. This means that when cond is true, the value of the expression is Y, otherwise the value of the expression is x. Equivalent to cond?y:x in C + + and Java.

There are two types of Python (list) and tuple (tuple). The list is written in [All-in-one], and the tuple's notation is (a). You can change the elements in the list without changing the tuple. In some cases, the parentheses of a tuple can be omitted. Tuple has special handling for assignment statements. Therefore, you can assign values to multiple variables at the same time, such as:

>>> x, y=1,2# simultaneously assigns x, Y, and the final result: X=1, y=2

In particular, you can exchange the values of two variables using the following form:

>>> x, Y=y, x #最终结果: Y=1, x=2

Python uses ' (single quotation marks) and "(double quotation marks) to represent strings. Unlike languages such as Perl, the Unix shell language, or Ruby, groovy, the two symbols work the same way. In general, if double quotation marks appear in a string, a single quotation mark is used to denote the string, whereas a double quotation mark is used. If none of them appear, choose according to your preferences. The \ (backslash) that appears in the string is interpreted as a special character, such as \ n to represent a line break. The expression pre-plus r indicates that Python does not interpret \ As it appears in the string. This notation is commonly used to write regular expressions or Windows file paths.

Python supports list slices, which can be part of a complete list. The types of support cutting operations are str, bytes, list, tuple and so on. Its syntax is ... [Left:right] or ... [Left:right:stride]. Assuming that the value of the nums variable is [1, 3, 5, 7, 8, 13, 20], then the following statements are true:

Nums[2:5] = = [5, 7, 8] The element from subscript 2 is cut to the element labeled 5, but does not contain an element labeled 5.

Nums[1:] = = [3, 5, 7, 8, 13, 20] cut to the last element.

NUMS[:-3] = = [1, 3, 5, 7] from the beginning of the element has been cut to the 3rd element of the bottom.

nums[:] = = [1, 3, 5, 7, 8, 13, 20] returns all elements. Changing the new list does not affect the nums.

Nums[1:5:2] = = [3, 7] cut from the subscript 1 element to the subscript 5 element without the element labeled 5, with a step of 2

Function

Python's functions support recursion, default parameter values, and mutable parameters, but do not support function overloading. To enhance the readability of your code, you can write a "document string" (documentation Strings, or simply docstrings) after the function to explain the function, the type and meaning of the parameter, the type of return value, and the range of values. You can use the built-in function help () to print out the use of the function. Like what:

>>>def Randint (A, b): ... "Return random integer in range [A, b], including both end points." >>>help (randint) Help on Function randint in module __main__: Randint (A, b) Return random integer inrange[a, b] , including both end points.

Methods of the Object

Object refers to a function that is bound to an object. The syntax for calling an object method is Instance.method (arguments). It is equivalent to calling Class.method (instance, arguments). When you define an object method, you must explicitly define the first parameter, which typically uses self, to access the object's internal data. The self here is equivalent to the this variable in C + +, Java, but we can also use any other valid parameter name, such as this and mine, and self is not exactly the same as this in C++,java, it can be seen as a habitual usage, We can pass in any other legal name, such as:

Python recognizes some special method names that begin with "__" and End With "__", which are used to implement operator overloading and implement a variety of special functions.

Type

Python uses a dynamic type system. At compile time, Python does not check whether an object has a called method or property, but is not checked until run time. Therefore, an exception may be thrown when manipulating objects. However, although Python uses a dynamic type system, it is also strongly typed. Python prohibits operations that are not explicitly defined, such as numbers plus strings.

Like other object-oriented languages, Python allows programmers to define types. To construct an object, you only need to invoke the type like a function, for example, with fish () for the fish type defined earlier. The type itself is also a special type of object (the type itself is also a type object), a special design that allows for reflection programming of the type.

Python has a rich data type built in. These data types effectively reduce the length of code compared to Java, C + +. The following list briefly describes Python's built-in data types (for Python 3.x):

Type

Description

Example

Note
str a character-made immutable serial

' Wikipedia '

"Wikipedia"

"" "Spanning

Multiple

Lines" "

bytes A byte-made non- Changed to have serial  
list can contain multiple types of modified Variable has serial &NBSP;
tuple can contain multiple types of non- Changed has serial &NBSP;
set, Frozenset

{4.0, ' string ', true}

Frozenset ([4.0, ' String ', true])

 
Dict A configurable, non-serial, of key-value pairs {' Key1 ':, 1,0,3:,false}
Int Integer with unlimited precision 42
Float Floating-point numbers, accuracy and system-related 3.1415927
Complex Plural 3+2,7j
bool Logical value, only two values: true, False TrueFalse

In addition to various data types, the Python language uses types to represent functions, modules, types themselves, methods of objects, compiled Python code, run-time information, and so on. As a result, Python has a strong dynamic nature.

Mathematical operations

Python uses operators similar to C and Java to support mathematical operations of integers and floating-point numbers. Integer operations are also supported for complex operations and infinite digits (which are actually limited to the computer's ability). In addition to the absolute value function abs (), most mathematical functions are in the math and Cmath modules. The former is used for real arithmetic, while the latter is used for complex operations. You need to import them first, such as:

>>>importmath>>>print (Math.sin (MATH.PI/2)) 1.0

The fractions module is used to support fractional operations, and the decimal module is used to support high-precision floating-point arithmetic.

Python defines that the value of a% B is in the open interval [0, B), and if B is a negative number, the opening interval becomes (b, 0]. This is a very common way of defining. But in fact it relies on the definition of divisible. In order for the equation to be: b * (A/b) + a% B = A constant, the division operation needs to take a value to the negative infinity direction. For example, the result of 7//3 is 2, and (-7)//3 results are-3. This algorithm is not the same as many other programming languages, and it is important to note that their division of operations will take a value in the direction of 0.

Python allows two comparison operators to be written in a way that is commonly used in mathematics. For example a < b < C is equivalent to a < b and B < C. C + + does not have the same result as Python, first it calculates a < B, gets one of 0 or 12 values based on the size of the two, and then compares it to C.

The above is my experience and feeling in the early days of learning Python, the entire article I am in accordance with the production of Python, development, Python's first grammar rules, the Python environment to write! Hope that everyone in the process of learning to communicate and learn to promote common progress 1

The first feeling of Python learning

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.