Python first week basic syntax and concepts

Source: Internet
Author: User
Tags arithmetic operators bitwise bitwise operators logical operators new set stack trace python script

Two ways to execute Python commands

1. Execute in interactive mode

After the Python program is installed, the command line of Windows or Linux, Mac terminal interface input python command to enter the Python interactive mode, enter the Python statement in this mode, press ENTER to return the execution result. Typically used for debugging.

2. Script execution

Write the Python statement in the. py file, and then use the format Python script.py to execute the Python script, or add executable permissions to the script on the Linux platform, using absolute or relative paths to execute the script.


Execution flow of Python programs

The. py file We write is called a Python script, and when we execute a python script using the python command, the Python interpreter first translates the statements in the Python script into a set of bytecode commands . stored in the __pycache__ directory under the same directory as the script, in the file ending with. PYc , and then sending the Python bytecode to the PVM (Python virtual Machine,python vm) , Executed by PVM and returns the final result. PVM is part of the Python program.

Basic Concepts of Python programs:

1. The program is composed of modules

2. Module contains statements

3. Statement contains an expression

4. Expression creation and processing of an object


I. Built-in objects

Numbers, strings, lists, dictionaries, tuples, files, collections, other types (Type,none, BOOL), Programming unit types (functions, modules, classes), implementation-related types (compiled code stack trace traceback).

Features of built-in objects:

    • Built-in objects make programs easier to write, and for simple tasks, you can use built-in types to do your work.

    • Built-in objects are extended components that can be used to assemble more complex data types using built-in data types.

    • Built-in objects are more efficient than custom data structures, and built-in objects are generally implemented in C language and are more efficient.

    • Built-in objects are part of the language standard, so compatibility with different platforms is better.


common built-in objects :

1. Digital

The number types supported by Python are integers, floating-point numbers, complex numbers, octal numbers, fixed-precision decimal numbers, hexadecimal numbers, rational fractions with numerator and denominator, and so on. Some specific numbers may require support for specific modules or third-party libraries.

Common modules in numbers math, random, the former used to provide constants such as PI, E, etc., which are common in numbers, which are used to provide random number generators and random number selectors.


2. String

Used to record text information, and then as a subset of the sequence in Python, supports common operations for sequences such as Len () functions, indexes, shards, and so on.

An important characteristic of a string--immutability , cannot be changed in place after creation .

Some common ways to bring strings: Find (), replace (), split (), Rstrip (), format operations, and so on.

The string starting with R represents the string itself, with no special meaning, and the escape character does not work in such a string.

The string that starts with U represents a Unicode string, python3.x supports Unicode strings by default, and you do not need to add U.

The RE module is used to handle pattern matching of strings.


3. List

A list is the most common sequence provided by the language, an ordered set of positions related to an arbitrary type of object, no fixed size, variable size, and can be called according to the index to copy the elements, and to support various lists of methods.

Supports common sequence operations such as indexes, shards, and so on.

The list comes with methods append (), sort (), reverse (), pop (), and so on.


4. Dictionaries

A dictionary is not a sequence, but a mapping that is stored by a key and mapped to a value. The keys of a dictionary are unique, and the values for the keys can be multiple objects, such as strings, numbers, lists, collections, or even the dictionary itself.


5. Tuples

Equivalent to an immutable list, but also a sequence, but with immutability. Blending and nesting of multiple elements is also supported.


6. Documents

In Python, a file is treated as an object. The file object is the primary interface of Python code to external files on your computer. No specific constant syntax is created for the file. To create a file object, you need to call the Open function that handles the file object and pass it a file name and a document processing pattern string .

The methods supported by the file object read, ReadLine, ReadLines, write, Writelines, Seek, close, and so on.

Additional class file Tools: Pipe, FIFO queue (FIFO), socket (socket), access to files through keys, object persistence, descriptor-based files, relational databases, and object-oriented database interfaces.


7. Collection

is not a map or a sequence, it is an unordered collection of immutable objects. Create by calling the built-in function set function, or by using the new set constants and expressions in Python3.0 to support general mathematical set operations, which are more like keys to a dictionary without values.

X = set (' Spam ')

Y = {' h ', ' A ', ' m '}

These are the two ways to create a collection.

Many of these objects support object-specific methods, which are explained when the object is introduced separately. In the Python command line interface, there are several commands that can be used to view the object's Help information, respectively:

    • The Dir (obj) method can see all the properties of an object

    • The Ord (obj) method to view the ASCII encoding of an object

    • Assistance (obj) or help (Obj.fn) to view help information for an object or an object method.

These are the Python core object types and some simple things you can do about them.


Ii. Dynamic Type

1. Constants/Variables

    • Literal constants

    • Variable, which is a pointer to a piece of allocated memory.

      • The creation of a variable, which is created when assigning a value to the variable

      • The type of the variable, the variable has no type, and the type is the property of the object associated with the variable. When a pointer to a variable points to a different object, it is associated to a different type of object.

      • Naming rules for variables

      1. Can only contain letters, numbers, and underscores

      2. Can only start with a letter or an underscore

      3. Cannot be a reserved word for the Python interpreter

garbage collection of objects : When no pointer points to an object, the object's reference counter is zeroed, and the memory space occupied by the object is placed in the free memory space, waiting for the object to be used later. The advantage of this mechanism is that you do not have to consider freeing up memory space.

object : Changing an immutable object, such as a number or string, to a variable, such as a number +1, or a new string, when actually executing a new numeric object or String object, The pointer to the variable is then re-directed to the new object.

shared references : When a mutable object is assigned to a variable, changing the variable object does not change the pointer to the variable. So when two of the same variables point to the same Mutable object, one of the variables modifies the object's operation, and the value of the other variable changes. For example:

>>>l1=[1,2,3]

>>>l2=l1

>>>l2[0]=24

>>>l2

[24,2,3]

>>>l1

[24,2,3]

You should use the copy (copy and Deepcopy methods)If you do not want the L1 to change because L2 changes the value of the list. The knowledge point is mentioned in the list.


is and ' = = ', with only two pointers pointing to the same piece of memory, two variables are the is relationship, not pointing to the same piece of memory, but the two variables point to the same object, at which point the two variables are the ' = = ' relationship.

Supplemental content: The relationship between variables and objects

    • A variable is a system table element that has a connection to an object, which is the space to hold the pointer.

    • object is a piece of memory allocated by the system, there is enough space to represent the value they represent, an object has two standard header information, a type identifier to identify the type of object, a reference counter , to determine whether this object can be recycled

    • A reference is an automatically formed pointer from a variable to an object s


2. Operators/expressions

Arithmetic operators: + 、-、 *,/(different meanings in py2 and py3),//,%, * *;

comparison operator:>,<,=,!=,>=,<=,==;

Logical operators: And, OR, not

    • The member participating in the operation can only be of type bool, or it can be implicitly converted to a type of type bool (0,1);

    • And two is positive, two negative, one positive and one negative are negative

    • Or two is positive, both negative negative, one positive and one negative are negative

    • not be negative, negative positive

    • short-circuit operation : Always left-to-right calculation, once the final value of the expression can be determined, will immediately stop the calculation and return. That is, when the and operator is used, the left value is negative to end the operation immediately, and when the OR operator is used, the operation is terminated immediately when the left side is positive. When you need an expression on either side of an operator in this case, you can replace the expression on either side with a temporary variable.

Bitwise operators:

    • Bin (num) returns the binary representation of NUM

    • & (Bitwise AND), | (bitwise OR), ^ (bitwise XOR, same as 1 or 0 for 0, not both 1), ~ (Bitwise reverse ~x=-(x+1))

    • >>,<< (left and right shift operators)

Other operators:

    • Assignment operator =

    • Member operator in (contents of the built-in data structure)

    • Identity operator is, is not (object-oriented content)

Precedence of operators: operators are evaluated based on precedence.

    • Arithmetic operators above comparison operators

    • Comparison operators are higher than logical operators

Expressions are formulas that consist of constants/variables and operators.


3. Program Control Structure

Sequential structure: The combination of expressions executed from top to bottom;

Branching structure:

    • Single branch: If Condition:block

    • Dual branch: If....else ....

    • Multi-branch: If...elif...else

There is always only one branch in the branching structure that will be executed.

Loop structure:

    • for element in Iterator:block

    • While Condition:block

    • Break, Continue,break is used to end the loop prematurely, and continue is used to skip the remainder of the current loop.

* Never modify an iterative object in the loop body.

For _ in range (0,3) #表示不使用 _ This variable, just three cycles.

Nested structure: If, for, while and many other structures combined structure.

0, empty built-in structure, none bool structure is false, non-0, non-empty built-in structure are true


Knowledge points in this section:

1. Know the built-in types common to Python and the methods commonly used by these built-in types (len, index, Shard, and so on).

2. Learn about the rules for creating variables in Python, and the relationships between variables and objects when they refer to different objects. The following points are included:

    • Variable naming rules

    • Variable pointer changes after changing an object when the variables refer to immutable objects

    • When a variable refers to a Mutable object, the relationship between the variable and the object is changed after the object.

3. Be familiar with simple operator operations.

4. Be familiar with the basic control structure in Python.


This article is from the "No Flying World" blog, please be sure to keep this source http://hf1208.blog.51cto.com/8957433/1881621

Python first week basic syntax and concepts

Related Article

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.