SoFunction
Updated on 2024-11-15

Python basic syntax classic tutorial

This article is about basic Python syntax. It is shared for your reference as follows:

Overview:

The main story here is the following:

① Indent
② Process Control Statements
③ Expressions
④ Functions
⑤ Methods of objects
(vi) Type
⑦ Mathematical operations

1. Indentation

Python developers intentionally make programs that violate indentation rules fail to compile as a way of enforcing good programming habits among programmers. And Python uses indentation to indicate the beginning and end of a block of statements (the off-side rule), rather than using parentheses or some kind of keyword. Increasing indentation indicates the beginning of a block of statements, while decreasing indentation indicates the exit of a block of statements. Indentation becomes part of the syntax. An example is the if statement:

if age < 21:
  print("You can't buy alcohol.")
  print("But you can buy gum.")
print("This sentence is outside the if statement block.")

Note: The above example is for python 3.0.

According to PEP, 4 spaces must be used for each level of indentation (it is not clear how the 4-space rule works; in practice, you can customize the number of spaces, but you have to meet the requirement that the number of spaces between each level of indentation be equal). The use of Tab characters and other numbers of spaces can be compiled, but does not meet the coding specification. Tabs and other spaces are supported only for compatibility with very old Python programs and some problematic editors.

2. Process control statements

An if statement that runs a block of statements when a condition is met. Often used in conjunction with else, elif (equivalent to else if).

The for statement, which traverses iterators such as lists, strings, dictionaries, and collections, processes each element of the iterator in turn.

The while statement, when the condition is true, loops through the statement block.

The try statement. Used in conjunction with except and finally to handle exceptions that occur during program execution.

class statement. Used to define types.

def statement. Methods for defining functions and types.

pass statement. Indicates that this line is empty and no operation is run.

assert statement. Used to test for the fulfillment of a runtime condition during the adaptation phase of a program.

The with statement, a syntax defined in Python 2.6 onward, runs a block of statements in a scenario. For example, encrypt before running the statement block, then decrypt after the statement block runs out.

yield statement. Used inside an iterator function to return an element. Since Python 2.5. This statement has become an operator.

raise statement. Creates an error.

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 expression writing style is similar to C/C++. It only differs in some writing styles.

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

+, -, *, /, //, **, ~, % denote addition or positive, subtraction or negative, multiplication, division, integer division, multiplication, complement, and modulo, respectively.

>>, << indicate right and left shifts.

&, |, ^ represent binary AND, OR, XOR operations.

>, <, ==, ! =, <=, >= are used to compare the values of two expressions that are greater than, less than, equal to, not equal to, less than equal to, greater than equal to, respectively.

Within these operators, ~, |, ^, &, <<, >> must be applied to integers.

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 Derivative

List comprehension is a method of creating new lists (similar to set comprehension in math terms) from other lists. It works like a for loop and is very 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 out those squares that are divisible by 3, you can do so simply by adding 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]

It is also possible to add more sections of 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. Anonymous function bodies can only be expressions. For example:

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

Python uses y if cond else x to represent a conditional expression. This means that when cond is true, the expression evaluates to y, otherwise it evaluates to x. This is equivalent to cond?y:x in C++ and Java.

Python distinguishes between lists, which are written as [1,2,3], and tuples, which are written as (1,2,3). You can change the elements of a list, but not a tuple, and in some cases the parentheses of a tuple can be omitted. tuple

There is special treatment for assignment statements. Therefore, it is possible to assign to more than one variable at the same time, for example:
>>> x, y=1,2# Assign values to x,y at the same time, final result: x=1, y=2

In particular, values of two variables can be exchanged using a form such as the following:
>>> x, y=y, x # final result: y=1, x=2

Python uses ' (single quotes) and " (double quotes) to represent strings. Unlike Perl, the Unix Shell language, or languages such as Ruby or Groovy, the two symbols serve the same purpose. Generally, if double quotes are present in a string, single quotes are used to represent the string

strings; conversely, use double quotes. If neither appears, the choice is left to personal preference. \ (backslashes) appearing in strings are interpreted as special characters, e.g., \n for a line break. An expression preceded by r instructs Python not to interpret \ that appears in the string. This style of writing is commonly used for writing regular expressions or Windows file paths.

Python supports list slices, which allows you to get part of a complete list. The types of cuts supported are str, bytes, list, tuple, etc. The syntax is... The syntax is ... [left:right] or ... [left:right:stride]. Assuming the values of the nums variable are [1, 3, 5, 7, 8, 13, 20], the following statements are true:

nums[2:5] == [5, 7, 8] cuts from an element with subscript 2 to an element with subscript 5, but does not contain an element with subscript 5.
nums[1:] == [3, 5, 7, 8, 13, 20] Cut to the last element.
nums[:-3] == [1, 3, 5, 7] Cut from the very first element all the way down to the penultimate element.
nums[:] == [1, 3, 5, 7, 8, 13, 20] Returns all elements. Changing the new list does not affect nums.
nums[1:5:2] == [3, 7] cuts from an element subscripted 1 to an element subscripted 5 but does not contain an element subscripted 5 with a step size of 2.

4. Functions

Python functions support recursion, default parameter values, and variable parameters, but not function overloading. In order to enhance the readability of the code, you can write "documentation strings" (Documentation Strings, or docstrings for short) after the function, used to explain the function's role, the type and meaning of the parameters, the type and range of the return value, and so on. You can use the built-in function help () to print out the function of the use of 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. Methods of objects

The methods of an object are the functions bound to the object. The syntax for calling an object's methods is (arguments). It is equivalent to calling (instance, arguments). When defining an object method, you must explicitly define the first argument, which is usually called self, to access the internal data of the object. Self is equivalent to the C++ and Java variable this, but we can use any other legal argument name, such as this and mine, etc. Self is not exactly the same as C++ and Java this, it can be seen as an idiomatic usage, we can pass any other legal name, such as:

class Fish:
  def eat(self, food):
    if food is not None:
      =False
class User: 
  def__init__(myself, name):
    myself. name= name
# Construct an instance of Fish:
f=Fish()
# The following two forms of invocation are equivalent:
(f,"earthworm")
("earthworm") 
u = User('username')
print(u .name)

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

6. Types

Python uses a dynamic type system. At compile time, Python does not check whether an object has a called method or property, but does not do so until runtime. So exceptions 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 adding numbers to strings.

Like other object-oriented languages, Python allows the programmer to define types. Constructing an object is simply a matter of calling the type like a function, e.g., for the Fish type defined earlier, use Fish(). Types are themselves objects of the special type type (type types are themselves type objects), and this special design allows for reflective programming of types.

Python has a rich set of built-in data types. These data types effectively reduce the length of code compared to Java and C++. The following list briefly describes the Python built-in data types (for Python ):

In addition to various data types, the Python language uses types to represent functions, modules, types themselves, methods of objects, compiled Python code, runtime information, and so on. As a result, Python is highly dynamic.

7. Mathematical operations

Python supports mathematical operations on integers and floating point numbers, using similar operators to C and Java. It also supports complex number operations and integer operations with infinite digits (which are limited by the power of the computer). Most of the math functions are in the math and cmath modules, except for the absolute value function abs(). The former is used for real number operations, while the latter is used for complex number operations. To use them you need to import them first, for example:

>>> import math
>>> print((/2))
1.0

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

Python defines the value of the remainder run a % b to lie within the open interval [0, b), which becomes (b, 0] if b is negative. This is a very common way of defining it. But it actually relies on the definition of integer division. In order for the equation: b * (a // b) + a % b = a to be constant true, the integer division run needs to take values in the negative infinitesimal direction. For example, 7 // 3 results in 2, while (-7) // 3 results in -3. This algorithm is different from many other programming languages, and it's important to note that their integer division operations take values in the direction of 0. Python allows for two comparison runners in a row, as is common in math. For example, a < b < c is equivalent to a < b and b < c. C++'s result is different from Python's, in that it first calculates a < b, obtains one of the values 0 or 1 depending on the size of the two, and then compares the result with c.

I hope that what I have said in this article will help you in Python programming.