Python basic syntax

Source: Internet
Author: User
Tags python list
This article mainly introduces the basic syntax of Python and analyzes in detail the concepts and usage skills of process control statements, expressions, functions, objects, types, and mathematical operations involved in the basic syntax of Python, for more information about the basic Python syntax, see the following section. We will share this with you for your reference. The details are as follows:

Overview:

The following content is introduced:

① Indent
② Process control statement
③ Expression
④ Function
⑤ Object Method
Type 6
7 mathematical operations

1. indent

Python developers intentionally prevent programs that violate indentation rules from being compiled to force programmers to develop good programming habits. In addition, the Python language uses indentation to indicate the start and exit of the statement block (Off-side rules), rather than using curly braces or certain keywords. Increasing indentation indicates the beginning of the statement block, while decreasing indentation indicates the exit of the statement block. Indentation is part of the syntax. For example, if statement:

If age <21: print ("You cannot buy wine. ") Print (" but you can buy gum. ") Print (" is outside the if statement block. ")

Note: The above example is python 3.0 code.

According to PEP, four spaces must be used to represent each level of indentation (it is unclear how the four spaces are defined. In actual writing, the number of spaces can be customized, but the number of spaces must be equal for each indentation ). Although tabs and other spaces can be compiled, they do not conform to the encoding rules. Supporting Tab characters and other spaces is only compatible with old Python programs and some problematic editing programs.

2. Process Control statements

If statement. When the condition is true, the statement block is run. It is often used with else and elif (equivalent to else if.

The for statement traverses the list, String, Dictionary, set, and other iterators, and processes each element in the iterator in sequence.

When the while statement is true, the statement block is run cyclically.

Try statement. Works with mongot and finally to handle exceptions that occur during the program running.

Class statement. Defines the type.

Def statement. Defines functions and types.

Pass statement. This action is empty and does not run any operation.

Assert statement. Used to test whether the running conditions are met during the program adjustment phase.

With statement. The syntax defined after Python2.6 runs statement blocks in a scenario. For example, encrypt the block before running the statement and decrypt it after it exits.

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

Raise statement. Make a mistake.

Import Statement. Import a module or package.

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

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

In statement. Determines whether an object is in a string/LIST/tuples.

3. Expression

The expression in Python is similar to that in C/C ++. However, there are differences in some writing methods.

The main arithmetic operators are similar to C/C ++.

+ ,-,*,/,//,**,~, % Indicates addition or positive subtraction or negative addition, multiplication, division, division, multiplication, population, and modulo.

>>,< <表示右移和左移。< p>

&, |, ^ Indicates the AND, OR, XOR operations of binary.

>,<, = ,! =, <=, >= Is used to compare the values of two expressions, indicating greater than, less than, equal to, not equal to, less than or equal to, and greater than or equal.

In these operators ,~, |, ^, &, <,> Must be an integer.

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

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

Python list Derivation

List comprehension is a method for creating a new list using other lists (similar to the set derivation in mathematical terms. It works in a way similar to a for loop and is also simple:

In [39]: [x*x for x in range(10)]Out[39]: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

If you only want to print the number of delimiters that can be divisible by 3, you only need to add an if part in the derivation:

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

You can also add more for statements:

In [42]: [(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, 0), (2, 1), (2, 2)]In [43]: [[x,y] for x in range(2) for y in range(2)]Out[43]: [[0, 0], [0, 1], [1, 0], [1, 1]]

Python uses lambda to represent anonymous functions. The anonymous function body can only be an expression. For example:

>>> add=lambda x, y : x + y>>> add(3,2)5

Python uses y if cond else x to represent conditional expressions. If cond is true, the expression value is y; otherwise, the expression value is x. Is equivalent to cond in C ++ and Java? Y: x.

Python lists and groups (tuple. List is written as [1, 2, 3], while tuple is written as (1, 2, 3 ). You can change the elements in the list but not tuple. In some cases, the brackets of the tuple can be omitted. Tuple

The value assignment statement is specially processed. Therefore, you can assign values to multiple variables at the same time, for example:
>>> X, y = # assign values to x and y at the same time. The final result is: x = 1, y = 2.

In particular, you can exchange the values of two variables in the following form:
>>> X, y = y, x # final result: y = 1, x = 2

Python uses '(single quotes) and "(double quotes) to represent strings. Unlike Perl, Unix Shell, Ruby, Groovy, and other languages, the two symbols work the same. Generally, if double quotation marks appear in a string, they are represented by single quotation marks.

String; otherwise, double quotation marks are used. If none of them appear, you can choose according to your personal preferences. The \ (backslash) in the string is interpreted as a special character. For example, \ n indicates a line break. Add r before the expression to indicate that Python does not interpret the \ in the string \. This method is usually used to write regular expressions or Windows File paths.

Python supports list slices to obtain a complete list. The following types are supported: str, bytes, list, And tuple. 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], the following statements are true:

Nums [2: 5] = [5, 7, 8] Cut from an element whose subscript is 2 to an element whose subscript is 5, but does not contain an element whose subscript is 5.
Nums [1:] = [3, 5, 7, 8, 13, 20] Cut to the last element.
Nums [:-3] = [1, 3, 5, 7] Cut from the first element to the last 3rd elements.
Nums [:] = [1, 3, 5, 7, 8, 13, 20] returns all elements. Changing the new list does not affect nums.
Nums [] = [3, 7] Cut from an element whose subscript is 1 to an element whose subscript is 5 but does not contain an element whose subscript is 5, and the step size is 2.

4. Functions

Python Functions Support recursion, default parameter values, and variable parameters, but do not support function overloading. To enhance code readability, you can write the "Documentation Strings" (docstrings) after the function ), it is used to explain the functions, types and meanings of parameters, return value types and value ranges, and so on. You can use the built-in function help () to print out the function help. For example:

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

5. Object Method

An object is a function bound to an object. The syntax for calling object methods is instance. method (arguments ). It is equivalent to calling Class. method (instance, arguments ). When defining an object method, you must explicitly define the first parameter. Generally, this parameter name uses self to access internal data of the object. Self is equivalent to this variable in C ++ and Java, but we can also use any other valid parameter names, such as this and mine. self and C ++, this in Java is not exactly the same. It can be regarded as a habitual usage. We can pass in any other legal name, for example:

Class Fish: def eat (self, food): if food is not None: self. hungry = Falseclass User: def _ init _ (myself, name): myself. name = name # construct a Fish instance: f = Fish () # The following two call forms are equivalent: Fish. eat (f, "earthworm") f. eat ("earthworm") u = User ('username') print (u. name)

Python recognizes some special method names starting with "_" and ending with "_". They are used to implement Operator Overloading and implement various special functions.

6. Type

Python uses a dynamic type system. During compilation, Python does not check whether the object has the called method or attribute, but does not check until it is running. Therefore, an exception may be thrown during object operations. However, although Python uses a dynamic type system, it is also strongly typed. Python prohibits unspecified operations, such as adding numbers to strings.

Like other object-oriented languages, Python allows programmers to define types. To construct an object, you only need to call the type like a function. For example, for the previously defined Fish type, use Fish (). The type itself is also a special type object (the type itself is also a type object), this special design allows reflection programming on the type.

Python has a wide range of built-in data types. Compared with Java and C ++, these data types effectively reduce the code length. The following list briefly describes the Python built-in data types (applicable to Python 3.x ):

In addition to various data types, the Python language also uses types to represent functions, modules, types, object methods, compiled Python code, runtime information, and so on. Therefore, Python is highly dynamic.

7. mathematical operations

Python uses operators similar to C and Java to support mathematical operations on integers and floating-point numbers. At the same time, it also supports the complex operation and the Integer Operation of the infinite number of digits (actually limited by the ability of the computer. In addition to the absolute value function abs (), most mathematical functions are in the math and cmath modules. The former is used for real operations, while the latter is used for complex operations. You must first import them for use, for example:

>>> import math>>> print(math.sin(math.pi/2))1.0

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

Python defines that the value of a % B is in the open range [0, B). If B is a negative number, the open range is changed to (B, 0]. This is a common definition method. However, it depends on the entire division definition. In order to let the equation: B * (a/B) + a % B = a constant, the operation of the entire Division must be in the negative infinity direction. For example, the result of 7 // 3 is 2, while the result of (-7) // 3 is-3. This algorithm is different from many other programming languages. Note that their Division operations take a value in the direction of 0. Python allows two comparison operators to be written in parallel like a common mathematical statement. For example, a <B <c is equivalent to a <B and B <c. The result of C ++ is different from that of Python. First, it calculates a <B, obtains one of the values 0 or 1 based on the size of the two, and then compares them with c.

I hope this article will help you with Python programming.

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.