Python Basic Grammar Classic Tutorial

Source: Internet
Author: User
This article describes the basic Python syntax. Share to everyone for your reference, as follows:

Overview:

Here are the main things to tell:

① Indent
② Process Control Statements
③-expression
④ function
Methods for ⑤ objects
⑥ type
⑦ Mathematical Operations

1. Indent

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:

If age <:  print ("You can't buy wine.")  print ("but you can buy gum.") Print ("The sentence is outside of the IF statement block.) ")

Note: The above example is Python version 3.0 code

According to THE PEP rules, you must use 4 empty glyd to represent each level of indentation (unclear about the 4-space rule, 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.

2. 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, which iterates through the iterators, such as lists, strings, dictionaries, and collections, and sequentially processes 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.

3. Expressions

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.

>>, <<>< p=""><>

&, |, ^ 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 list derivation

List comprehension is a way to create a new list (similar to a set deduction in mathematical terms) with other lists. It works like a For loop, and it's simple:

In [all]: [x*x for x in Range]]out[39]: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

If you want to print only those squares that can be divisible by 3, you can do so by adding an if section in the derivation:

In [total]: [x*x for X in xrange () if x% 3 = = 0]out[41]: [0, 9, 36, 81]

You can also add more parts of the FOR statement:

In [All]: [(x, Y) for x in range (3) for Y in range (3)]out[42]: [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2), 1), (2, 2)]in [[]: [[x, Y] for x in range (2)-Y in range (2)]out[43]: [[0, 0], [0, 1], [1, 0], [1, 1]]

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

There is 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, single quotation marks are used to denote

string, or double quotation marks instead. 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] from the subscript 1 of the element is cut to the element subscript 5 but does not contain the element labeled 5, and the step is 2.

4. Functions

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) to the function randint in module __main__:randint (A, b) Return random integer inrange[a, b], Including both end points.

5. 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:

Class Fish:  def eat (self, food): If food is not    None:      self.hungry=falseclass User:   def__init__ (Myself, Name):    myself. Example of a name= name# constructed Fish: F=fish () #以下两种调用形式是等价的: Fish.eat (F, "Earthworm") f.eat ("earthworm") u = User (' Username ') print (U. Name)

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.

6. 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):

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.

7. 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:

>>> Import math>>> 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.

I hope this article is helpful for Python program design.

  • 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.