Python3 basics-knowledge points and python3

Source: Internet
Author: User
Tags bitwise operators integer division

Python3 basics-knowledge points and python3

1. Basic syntax

Encoding, identifier, reserved word, comment, line and indent...

2. Variable type

(1) Python3 has six standard data types:

  • Numbers (number)

The numeric data type is used to store numeric values.

Unchangeable Data Types

Can be subdivided into int, float, bool, complex (plural), no long in python2

  • String (String)

A string is enclosed by single quotation marks (') or double quotation marks ("), and special characters are escaped using a backslash (\).

Variable [header Subscript: tail subscript]

The backslash can be used for escape, and r can be used to prevent the backslash from being escaped.

Strings can be connected together using the + operator, which is repeated using the * operator.

There are two indexing methods for strings in Python: 0 from left to right and-1 from right to left.

The strings in Python cannot be changed.

  • List)

The list can implement the data structure of most collection classes. The types of elements in the list can be different. It supports numbers, strings, and even lists (so-called nesting ).

A list is a list of elements written between square brackets ([]) and separated by commas.

Like a string, the list can also be indexed and intercepted. After the list is intercepted, a new list containing the required elements is returned.

Syntax format of list truncation: Variable [header Subscript: tail subscript]. The index value starts with 0 and-1 is the starting position from the end.

  • Tuple (tuples)

The tuple is similar to the list, except that the elements of the tuples cannot be modified.

The tuples are written in parentheses (()Are separated by commas.

The element types in the tuples can also be different.

  • Sets)

A set is a sequence of unordered and non-repeating elements.

The basic function is to test the member relationship and delete duplicate elements.

Braces can be used.{}OrSet ()Function to create a set. Note: To create an empty set, useSet ()Instead{}Because{}Is used to create an empty dictionary.

Creation format: parame = {value01, value02,...} or set (value)

  • Dictionary)

A list is a combination of ordered objects, and a dictionary is a collection of unordered objects. The difference between the two is that the elements in the dictionary are accessed by keys, rather than by offset.

A dictionary is a ing type. It is identified by "{}" and is unordered.Key: value)Pair set

Key must use an unchangeable type

In the same dictionary, the key must be unique.

 

(2) Data Type Conversion

Common functions

Description

Int (x [, base])

Converts x to an integer.

Float (x)

Convert x to a floating point number.

Complex (real [, imag])

Create a plural number

Str (x)

Convert object x to a string

Repr (x)

Convert object x to an expression string

Eval (str)

Used to calculate a valid Python expression in a string and return an object

Tuple (s)

Converts the sequence s into a single tuples.

List (s)

Converts sequence s to a list.

Set (s)

Convert to a variable set

Dict (d)

Create a dictionary. D must be a sequence (key, value) tuples.

Frozenset (s)

Convert to an unchangeable set

Chr (x)

Converts an integer to a character.

Ord (x)

Converts a character to an integer.

Hex (x)

Converts an integer to a hexadecimal string.

Oct (x)

Converts an integer to an octal string.

 

3. Notes

L single line comment#Start

L multiple-line comments use three single quotes'''Or three double quotes"""Enclose comments

 

4. Operators

(1) Arithmetic Operators: +,-, *,/, %, and ** (power-returns the Power y of x, for example, a ** B is the power 21 of 10), // (take the integer part of the integer division-return operator );

(2) Comparison operators: = ,! =,>, <,> =, <=

(3) assignment operators: =, + =,-=, * =,/=, % =, ** = (power assignment operator), // =

(4) bitwise operators: &, |, ^ ,~ , <,>

(5) logical operators: and, or, not

(6) member OPERATOR: in (returns True if a value is found in the specified sequence; otherwise, returns False), not in (opposite to in)

(7) Identity OPERATOR: is (is used to determine whether two identifiers reference an object) and is not (is not used to determine whether two identifiers reference different objects)

(8) operator priority (from high to low ):

Operator

Description

**

Index (highest priority)

~ +-

Flip by bit, one-dollar plus sign and minus sign (the last two methods are named + @ and -@)

*/% //

Multiplication, division, modulo and Division

+-

Addition and subtraction

>>< <

Right Shift, Left Shift Operator

&

AND'

^ |

Bitwise operators

<=<>>=

Comparison Operators

<>==! =

Equal to operator

= % =/= // =-= + = * = ** =

Value assignment operator

Is not

Identity Operators

In not in

Member Operators

Not or and

Logical operators

 

5. condition Control

If statement:

  

 1 if condition_1:    2  3      statement_block_1  4  5   elif condition_2:    6  7     statement_block_2  8  9   else:     10 11     statement_block_3
View Code

 

 

6. Loop statements

(1) while

While judgment condition: Statement else: statement_block
View Code

 

Note: while... When the condition is false, else executes the statement block of else.

 

(2)

for <variable> in <sequence>:       <statements>  else:           <statements>
View Code

 

 

 

(3) break, continue, and pass 

The break statement can jump out of the for and while LOOP bodies. If you terminate a for or while LOOP, no corresponding loop else block will be executed.

The continue statement is used to tell Python to skip the remaining statements in the current loop block and continue the next loop.

Pass does not do anything. It is generally used as a placeholder statement.

 

7. Functions

(1) Function Definition:

Def function name (parameter list): function body
View Code

 

 

(2) parameter transfer:

Actually, variable types (list, dict) and variable types (strings, tuples, numbers, and Sets) are passed ).

 

(3) parameter type:

1) VAR_POSITIONAL

When the parameter type is VAR_POSITIONAL, that is, * The args parameter (receiving a tuple) can only be passed through the position, for example:

Def func_a (* args): print (args) # pass the value func_a ('Alex ', 'timeflow') by position ')
View Code

 

2) VAR_KEYWORD

The parameter type is VAR_KEYWORD, that is, ** the kwargs parameter (which receives a dict) can only be passed through keywords, for example:

Def func_ B (** kwargs): print (kwargs) # pass the value func_ B through the keyword (a = 1, B = 2)
View Code

 

3) POSITIONAL_OR_KEYWORD

There is no VAR_POSITIONAL type parameter before this parameter. You can pass the value by position or keyword, for example:

Def func_c (args): print (args) # pass the value func_c by position (1) # pass the value func_c by keyword (args = 1)
View Code

 

4) KEYWORD_ONLY

A VAR_POSITIONAL type parameter exists before this parameter. Values can only be passed through keywords, for example:

Def func_d (* args, age, sex): print (args, age, sex) # Only values func_d ('Alex ', age = 24, sex = 'man ')
View Code

 

 

5) POSITIONAL_ONLY

Parameters that can only be passed by location. Python does not have a clear syntax to define a function parameter that can only pass values by location, but many built-in and extended module functions will accept this type of parameter.

 

(4) Anonymous Functions

Lambda can be used to create anonymous functions.

Lambda function Syntax:

Lambda [arg1 [, arg2,... argn]: expression

Example:

# Lambdasum = lambda arg1, arg2: arg1 + arg2; # Call the sum function print ("the sum value is:", sum (10, 20 ))
View Code

 

 

(5) variables

1) Scope

U L (Local) Local scope

In the functions outside the closure function of u E (Enclosing ),

U G (Global) Global SCOPE

U B (Built-in) built-in Scope

Search by L-> E-> G-> B rules.

2) global and nonlocal keywords

When the internal scope wants to modify the variables of the external scope, the global and nonlocal keywords can be used:

L modify the global variable, global

L modify the variables in the nested scope (enclosing scope, outer non-global scope) and use the nonlocal keyword

 

 

8. file read/write

Common read/write modes:

Mode

R

R +

W

W +

A

A +

Read

+

+

 

+

 

+

Write

 

+

+

+

+

+

Create

 

 

+

+

+

+

Overwrite

 

 

+

+

 

 

Pointer at start

+

+

+

+

 

 

Pointer at the end

 

 

 

 

+

+

 

9. Object-oriented

(1) Class Definition

class ClassName:          <statement-1>                  .                 .        <statement-N>
View Code

 

 

(2) Inheritance

class DerivedClassName(Base1, Base2, Base3):           <statement-1>                   .                .            <statement-N>     
View Code

 

(3) class attributes and Methods

1) Private attributes of the class

_ Private_attrs: It starts with two underscores and declares that this attribute is private and cannot be used outside the class or accessed directly. Self. _ private_attrs is used in internal methods of the class.

2) Class Method

Inside the class, use the def keyword to define a method. Unlike the general function definition, the class method must contain the parameter self, which is the first parameter. self represents the instance of the class. The name of self is not specified or can use this, but it is best to use self as agreed.

3) Private method of the class

_ Private_method: It starts with two underscores and declares that this method is a private method. It can only be called within the class and cannot be called outside the class. Self. _ private_methods.

 

(4) Class-specific methods

U_ Init __:Constructor called when an object is generated

U_ Del __:Destructor used to release objects

U_ Repr __:Print, convert

U_ Setitem __:Assign values by index

U_ Getitem __:Retrieve value by index

U_ Len __:Get Length

U_ Cmp __:Comparison

U_ Call __:Function call

U_ Add __:Addition operation

U_ Sub __:Subtraction

U_ Mul __:Multiplication

U_ Div __:Division operation

U_ Mod __:Remainder operation

U_ Pow __:Multiplication party

Operators can be overloaded.

 

10. Standard Library

Library

Description

Operating System Interface

The OS module provides a number of functions associated with the operating system.

File wildcard

The glob module provides a function to generate a file list from the directory wildcard search:

Command Line Parameters

Common tool scripts often call command line parameters. These command line parameters are stored in the argv variable of the sys module as a linked list.

Error output redirection and program termination

Sys also has stdin, stdout, and stderr attributes, which can be used to display warnings and error messages even when stdout is redirected.

String Regular Expression matching

The re module provides a regular expression tool for advanced string processing.

Mathematics

The math module provides access to the underlying C function library for floating-point operations. random provides a random number generation tool.

Network

Urllib. request, smtplib

Date and Time

Datetime

Data Compression

Zlib, gzip, bz2, zipfile, and tarfile

...

...

 

11. Multithreading

In Python3, the thread module has been deprecated. Currently, the threading module can be used instead. However, for compatibility purposes, Python3 renames the thread as "_ thread ".

(1) There are two ways to create a thread:

1) Call the start_new_thread () function in the _ thread module to generate a new thread.

_ Thread. start_new_thread (function, args [, kwargs]):

Parameter description:

U function-thread function.

U args-the parameter passed to the thread function. It must be of the tuple type.

U kwargs-optional parameter.

2) threading

Inherit from threading. Thread to create a new subclass, and call the start () method to start a new Thread after instantiation, that is, it calls the Thread's run () method;

 

(2) thread synchronization

The Lock and Rlock of the Thread object can be used for simple Thread synchronization. Both objects have the acquire and release methods. For data that requires only one Thread to operate at a time, you can place the operations between the acquire and release methods.

 

 

Main reference: python tutorial

  

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.