Learning python notes on the basis of c

Operator correlation

  • #Represents a single line comment, and '' '' or '' '' represents an interval comment. All contents between three quotation marks are annotated
  • In python, Division will not be rounded automatically, so / / is required to indicate Division a//b:a divides b
  • You can directly use * * to represent the power function a**b: the b power of A
  • The + sign in "name"+","+"age"python can be added directly
  • python is a strictly indented programming language. The purpose of indentation is equivalent to {} in c

python logical operator and or not

andAnd(3 > 2) and (3 < 5)
oror(1 > 3) or (9 < 2)
notwrongnot (2 > 1)

Bitwise operators in python

~Bitwise inversion~4
&Bitwise AND4 & 5
|Bitwise OR4 | 5
^Bitwise XOR4 ^ 5
<<Shift left4 << 2
>>Shift right4 >> 2

Ternary operator

x, y = 4, 5  #python does not need to define variable types when assigning values
if x < y:
    small = x
    small = y

print(small)  # 4
x, y = 4, 5
small = x if x < y else y #This is equivalent to x < y? X: y in c
print(small)  # 4

Other operators do not exist, do they? The return value is bool type

inexistence'A' in ['A', 'B', 'C']
not innon-existent'h' not in ['A', 'B', 'C']
isyes"hello" is "hello"
not isno"hello" is not "hello"
#Exist or not
letters = ['A', 'B', 'C']
if 'A' in letters: #The return value type is bool
    print('A' + ' exists') # A exists
if 'h' not in letters:
    print('h' + ' not exists') # h not exists

# Both variables in the comparison point to immutable types
a = "hello"
b = "hello"
print(a is b, a == b)  # True True
print(a is not b, a != b)  # False False

#Both variables in the comparison point to variable types
a = ["hello"]
b = ["hello"]
print(a is b, a == b)  # False True
print(a is not b, a != b)  # True False

be careful:

  • Is and is not compare the memory addresses of the two variables
  • ==,!= Compare the values of two variables
  • If the two variables in the comparison point to the type with immutable address (str, etc.), then is, is not and = == Is completely equivalent
  • The two variables in comparison refer to the types with variable addresses (list, dict, tuple, etc.), so they are different

Operator precedence

**Index (highest priority)
Bitwise flip, unary plus and minus signs
* / % //Multiplication, division, modulo and integer division)
+ -addition and subtraction
>> <<Shift right, shift left operator
&Bit 'AND'
^|Bitwise Operators
<=<>>=Comparison operator
<>==!=equal operator
=%=/=//=-=+=*=**=Assignment Operators
is is notIdentity operator
in not inmember operator
not and orLogical operator

Variables and Assignment

  • x. Y = 1,2 can be assigned in this way

Data type and conversion

intInteger < class' Int '>-876, 10
floatFloating point < class' float '>3.149, 11.11
boolBoolean < class' bool '>True, False

Everything in python is an object, and integer is no exception. As long as it is an object, it has corresponding properties and methods

# Through print (), you can see the value of a and the class is int
a = 1031
#1021 <class 'int'>

print(1, type(1))
# 1 <class 'int'>
print(1., type(1.))
# 1.0 <class 'float'>
a = 0.00000023
b = 2.3e-7
print(a)  # 2.3e-07
print(b)  # 2.3e-07
  • Convert to integer int('a ') convert to character str(1)
print(int('520'))  # 520
print(int(520.52))  # 520
print(float('520.52'))  # 520.52
print(float(520))  # 520.0
print(str(10 + 10))  # 20
print(str(10.1 + 5.2))  # 15.3

print() function

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

  • Format and output the object as a string to the stream file object file. All non keyword parameters are converted into string output by str();
  • The keyword parameter sep is the implementation separator. For example, when multiple parameters are output, you want to output the middle separator character;
  • Keyword parameter end is the character at the end of output. The default is newline character \ n;
  • The keyword parameter file is the file that defines the stream output, which can be the standard system output sys.stdout or redefined as another file;
  • The keyword parameter flush is to output the content to the stream file immediately without caching.
shoplist = ['apple', 'mango', 'carrot', 'banana']
print("This is printed without 'end'and 'sep'.")
for item in shoplist:

# This is printed without 'end'and 'sep'.
# apple
# mango
# carrot
# banana

be careful:

  • When there are no parameters, the line will wrap after each output
  • Each output will end with the parameter & set by end, and line feed print (item, end = '&') will not be used by default
  • Parameter & split set by sep between item value and 'other string'. Since the end parameter is not set, the default value is line feed after output interpretation, that is, the default value of the end parameter is \ n.
shoplist = ['apple', 'mango', 'carrot', 'banana']
print("This is printed with 'sep='&''.")
for item in shoplist:
    print(item, 'another string', sep='&')

# This is printed with 'sep='&''.
# apple&another string
# mango&another string
# carrot&another string
# banana&another string

package and import

b = dir(int)

The built-in dir() function returns a list of names defined by the object. If the object is a module, the list includes the functions, classes, and variables defined within the function. This function accepts arguments. If the parameter is the module name, the function returns a list of the names of the specified module. If no arguments are provided, the function returns a list of the names of the current module.

Sometimes we want to keep the n decimal places of floating-point type. It can be implemented with the decimal object and getcontext() method in the decimal package.

import decimal #Import the decimal package
from decimal import Decimal #You need to use the Decimal object in this package

a = decimal.getcontext()

#`getcontext() ` shows that the default precision value of the 'Decimal' object is 28 bits (` prec=28 ')
# Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999,
# capitals=1, clamp=0, flags=[], 
# traps=[InvalidOperation, DivisionByZero, Overflow])

b = Decimal(1) / Decimal(3)

# 0.3333333333333333333333333333

#Make 1 / 3 keep 4 bits, and use getcontext(). prec to adjust the precision
decimal.getcontext().prec = 4
c = Decimal(1) / Decimal(3)

# 0.3333

There are many widely used packages in Python. You can import whatever you use. Packages are also objects. You can also use the dir(decimal) mentioned above to see their properties and methods.

Conditional statement

if statement

  • If expression: no parentheses, colons are required if expression: else:

assert keyword

The keyword assert is called "assertion". When the condition behind this keyword is False, the program will automatically crash and throw an assertion error exception

my_list = ['lsgogroup']
assert len(my_list) > 0#my_ The length of the list is not greater than 0, so the condition is False

# AssertionError

Circular statement

while Loop

while Boolean expression: like if, body does not need parentheses or curly braces, but it needs a colon.

while - else

while Boolean expression:

​ else:

When the division of the while loop is completed, execute else. If a statement that jumps out of the loop, such as break, is executed in the while loop, the content of the else code block will not be executed.

count = 0
while count < 5:  #The else statement is executed only when count==5 and the loop is executed normally
    print("%d is  less than 5" % count)
    count = count + 1
    print("%d is not less than 5" % count)
# 0 is  less than 5
# 1 is  less than 5
# 2 is  less than 5
# 3 is  less than 5
# 4 is  less than 5
# 5 is not less than 5

count = 0
while count < 5:
    print("%d is  less than 5" % count)
    count = 6
    break    #Execution force break, so the statements after else will not be executed
    print("%d is not less than 5" % count)

# 0 is  less than 5

for loop

for loop is an iterative loop, which is equivalent to a general iterator in python and can traverse any ordered sequence.

  • Similar to for (Auto & x: V) # in c + +, x is used to iterate every element in container v
dic = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
#Dictionary is the only mapping type in python. It stores data in the form of key value pairs.

for key, value in dic.items():
    print(key, value, sep=':', end=' ')
# a:1 b:2 c:3 d:4 

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

for key in dic.keys():
    print(key, end=' ')
# a b c d 

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

for value in dic.values():
    print(value, end=' ')
# 1 2 3 4

for - else loop

When the division of the for loop is completed, else is executed. If a statement that jumps out of the loop, such as break, is executed in the for loop, the content of the else code block will not be executed. Same as while - else.

range() function


  • This BIF (build in functions) has three parameters, of which two enclosed in square brackets indicate that these two parameters are optional.
  • step=1 means that the default value of the third parameter is 1
  • The function of range BIF is to generate a digital sequence from the value of start parameter to the value of stop parameter. The sequence contains the value of start, but does not contain the value of stop.
for i in range(2, 9):  # Excluding 9

# 2
# 3
# 4
# 5
# 6
# 7
# 8

for i in range(1, 10, 2):#Step size is 2

# 1
# 3
# 5
# 7
# 9

enumerate() function


  • Sequence: a sequence, iterator, or other object that supports iteration
  • Start: subscript start position
  • Returns the enumerate object
seasons = ['Spring', 'Summer', 'Fall', 'Winter']
lst = list(enumerate(seasons))
# [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
lst = list(enumerate(seasons, start=1))  # Subscript starts with 1
# [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

enumerate() is used in conjunction with a for loop.

for i, a in enumerate(A)
    do something with a  

enumerate(A) not only returns the element in A, but also gives the element an index value (starting from 0 by default). In addition, using enumerate(A, j) can also determine that the initial value of the cable is j.

languages = ['Python', 'R', 'Matlab', 'C++']
for language in languages:
    print('I love', language)
# I love Python
# I love R
# I love Matlab
# I love C++
# Done!

#The index value starts at 2
for i, language in enumerate(languages, 2):
    print(i, 'I love', language)
# 2 I love Python
# 3 I love R
# 4 I love Matlab
# 5 I love C++
# Done!

break statement and continue statement

  • break statement jumps out of the loop of the current layer
  • continue statementterminates this cycle and starts the next cycle

pass statement

The pass statement means "don't do anything". If you don't write any statements where statements are needed, the interpreter will prompt an error, and the pass statement is used to solve this problem.

def a_func():

# SyntaxError: unexpected EOF while parsing

def a_func():

Pass is an empty statement. It does not do any operation. It only plays the role of occupying bits. Its role is to maintain the integrity of the program structure. Although the pass statement does not do anything, if you are not sure what kind of code to put in a position for the time being, you can put a pass statement first to make the code run normally.


List derivation list []

list=[ expr for value in collection if condition ]
# Operation expression if the condition is true, operate on each value value in the collection
x = [-4, -2, 0, 2, 4]
y = [a * 2 for a in x]  #Every value in a * 2
# [-8, -4, 0, 4, 8]

x = [i ** 2 for i in range(1, 10)]  #Interval 1-10, square of each number
# [1, 4, 9, 16, 25, 36, 49, 64, 81]

x = [(i, i ** 2) for i in range(6)] #Generate 0-5, each square

# [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]

x = [i for i in range(100) if (i % 2) != 0 and (i % 3) == 0]
#Outputs multiples of 3 within 100 and skips even numbers

# [3, 9, 15, 21, 27, 33, 39, 45, 51, 57, 63, 69, 75, 81, 87, 93, 99]

a = [(i, j) for i in range(0, 3) for j in range(0, 3)]
#Two dimensional array
# [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]

Tuple derivation (tuple)

A tuple is a sequence, just like a list. The main difference between tuples and lists is that tuples cannot change the value of elements like lists, which can be simply understood as "read-only lists". Tuples use parentheses - (), while lists use square brackets - []

  • Lists are usually used to store the same type of data; Tuples are usually used to store different types of data in practical development.
  • Tuples are similar to lists, except that the elements of tuples cannot be modified;
  • Tuple represents a sequence composed of multiple elements; It is used to store a string of information, and different data are separated by commas;
  • The index of tuples starts from 0;
tuple=[ expr for value in collection if condition ]
# Operation expression if the condition is true, operate on each value value in the collection
a = (x for x in range(10))

# <generator object <genexpr> at 0x0000025BE511CC48>

#The output of tuples comes with parentheses
# (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

Dictionary derivation dict {}

In Python, a dictionary is a series of key value pairs. Each key is associated with a value, and you can use the key to access the value associated with it. The values associated with keys can be numbers, strings, lists, and even dictionaries. In fact, any Python object can be used as a value in the dictionary.

  • list is an ordered collection of objects
  • dict is an unordered collection of objects

Dictionaries are defined with {}. Dictionaries use key value pairs to store data. Key value pairs are separated. Key is index, value is data, and key and value are separated. Keys must be unique (because we must find the data through the key, the value can take any data type, but the key can only use string, number or tuple. The dictionary is an unordered data set and. When using the print function to output the dictionary, the output order is usually inconsistent with the defined order

{ key_expr: value_expr for value in collection [if condition] }
b = {i: i % 2 == 0 for i in range(10) if i % 3 == 0}
# {0: True, 3: False, 6: True, 9: False}

set derivation

  • A collection is different from a list or tuple. Each element in the collection cannot appear multiple times and is stored out of order.

  • Because the elements in the set cannot appear many times, the set can effectively delete duplicate values from the list or tuple to a great extent, and perform common mathematical operations such as union set and intersection.

s = {1,2,4,5} 
print(type(s)) #<class 'set'>

s1 = {}
print(type(s1))   ##Empty dictionary definition
#<class 'dict'> #Type is Dictionary

s1 = set([])
print(type(s1))    ###Empty set definition
#<class 'set'> #Type is collection

{ expr for value in collection [if condition] }
c = {i for i in [1, 2, 3, 4, 5, 5, 6, 4, 3, 2, 1]}
# {1, 2, 3, 4, 5, 6}

exception handling

An exception is an error detected during runtime. The computer language defines an exception type for possible errors. When an error causes a corresponding exception, the exception handler will be started to restore the normal operation of the program.

Python standard exception summary

  • BaseException: the base class for all exceptions
  • Exception: base class of general exception
  • StandardError: the base class of all built-in standard exceptions
  • ArithmeticError: the base class of all numerical calculation exceptions
  • FloatingPointError: floating point calculation exception
  • Overflow error: numeric operation exceeds the maximum limit
  • ZeroDivisionError: divisor is zero
  • Assertion error: assertion statement (assert) failed
  • AttributeError: an attempt was made to access an unknown object attribute
  • Eofilter: there is no built-in input and the EOF flag is reached
  • EnvironmentError: base class of operating system exception
  • IOError: input / output operation failed
  • OSError: an exception generated by the operating system (for example, opening a file that does not exist)
  • WindowsError: system call failed
  • ImportError: when the import module fails
  • KeyboardInterrupt: user interrupts execution
  • LookupError: base class for invalid data query
  • IndexError: index is out of range for the sequence
  • KeyError: find a keyword that does not exist in the dictionary
  • MemoryError: memory overflow (memory can be released by deleting objects)
  • NameError: an attempt was made to access a variable that does not exist
  • UnboundLocalError: access uninitialized local variables
  • ReferenceError: a weak reference attempts to access an object that has been garbage collected
  • RuntimeError: General runtime exception
  • NotImplementedError: method not yet implemented
  • Syntax error: exception caused by syntax error
  • Indentation error: exception caused by indentation error
  • TabError: mixed use of Tab and space
  • SystemError: General interpreter system exception
  • TypeError: invalid operation between different types
  • ValueError: invalid parameter passed in
  • Unicode error: Unicode related exception
  • Unicode decodeerror: exception during Unicode decoding
  • Unicode encodeerror: exception caused by Unicode encoding error
  • Unicode translateerror: exception caused by Unicode conversion error

There are hierarchical relationships within the exception system. Some relationships in Python exception system are as follows:

Python standard warning summary

  • Warning: base class for warning
  • DeprecationWarning: warning about deprecated features
  • Future warning: warning about future semantic changes in construction
  • UserWarning: warning generated by user code
  • Pending deprecation warning: warning that the feature will be discarded
  • RuntimeWarning: warning of suspicious runtime behavior
  • Syntax warning: warning of suspicious syntax
  • ImportWarning: used to trigger warnings during module import
  • Unicode warning: Unicode related warnings
  • BytesWarning: a warning related to a byte or bytecode
  • ResourceWarning: resource usage related warnings

try - except statement

    Detection range
except Exception[as reason]:
    Handling code after exception

The try statement works as follows

  • First, execute the try clause (the statement between the keyword try and the keyword except)
  • If there is no exception, the exception clause is ignored and the try clause ends after execution
  • If an exception occurs during the execution of the try clause, the rest of the try clause will be ignored. If the type of the exception matches the name after the exception, the corresponding exception clause will be executed. Finally, execute the code after the try exception statement
  • If an exception does not match any except, the exception will be passed to the upper try
    f = open('test.txt')
except OSError as error:
    print('Error opening file\n as a result of:' + str(error))

# Error opening file
# The reason is: [Errno 2] No such file or directory: 'test.txt'
  • A try statement may contain multiple except clauses to handle specific exceptions that are not used. At most one branch will be executed
    s = 1 + '1'
    f = open('test.txt')
except OSError as error:
    print('Error opening file\n as a result of:' + str(error))
except TypeError as error:
    print('Type error\n as a result of:' + str(error))
except ValueError as error:
    print('Value error\n as a result of:' + str(error))

# Value error
# The reason is: invalid literal for int() with base 10: 'abc'
  • An exception clause can handle multiple exceptions at the same time. These exceptions will be placed in a bracket as a tuple
    s = 1 + '1'
    f = open('test.txt')
except (OSError, TypeError, ValueError) as error:
    print('Something went wrong!\n as a result of:' + str(error))

# Something went wrong!
# The reason is: unsupported operand type(s) for +: 'int' and 'str'

Try except finally statement

Detection range
except Exception[as reason]:
Handling code after exception
Code that will be executed anyway

  • The finally clause is executed regardless of whether an exception occurs in the try clause.

  • If an exception is thrown in the try clause and no exception intercepts it, the exception will be thrown after the finally clause is executed.

def divide(x, y):
        result = x / y
        print("result is", result)
    except ZeroDivisionError:
        print("division by zero!")
        print("executing finally clause")

divide(2, 1)
# result is 2.0
# executing finally clause
divide(2, 0)
# division by zero!
# executing finally clause
divide("2", "1")
# executing finally clause
# TypeError: unsupported operand type(s) for /: 'str' and 'str'

Try except else statement

  • If no exception occurs during the execution of the try clause, python will execute the statement after the else statement
    Detection range
except(Exception1[, Exception2[,...ExceptionN]]]):
   If one of the above exceptions occurs, execute this code
    If there are no exceptions, execute this code
    fh = open("testfile.txt", "w")
    fh.write("This is a test file for testing exceptions!!")
except IOError:
    print("Error: File not found or failed to read")
    print("Content written to file successfully")

# Content written to file successfully

Note: the existence of else statement must be based on the existence of exception statement. Using else statement in try statement without exception statement will cause syntax error.

raise statement

  • python uses the raise statement to throw a specified exception
    raise NameError('HiThere')
except NameError:
    print('An exception flew by!')
# An exception flew by!

Tags: Python C

Posted on Sat, 18 Sep 2021 21:19:41 -0400 by Styles2304