Python review series: Python Basics

Keywords: Python Back-end

Python basics (1)

(1) Introduction to Python language

1. Overview of Python language

python is a cross-platform, open source, free, interpretive computer programming language.

2. Python Language Features

The grammar is simple, clear and easy to learn and master.

python is a cross-platform, open source, free, interpretive advanced dynamic programming language.

python supports command programming, function programming, object-oriented programming, and a large number of expansion libraries.

Enforce space indentation to make code readable.

3. Version of Python

There are currently 2.x and 3.x versions of python that are incompatible with each other.

The Python 2.x series will be abandoned for maintenance and updates by the end of the year 2020.

4. Python programming specification

(1) Indentation

Class definition, function definition, selection structure, loop structure, with block, colon at end of line indicates start of indentation.

The python program relies on indentation of code blocks to represent the logical relationship between code, and the end of indentation means the end of a code block.

The indentation of blocks of code at the same level must be the same.

Generally speaking, basic indentation units are 4 spaces.

(2) Each import statement can only import one module, preferably in the order of standard library, expanded library and custom library.

(3) Add a blank run after each class, function definition, and a complete function code, add a space on each side of the operator, and add a space after the comma.

(4) Try not to write too long sentences. If the statement is too long, consider splitting it into several shorter statements to ensure that the code is readable. If the statement is really too long, the code is readable. If the statement is really too long to exceed the screen width, it is best to use the line continuation character'\', or parentheses to enclose multiple lines of code to represent a statement.

(5) Although Python operators have clear priorities, parentheses are recommended for complex expressions to make membership and order of operations clearer and clearer.

(6) Comments

Start with the symbol #to indicate that the content following this line #is a comment.

Content contained between a pair of three quotes''...''or''...'' that does not belong to any statement is considered a comment by the interpreter.

(2) Basic Python grammar

1. Import and use of Libraries

Objects in the python standard and extension libraries must be imported before they can be used. There are three ways to import.

import module name [as alias]

This method can import multiple modules at a time. However, when using classes, methods, functions, constants in a module, you need to precede it with the module name.

import math
print(math.pow(2, 3)) 
import math as ma
print(ma.pow(2, 3))

from module name import*

This method imports everything in a module at a time, such as a function. You do not need to add a prefix to the module name when using it. Poor readability.

from math import*

from module name import object name [as alias]

This method imports the specified content in one module at a time, such as a function. There is no need to prefix the module name when calling.

from math import pow,pi

2. Common built-in objects for Python

Everything that is handled in python is an object, an integer, a real number, a complex number, a string, a list, a tuple, a dictionary, a collection is an object, and functions such as zip, map, enumerate, filter return objects as well as functions and classes.

python has built-in objects, standard library objects, and extended library objects, where built-in objects can be used directly.

Non-built-in objects require import modules to be used, such as sine function sin(x), random number generation function random(), and so on.

2.1 Constants and Variables

In Python, variable names and their types are not required to be declared beforehand, but directly assigned to create various types of object variables. This applies to any type of object in Python.

The assignment statement is executed by first calculating the value of the expression to the right of the equal sign, then finding a location in memory to store the value, and finally creating a variable and pointing to the memory address.

Variables in Python do not store values directly, but instead store the value's memory address or reference, which is why variable types can be changed at any time.

Python is a strongly typed programming language, and the Python interpreter automatically infers variable types based on assignments or operations.

Python is also a dynamic type language, and the type of variable can change at any time.

# View variable types
x = 4
x = 'hello word'
x = [1,2,3]

# Test whether an object is an instance of a type
print(isinstance(3, int))
print(isinstance('hello word',str))

<class 'int'>
<class 'str'>
<class 'list'>

When defining variable names, you need to be aware of the following issues:

Variable names must start with a letter or an underscore, but variables that start with an underscore have a special meaning in Python.

Variable names cannot have spaces or punctuation marks (brackets, quotes, commas, slashes, backslashes, colons, periods, question marks, and so on).

You cannot use keywords as variable names. You can use print(keyword.kwlist) to view all Python keywords after importing the keyword module.

Variable names are case sensitive, for example, student and student are different variables.

It is not recommended to use system-built module, type or function names, and imported module and member names as variable names, which will change their type and meaning.

2.2 digits

In Python, the built-in number types are integer, real, and complex.

In addition to the common decimal integers, integer types include:

Binary. Beginning with 0b, each can only be 0 or 1.

Octal number system. Beginning with 0o, each digit can only be one of the eight numbers 0, 1, 2, 3, 4, 5, 6, 7.

Hexadecimal. Starting with 0x, each bit can only B e one of 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a, b, c, d, e, f.

python supports any large number (subject to memory size limitations)

print(99999 ** 99)


Due to the accuracy problem, there may be some error in real number operation, so we should try to avoid the direct equality test between real numbers, but whether the absolute value of the difference between the two is small enough is the basis for the equality of the two real numbers.

print(0.3-0.2==0.1)  # False
print(abs(0.4-0.1 - 0.3) < 1e-6) # True

Implicit type conversions occur when the arithmetic expression of a number is evaluated. Complex numbers become complex if they exist, real numbers become real if they do not exist, and no type conversions occur if they are all integers.

x = 3 + 4j                 #Use J or J to represent the imaginary part of a complex number
y = 5 + 6j
print(x + y)               #Supports addition, subtraction, multiplication, division and power between complex numbers
print(abs(x))              #The built-in function abs() can be used to calculate the modulus of a complex number
print(x.imag)              #imaginary part
print(x.real)              #real part
print(x.conjugate())       #Conjugate Complex Numbers


2.3 String

In Python, there is no concept of character constants and variables, only string-type constants and variables, and a single character is a string. Use single, double, three single, and three double quotes as delimiters to represent strings, and different delimiters can be nested within each other.

Python 3.x fully supports Chinese. Chinese and English letters are treated as one character, and even Chinese can be used as variable names.

In addition to supporting the use of plus-sign operators to connect strings, Python strings provide a number of methods to support formatting, finding, replacing, typesetting, and so on.

2.4 List tuple dictionary collection

x_list = [1, 2, 3]                 #Create List Object
x_tuple = (1, 2, 3)                #Create tuple object
x_dict = {'a': 97, 'b': 98, 'c': 99}  #Create Dictionary Object
x_set = {1, 2, 3}                  #Create Collection Object
print(x_list[1])                   #Use subscripts to access elements at specified locations
print(x_tuple[1])                  #Tuples also support the use of serial numbers as Subscripts
print(x_dict['a'])                 #The subscript of a dictionary object is a key
print(3 in x_set)                  #Member Test


2.5 Python Operators and Expressions

Arithmetic Operators
print([1, 2, 3] + [4, 5, 6])          # Join two lists [1, 2, 3, 4, 5, 6]
print((1, 2, 3) + (4,))               # Connect two tuples (1, 2, 3, 4)
print('abcd' + '1234')                # Connect two strings abcd1234
# print('A' + 1)                      # Adding characters to numbers is not supported, throwing an exception
print(True + 3)                       # Python internally treats True as 1 and 4
print(False + 3)                      # Treat False as 0 with 3

print(True * 3)                       # 3
print(False * 3)                      # 0
print([1, 2, 3] * 3)                  # [1, 2, 3, 1, 2, 3, 1, 2, 3]
print((1, 2, 3) * 3)                  # (1, 2, 3, 1, 2, 3, 1, 2, 3)
print('abc' * 3)                      # abcabcabc

print(3 / 2)                          # Division 1.5 Mathematically
print(15 // 4) #If both operands are integers, the result is integer 3
print(15.0 // 4) #If there is a real number in the operand, the result is an integer value of 3.0 in the form of a real number
print(-15//4) #Round Down-4

print(789 % 23)                       # Remaining 7
print(123.45 % 3.2)                   # Remainder operations can be performed on real numbers, with attention to accuracy issues 1.8499999999996
print('%c, %d' % (65, 65))            # Format 65 as character and integer A, 65 respectively
print('%f,%s' % (65, 65))             # Format 65 as real number and string 65.000000,65 respectively

print(3 ** 2)                         # 2nd power of 3, equivalent to pow(3, 2) 9
print(pow(3, 2, 8))                   # Equivalent to (3**2)%8 1
print(9 ** 0.5)                       # 0.5 power of 9, square root 3.0
print((-9) ** 0.5)                    # The square root of a negative number can be calculated (1.8369701987210297e-16+3j)
Relational Operators
print(1 < 3 < 5)                    # Equivalent to 1 < 3 and 3 < 5 True
print(3 < 5 > 2)                    # True
print(1 > 6 < 8)                    # False
print(1 > 6 < math.sqrt(9))         # False with lazy evaluation or logical short circuit
print(1 < 6 < math.sqrt(9))         # The math module has not been imported, throwing an exception NameError: name'math'is not defined
import math
print(1 < 6 < math.sqrt(9))         # False

print('Hello' > 'world')              #Compare string size False
print([1, 2, 3] < [1, 2, 4])          #Compare List Size True
# print('Hello' > 3)                  #Strings and numbers cannot be compared TypeError: unorderable types: str() > int()
print({1, 2, 3} < {1, 2, 3, 4})       #Test for subset True
print({1, 2, 3} == {3, 2, 1})         #Test whether two sets are equal True
print({1, 2, 4} > {1, 2, 3})          #Inclusion test False between collections
print({1, 2, 4} < {1, 2, 3})          #False
print({1, 2, 4} == {1, 2, 3})         #False
Member Test Operator in
print(3 in [1, 2, 3])                # Test whether 3 exists in True in list [1, 2, 3]
print(5 in range(1, 10, 1))          # range() is the built-in function True used to generate a specified range number
print('abc' in 'abcdefg')            # Substring Test True
for i in (3, 5, 7):                  # Loop, members traverse 3 5 	 7	
    print(i, end='\t')
Set operators
print({1, 2, 3} | {3, 4, 5})          # Union, automatically removes duplicate elements {1, 2, 3, 4, 5}
print({1, 2, 3} & {3, 4, 5})          # Intersection {3}
print({1, 2, 3} ^ {3, 4, 5})          # Symmetric difference set {1, 2, 4, 5}
print({1, 2, 3} - {3, 4, 5})          # Difference set
Logical operators
print(3>5 and a>3)              # Notice that the variable a False is not defined at this time
# print(3>5 or a>3 )              # The value of 3>5 is False, so the following expression needs to be evaluated: name'a'is not defined
print(3<5 or a>3 )              # The value of 3 < 5 is True, and the following expression True does not need to be evaluated
print(3 and 5)                  # The value of the last evaluated expression as the value of the entire expression 5
print(3 and 5>2)                # True
print(3 not in [1, 2, 3])       # Logical non-operation not False
print(3 is not 5)               # not can only be calculated as True or one of False s True
print(not 3)                    # False
print(not 0)                    # True

Logical operators and, or, and not are often used to join conditional expressions to form more complex conditional expressions, and they are characterized by lazy evaluation or logical short-circuit. When connecting multiple expressions, only the values that must be calculated are calculated.

Operators and or do not necessarily return True or False, but instead get the value of the last evaluated expression, but operator not does return True or False.

Python also has a number of composite assignment operators, such as assignment operators = and +=, -=, *=, /=, /=, **=, |=, ^=.

Python does not support ++ and - operators. Although they may seem to work in form at times, they actually have different meanings. Be aware of the differences between Python and other languages.

i = 3
print(++i)                            #Exactly 3
print(+(+3))                          #Equivalent to ++ i 3
print(i++)                            #Python does not support ++ operators, syntax error SyntaxError: invalid syntax
print(--i)                            #Negative minus plus, equivalent to - (-i) 3
print(---i)                           #Equivalent to - (-(-i))-3
print(i--)                            #Python does not support--operator, syntax error SyntaxError: invalid syntax

3. Common Python built-in functions

The built-in functions bin(), oct(), and hex() are used to convert integers to binary, octal, and hexadecimal forms, all requiring that the parameters be integers.

The built-in function float() is used to convert other types of data to real numbers, and complex() can be used to generate complex numbers.

_ord() and chr() are opposite functions, ord() returns the Unicode code code of a single character, chr() returns the character corresponding to the Unicode code code, and str() converts any type of parameter directly to a string.

>>> ord('a')      #View Unicode encoding for specified characters


>>> chr(65)      #Returns the character corresponding to the number 65


>>> chr(ord('A')+1)  #Python does not allow addition between strings and numbers


>>> chr(ord('country')+1)  #Support Chinese


>>> ord('Dong')     #This usage only applies to Python 3.x


list(), tuple(), dict(), set() are used to convert other types of data into lists, tuples, dictionaries, collections, or to create empty lists, empty tuples, empty dictionaries, and empty collections.

>>> list(range(5))        #Convert range object to list

[0, 1, 2, 3, 4]

>>> tuple(_)           #An underscore indicates the last correct output

(0, 1, 2, 3, 4)

>>> dict(zip('1234', 'abcde'))  #Create Dictionary

{'4': 'd', '2': 'b', '3': 'c', '1': 'a'}

>>> set('1112234')        #Create variable sets to automatically remove duplicates

{'4', '2', '3', '1'}

Built-in function types () and isinstance() can be used to determine data types, and are often used to check function parameters to avoid incorrect parameter types causing functions to crash or return unexpected results.

The built-in function eval() is used to calculate the value of a string and, in some cases, to implement the function of type conversion.

>>> eval('3+5')


>>> eval('9')         #Converting a Number String to a Number


>>> eval('09')         #Throw an exception, numbers starting with 0 are not allowed

SyntaxError: invalid token

>>> int('09')         #This conversion is possible


>>> list(str([1, 2, 3, 4]))  #Each character in the string becomes an element in the list

['[', '1', ',', ' ', '2', ',', ' ', '3', ',', ' ', '4', ']']

eval(str([1, 2, 3, 4]))  #String evaluation

[1, 2, 3, 4]

The three built-in functions max(), min(), sum() are used to calculate the maximum, minimum, and sum of all elements in a list, tuple, or other iterative object containing a finite number of elements.

The sum() default (which can be changed by the start parameter) supports a sequence of numeric elements or an Iterable object, while max() and min() require comparable sizes between elements in a sequence or an Iterable object.

The functions max() and min() also support default parameters and key parameters, where the default parameter specifies the maximum or minimum value returned by default when the Iterable object is empty, and the key parameter specifies the basis or rule for the comparison size, which can be a function or a lambda expression.

>>> max(['2', '111'])        #Do not specify a collation


>>> max(['2', '111'], key=len)   #Returns the longest string


>>> print(max([], default=None))  #Maximum empty list returns null value None


input() and print() are Python's basic input and output functions that receive user keyboard input and output data to a standard console or specified file object in a specified format. Regardless of what the user enters, input() always returns a string treatment, and when necessary, it can use built-in functions int(), float(), or eval() to type the user's input.

The built-in function print() is used to output information to a standard console or to a specified file in the syntax:

print(value1, value2, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

The sep parameter is preceded by what you want to output (there can be multiple).

The sep parameter specifies the separator between the data, defaulting to a space.

The end parameter specifies what characters to output after the data has been output.

>>> print(1, 3, 5, 7, sep='\t')    #Modify Default Delimiter

1 3 5 7

>>> for i in range(10):        #Modify the end parameter so that no line breaks occur after each output

  print(i, end=' ')

0 1 2 3 4 5 6 7 8 9 

sorted() sorts lists, tuples, dictionaries, collections, or other iterative objects and returns a new list.

reversed() flips (first-end exchange) an iterative object (except the generator object and similar objects such as zip, map, filter, enumerate with lazy evaluation) and returns an iterative reversed object.

>>> x = list(range(11))

>>> import random

>>> random.shuffle(x)           #Disrupt order

>>> x

[2, 4, 0, 6, 10, 7, 8, 3, 9, 1, 5]

>>> sorted(x)               #Sort by default rules

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

>>> sorted(x, key=lambda item:len(str(item)), reverse=True) #Sort descending by length after converting to string

[10, 2, 4, 0, 6, 7, 8, 3, 9, 1, 5]

>>> sorted(x, key=str)           #Sort in ascending order by size after conversion to string

[0, 1, 10, 2, 3, 4, 5, 6, 7, 8, 9]

>>> x = ['aaaa', 'bc', 'd', 'b', 'ba']
>>> sorted(x, key=lambda item: (len(item), item)) #Sort by length first, normal sort with the same length
['b', 'd', 'ba', 'bc', 'aaaa']
>>> reversed(x)                         #Reverse order, returns reversed object
<list_reverseiterator object at 0x0000000003089E48>
>>> list(reversed(x))                   #The reversed object is iterative
[5, 1, 9, 3, 8, 7, 10, 6, 0, 4, 2]

The enumerate() function enumerates the elements in an Iterable object and returns an Iterable enumerate object, where each element is a tuple containing an index and a value.

>>> list(enumerate('abcd'))              #Enumerate elements in a string

[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]

>>> list(enumerate(['Python', 'Greate']))       #Enumerate elements in a list

[(0, 'Python'), (1, 'Greate')]

>>> list(enumerate({'a':97, 'b':98, 'c':99}.items())) #Enumerate elements in a dictionary

[(0, ('c', 99)), (1, ('a', 97)), (2, ('b', 98))]

>>> for index, value in enumerate(range(10, 15)):   #Enumerate elements in range object

  print((index, value), end=' ')

(0, 10) (1, 11) (2, 12) (3, 13) (4, 14) 

The built-in function map() maps a function func onto each element of a sequence or iterator object in turn and returns an iterative map object as a result, each element in the map object being the result of a function func treatment of the elements in the original sequence.

>>> list(map(str, range(5)))  #Convert elements in a list to strings

['0', '1', '2', '3', '4']

>>> def add5(v):        #Single parameter function

      return v+5

>>> list(map(add5, range(10)))#Mapping single-parameter functions to all elements of a sequence

[5, 6, 7, 8, 9, 10, 11, 12, 13, 14]

>>> def add(x, y):      #Functions that can take two arguments

  		return x+y

>>> list(map(add, range(5), range(5,10)))  #Mapping a two-parameter function to two sequences

[5, 7, 9, 11, 13]

>>> import random

>>> x = random.randint(1, 1e30)     #Generate random integers in a specified range

>>> x
>>> list(map(int, str(x)))          #Extract numbers per bit of large integer
[8, 3, 9, 7, 4, 6, 5, 5, 8, 2, 1, 5, 8, 9, 7, 2, 4, 2, 2, 2, 0, 0, 4, 6, 2, 2, 3, 1, 5, 0]

The function reduce() in the standard library functools allows a function that takes two parameters to iteratively accumulate from left to right on all elements of a sequence or iterator object, allowing an initial value to be specified.

>>> from functools import reduce

>>> seq = list(range(1, 10))

>>> reduce(lambda x, y: x+y, seq)


The built-in function filter() applies a single-parameter function to a sequence and returns a filter object consisting of those elements in the sequence that make the function return a value of True. If the specified function is None, the elements in the sequence that are equal to True are returned.

>>> seq = ['foo', 'x41', '?!', '***']

>>> def func(x):

  	return x.isalnum()         #Test for letters or numbers

>>> filter(func, seq)          #Return filter object

<filter object at 0x000000000305D898>

>>> list(filter(func, seq))    #Convert the filter object to a list

['foo', 'x41']

range() is a built-in function that is often used in Python development. The syntax format is range([start,] end [, step]), which has three usages: range(stop), range(start, stop) and range(start, stop, step). This function returns a range object with lazy evaluation, which contains integers with step length in the left-closed right open interval [start,end). The parameter start defaults to 0, and the step defaults to 1.

>>> range(5)            #start defaults to 0, step defaults to 1

range(0, 5)

>>> list(_)

[0, 1, 2, 3, 4]

>>> list(range(1, 10, 2))     #Specify start value and step size

[1, 3, 5, 7, 9]

>>> list(range(9, 0, -2))     #start should be larger than end when step size is negative

[9, 7, 5, 3, 1]

The zip() function is used to compress elements from multiple iterative objects together and return an iterative zip object, where each element is a tuple of elements corresponding to the positions of the original multiple iterative objects, like a zipper.

>>> list(zip('abcd', [1, 2, 3]))       #Compress strings and lists

[('a', 1), ('b', 2), ('c', 3)]

>>> list(zip('123', 'abc', ',.!'))      #Compress three sequences

[('1', 'a', ','), ('2', 'b', '.'), ('3', 'c', '!')]

>>> x = zip('abcd', '1234')

>>> list(x)

[('a', '1'), ('b', '2'), ('c', '3'), ('d', '4')]

3. Python keywords

python is higher!!!

Posted by jibster on Thu, 11 Nov 2021 09:21:26 -0800