Python 3.0 Programming Summary

Basic Grammar

By default, Python 3 source files are encoded in UTF-8, and all strings are unicode strings.

Identifier: The first character must be an alphabet or underscore. The other parts are composed of letters, numbers and underscores. They are sensitive to case.

Note: In Python, one-line comments begin with, and multi-line comments can use multiple # numbers, as well as'''and''''''.

python's most distinctive feature is that it uses indentation to represent blocks of code without braces {} and semicolons at the end of statements. The same line shows the use of semicolons (;) between multiple statements.

A backslash () can be used to implement a multi-line statement. In [], {}, or (), there is no need to use backslash ().

total = item_one + \
        item_two + \
total = ['item_one', 'item_two', 'item_three',
        'item_four', 'item_five'] 

Number types have four types: integer, Boolean, floating point and complex.
Int (integer), such as 1, has only one integer type int, which is expressed as a long integer.
bool, such as True.
float (floating point number), such as 1.23, 3E-2
complex, such as 1 + 2j, 1.1 + 2.2j

String: Single and double quotation marks use exactly the same.

You can specify a multi-line string using three quotes ('''or "").
Escape character''

Backslashes can be used to escape, and r can keep backslashes from raw string s. If r"this is a line with \n", then n will show that it is not a newline.

Cascading strings literally, such as "this", "is" and "string", is automatically converted to this is string.

Strings can be concatenated with + operators and repeated with * operators.

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

Strings in Python cannot be changed.
Python does not have a separate character type, a character is a string of length 1.

print(str * 2)             # Output string twice
print(str + 'Hello')        # Connection string
print(str[0])              # Output string first character
print(str[2:5])            # Output from the third to the fifth character
print(str[2:])             # Output all characters starting from the third
print('hello\nrunoob')      # Use backslash ()+n to escape special characters
print(r'hello\nrunoob')     # Add an r before the string to indicate that the original string will not be escaped

Unlike code indentation, blank lines serve to separate two pieces of code with different functions or meanings, facilitating the maintenance or refactoring of code in the future.

Compound statements like if, while, def, and class begin with keywords and end with a ** colon (:)**

The default output of print is newline. If you want to achieve no newline, you need to add end="" at the end of the variable:

# Non-newline output
print( x, end=" " )

Use import or from... Import to import the corresponding module
Import the whole module in the format: import some module
Import a function from a module in the form of: from some module import some function
Import multiple functions from a module in the following formats: from some module import first func, secondfunc, thirdfunc
Import all functions in a module in the form of: from some module import*

Basic data types

Variables in Python do not need to be declared. Every variable must be assigned before it is used, and the variable will be created after it is assigned.

Variables are variables. There is no type. What we call "type" is the type of object in memory that a variable refers to.

# Variables are assigned directly without declaration
counter = 100          # Integer variables
miles   = 1000.0       # Float
name    = "runoob"     # Character string
print (counter)
print (miles)
print (name)

There are six standard data types: Number (number), String (string), List (list), Tuple (tuple), Set (collection), Dictionary (dictionary).

Immutable data (3): Number (number), String (string), Tuple (tuple); Variable data (3): List (list), Dictionary (dictionary), Set (set).

Number (number): supports int, float, bool, complex (plural). There is only one integer type int, which is represented as a long integer. The built-in type() function can be used to query the object type referred to by the variable. It can also be judged by isinstance.

Delete one or more objects by using del statements

del var
del var_a, var_b

Python can assign multiple variables at the same time, such as a, b = 1, 2.
2. A variable can be assigned to different types of objects.
3. The division of a numeric value consists of two operators: / Returns a floating point number, / / Returns an integer.
4. In hybrid computing, Python converts integers into floating-point numbers.

Strings are enclosed in single quotation marks or double quotation marks, and special characters are escaped with backslash. The two indexing methods start from left to right with 0 and start from right to left with -1.

>>> print('Ru\noob')
>>> print(r'Ru\noob')

Unlike C strings, Python strings cannot be changed. Assigning values to an index location, such as word [0]='m', can lead to errors.

List (list) lists can have different types of elements, which support numbers, and strings can even contain lists (so-called nesting).

A list is a comma-separated list of elements written between square brackets [].

After the list is truncated, a new list containing the required elements is returned. The plus sign + is a list join operator and the asterisk* is a repeat operation.

Like strings, lists can be indexed and sliced; lists can be spliced using the + operator; elements in lists can be changed.

List interception can accept the third parameter, which is the step size of interception. If the third parameter is negative, it means reverse reading and is used to flip the string.

def reverseWords(input): 
    # String separators are separated into lists by spaces
    inputWords = input.split(" ") 
    # Flip string
    # Suppose the list = 1,2,3,4,  
    # list[0]=1, list[1]=2, and - 1 represents the last element list[-1]=4 (as in list[3]=4) 
    # inputWords[-1::-1] has three parameters
    # The first parameter - 1 represents the last element
    # The second parameter is empty, which means moving to the end of the list
    # The third parameter is the step size, -1 represents the reverse.
    # Recombination of strings
    output = ' '.join(inputWords) 
    return output 
if __name__ == "__main__": 
    input = 'I like runoob'
    rw = reverseWords(input) 

Tuple: Elements of tuples cannot be modified. Tuples are written in parentheses (), separated by commas. Element types in tuples can also be different. Tuples can also be indexed and sliced in the same way. Tuples can also be spliced using the + operator.

tuple = ( 'abcd', 786 , 2.23, 'runoob', 70.2  )
tinytuple = (123, 'runoob')
print (tuple)             # Output complete tuples
print (tuple[0])          # The first element of the output tuple
print (tuple[1:3])        # The output starts with the second element and goes to the third element.
print (tuple[2:])         # Output all elements starting with the third element
print (tinytuple * 2)     # Output two tuples
print (tuple + tinytuple) # Connection tuples

>>> tup[0] = 11  # Modifying tuple elements is illegal
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

tup1 = ()    # Empty tuple
tup2 = (20,) # An element that needs to be followed by a comma

Set: The basic function is to test membership and delete duplicate elements. You can use braces {} or set() functions to create collections. To create an empty collection, you must use set() instead of {}, because {} is used to create an empty dictionary.

student = {'Tom', 'Jim', 'Mary', 'Tom', 'Jack', 'Rose'}
print(student)   # Output set, duplicate elements are automatically removed
# Membership testing
if 'Rose' in student :
    print('Rose In a collection')
else :
    print('Rose Not in the collection')
# Set can perform set operations
a = set('abracadabra')
b = set('alacazam')
print(a - b)     # Difference sets of a and b
print(a | b)     # Union of a and b
print(a & b)     # Intersection of a and b
print(a ^ b)     # Elements that do not exist at the same time in a and b
//Output results:
{'Mary', 'Jim', 'Rose', 'Jack', 'Tom'}
Rose In a collection
{'b', 'a', 'c', 'r', 'd'}
{'b', 'd', 'r'}
{'l', 'r', 'a', 'c', 'z', 'm', 'b', 'd'}
{'a', 'c'}
{'l', 'r', 'z', 'm', 'b', 'd'}

Dictionary lists are ordered sets of objects and dictionaries are disordered sets of objects. The difference is that elements in a dictionary are accessed by keys. The ** dictionary is marked with {} and ** is a collection of disordered keys: values. Keys must use immutable types (math/string/tuple), and keys must be unique in the same dictionary.

dict = {}
dict['one'] = "1 - Course"
dict[2]     = "2 - tool"
tinydict = {'name': 'runoob','code':1, 'site': ''}
print (dict['one'])       # The output key is the value of'one'.
print (dict[2])           # Value of output key 2
print (tinydict)          # Output complete dictionary
print (tinydict.keys())   # Output all keys
print (tinydict.values()) # Output all values
//Output results:

1 - Course
2 - tool
{'name': 'runoob', 'code': 1, 'site': ''}
dict_keys(['name', 'code', 'site'])   //
dict_values(['runoob', 1, ''])    //list
#Constructor dict() can construct dictionary directly from the sequence of key-value pairs
>>>dict([('Runoob', 1), ('Google', 2), ('Taobao', 3)])
{'Taobao': 3, 'Runoob': 1, 'Google': 2}
>>> {x: x**2 for x in (2, 4, 6)}
{2: 4, 4: 16, 6: 36}
>>> dict(Runoob=1, Google=2, Taobao=3)
{'Runoob': 1, 'Google': 2, 'Taobao': 3}

Data Type Conversion

Conversion of data types requires only the use of data types as function names. The function returns a new object that represents the value of the transformation.

long(x, base=10)  #Convert a number or string to a long integer, base decimal default decimal
>>> long(1)
>>> long('123')

int(x, base=10)  #Converts a string or number to an integer.

>>>complex(1, 2)   #Create a plural
(1 + 2j)

float(x)  #Converting x to a floating point number
str(x)    #Converting object x to string

eval(str)   #Used to calculate a valid Python expression in a string and return an object
>>>x = 7
>>> eval( '3 * x' )

tuple(s)   #Convert sequence s to a tuple

list(s)  #	Convert sequence s to a list

set(s)   #Converting to Variable Sets

dict(d)   #Create a dictionary. d must be a sequence tuple.

chr(x)   #Converting an integer to a character
unichr(x)   #Converting an integer to a Unicode character
ord(x)     #Converting a character to its integer value

hex(x)    #Converting an integer to a hexadecimal string
oct(x)     #Converting an integer to an octal string

repr(x)    #Converting object x to expression string
>>> dict = {'runoob': '', 'google': ''};
>>> repr(dict)
"{'google': '', 'runoob': ''}"

Python operator

// Divide-Return Integer Part of Quotient (Divide Down)
Arithmetic operator, comparison operator, assignment operator (power assignment operator c = c** a), bitwise operator, logical operator (and, or, not), member operator (in, not in), identity operator (is, is not),

Keywords: Python Google Asterisk

Added by vandalite on Fri, 23 Aug 2019 10:19:18 +0300