Introduction to the

Python is a general-purpose programming language with a wide range of applications in scientific computing and machine learning.

How Python works

  • Shell interactive interpreter
  • File mode, extension py

Install third-party plug-in packages

pip install [pkgName]
Copy the code

Output: print function

Grammar:

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
Copy the code
  • Formats and outputs the object as a string representation to the stream file object file. All non-keyword arguments are converted to string output as STR ();
  • The keyword argument sep is an implementation delimiter, such as the delimiter character that you want to print in the middle of multiple arguments.
  • The keyword argument end is the character at the end of the output. The default is newline character \n;
  • The keyword argument file is the file that defines the stream output. It can be the standard system output sys.stdout, or it can be redefined as another file.
  • The keyword argument flush immediately outputs the content to the stream file without caching.

If there are no arguments, each output will be wrapped.

shoplist = ['apple'.'mango'.'carrot'.'banana']
print("This is printed without 'end'and 'sep'.")
for item in shoplist:
    print(item)

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

shoplist = ['apple'.'mango'.'carrot'.'banana']
print("This is printed with 'end='&''.")
for item in shoplist:
    print(item, end='&')
print('hello world')

# This is printed with 'end='&''.
# apple&mango&carrot&banana&hello world

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
Copy the code

Input: input function

Input () returns a string of type

price = input('Please enter price:')
price
type(price)
# <class 'str'>
Copy the code

style

  • Single-line comments#
# This is a comment
print("Hello world")
Copy the code
  • Multiline comment
"" This is a multi-line comment with three single quotes."
print("Hello china") 
Copy the code
  • Line continuation\
if signal == 'red' and\
car == 'moving':
    car='stop'
# is equal to
if signal == 'red' and car == 'moving':
    car='stop'
Copy the code

Two cases in which a line can be wrapped without a line continuation

  1. The inside of braces, brackets, and curly braces can be written on multiple lines
  2. The triple quotes include strings that can be written across lines
print('''hi everybody, welcome to python, what is your name? ' ' ')
Copy the code
  • Multi-line statement

Use;

x='Today'; y='is'; z='Thursday';print(x,y,z)
Copy the code
  • The indentation

Python uses the same indentation to indicate that a block of the same level increases the indentation to indicate the start of the block and decreases the indentation to indicate the exit of the block

The operator

The operator The name of the The sample
+ add 1 + 1
Reduction of 2-1
* take 3 * 4
/ In addition to Three quarters of
// Exact division (floor division) 3/4
% Take more than 3% 4
** power 2 * * 3

[example]

print(1 + 1)  # 2
print(2 - 1)  # 1
print(3 * 4)  # 12
print(3 / 4)  # 0.75
print(3 // 4)  # 0
print(3 % 4)  # 3
print(2 ** 3)  # 8
Copy the code
  • Comparison operator
The operator The name of the The sample
> Is greater than 2 > 1
> = Greater than or equal to 2 > = 4
< Less than 1 < 2
< = Less than or equal to 5 < = 2
= = Is equal to the 3 = = 4
! = Is not equal to 3 != 5

[example]

print(2 > 1)  # True
print(2> =4)  # False
print(1 < 2)  # True
print(5< =2)  # False
print(3= =4)  # False
print(3! =5)  # True
Copy the code
  • Logical operator
The operator The name of the The sample
and with (3 > 2) and (3 < 5)
or or (1 > 3) or (9 < 2)
not non not (2 > 1)

[example]

print((3 > 2) and (3 < 5))  # True
print((1 > 3) or (9 < 2))  # False
print(not (2 > 1))  # False
Copy the code
  • An operator
The operator The name of the The sample
~ According to the not ~ 4
& Bitwise and 4 & 5
` ` Bitwise or
^ The bitwise exclusive or 4 ^ 5
<< Shift to the left 4 < < 2
>> Moves to the right 4 > > 2

For binary operations, see the section on bitwise operations.

print(bin(4))  # 0b100
print(bin(5))  # 0b101
print(bin(~4), ~4)  # -0b101 -5
print(bin(4 & 5), 4 & 5)  # 0b100 4
print(bin(4 | 5), 4 | 5)  # 0b101 5
print(bin(4 ^ 5), 4 ^ 5)  # 0b1 1
print(bin(4 << 2), 4 << 2)  # 0b10000 16
print(bin(4 >> 2), 4 >> 2)  # 0b1 1
Copy the code
  • Ternary operator

With the conditional expression for the ternary operator, you can use a single statement to perform the above conditional and assignment operations.

[example]

x, y = 4.5
small = x if x < y else y
print(small)  # 4
Copy the code
  • Other operators
The operator The name of the The sample
in There are ‘A’ in [‘A’, ‘B’, ‘C’]
not in There is no ‘h’ not in [‘A’, ‘B’, ‘C’]
is is “hello” is “hello”
not is not “hello” is not “hello”

[example]

letters = ['A'.'B'.'C']
if 'A' in letters:
    print('A' + ' exists')
if 'h' not in letters:
    print('h' + ' not exists')

# A exists
# h not exists
Copy the code

Both variables in the comparison refer to immutable types.

a = "hello"
b = "hello"
print(a is b, a == b)  # True True
print(a is notb, a ! = b)# False False
Copy the code

Both variables in the comparison refer to mutable types.

a = ["hello"]
b = ["hello"]
print(a is b, a == b)  # False True
print(a is notb, a ! = b)# True False
Copy the code

Note:

  • Is, is not compares the memory addresses of two variables

  • = =,! = compares the values of two variables

  • ==! == =! == ==! == ==! == ==! == == =! == == =! == == =! == == =! == == =! == == =! == == =! Theta is completely equivalent.

  • The two variables are different if they refer to types with variable addresses (list, dict, tuple, etc.).

  • The priority of the operator

The operator describe
** Index (highest priority)
~ + – Flip it bitwise, unary plus and minus
% * / / / Multiply, divide, take modulus and take exact division)
+ – Addition subtraction
>> << Shift right, shift left operator
& A ‘AND’
^ An operator
< = < > > = Comparison operator
< > = =! = Equal operator
= % = / = / / = = + = = * = The assignment operator
is is not Identity operator
in not in Member operator
not and or Logical operator

[example]

print(-3 ** 2)  9 # -
print(3* * -2)  # 0.1111111111111111
print(1 << 3 + 2 & 7)  # 0
print(-3 * 2 + 5 / -2 - 4)  # 12.5
print(3 < 4 and 4 < 5)  # True
Copy the code

Variables and assignments

  • A variable needs to be assigned before it can be used.
  • Variable names can contain letters, numbers, and underscores (_), but cannot start with a number.
  • Python variable names are case-sensitive, foo! = Foo.

[example]

teacher = "The Old Horse of Programming."
print(teacher)  # Ma's App Life

first = 2
second = 3
third = first + second
print(third)  # 5

myTeacher = "The Old Horse of Programming."
yourTeacher = "The Little Pony program."
ourTeacher = myTeacher + ', ' + yourTeacher
print(ourTeacher)  # Ma's App, Ma's App
Copy the code

Data types and conversions

  • Basic types: integer, floating point, Boolean
  • Container types: string, tuple, list, dictionary, and collection
type The name of the The sample
int The integer <class ‘int’> -876, 10
float floating-point < class ‘float’ > 3.149, 11.11
bool The Boolean <class ‘bool’> True, False
  • The integer

Python 2 supports long integers followed by “L”

Print (); print(); print();

a = 1031
print(a, type(a))
# 1031 <class 'int'>
Copy the code

Everything in Python is an object, including integers. As long as an object is an object, it has attributes and methods.

Find the binary representation of an integer and return its length.

a = 1031
print(bin(a))  # 0b10000000111
print(a.bit_length())  # 11
Copy the code
  • floating-point

[example]

print(1.type(1))
# 1 <class 'int'>

print(1..type(1.))
# 1.0 < class > 'float'

a = 0.00000023
b = 2.3 e-7
print(a)  # 2.3 e-07
print(b)  # 2.3 e-07
Copy the code

Sometimes we want to keep n decimal places for floating-point. This can be done using the Decimal object in the Decimal package and the getContext () method.

  • The Boolean

Boolean variables can take only two values, True and False. When Boolean variables are used in numeric operations, 1 and 0 represent True and False.

[example]

print(True + True)  # 2
print(True + False)  # 1
print(True * False)  # 0
Copy the code

Instead of assigning variables True and False directly, you can create variables with bool(X)

Bool (X) is True if X is not integer 0 or float 0.0, and the rest is False.

print(type(0), bool(0), bool(1))
# <class 'int'> False True

print(type(10.31), bool(0.00), bool(10.31))
# <class 'float'> False True

print(type(True), bool(False), bool(True))
# <class 'bool'> False True
Copy the code

To determine whether the value of bool(X) is True or False, it depends on whether X is empty, False if it is empty, True if it is not empty.

  • For numeric variables, 0, 0.0 are considered null.
  • Container variables are empty if there are no elements in them.

Getting type information

Get type information type(object)

print(isinstance(1.int))  # True
print(isinstance(5.2.float))  # True
print(isinstance(True.bool))  # True
print(isinstance('5.2'.str))  # True
Copy the code

Note:

  • Type () does not consider a subclass to be a parent type, regardless of inheritance.
  • Isinstance () considers a subclass to be a superclass type, considering inheritance.

Isinstance () is recommended to determine whether two types are the same.

Type conversion

To int(x, base=10) to string STR (object= “) to float(x)

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
Copy the code

An operation

  • Source, inverse, and complement

Binary is represented in three different forms: source code, inverse code and complement, which is used internally by computers.

Source code: is its binary representation (note that there is a sign bit).

00 00 00 11 -> 3
10 00 00 11 -> -3
Copy the code

Inverse code: the inverse code of a positive number is the original code, and the inverse code of a negative number is the same symbol bit, and the rest bits are inverted (the corresponding positive number is inverted by bit).

00 00 00 11 -> 3
11 11 11 00 -> -3
Copy the code

Complement: The complement of a positive number is the original code, and the complement of a negative number is the inverse +1.

00 00 00 11 -> 3
11 11 11 01 -> -3
Copy the code

Sign bit: The highest bit is the sign bit. 0 represents a positive number and 1 represents a negative number. Sign bits are also involved in bit operations.

Bitwise operations

  • Bitwise non-operation ~
~ 1 = 0
~ 0 = 1
Copy the code

~ inverts both 0 and 1 in num’s complement (0 becomes 1, 1 becomes 0). The sign bit of a signed integer is also inverted in ~.

  • Bit and operation &
1&1 = 1 1&0 = 0 0&1 = 0 0&0 = 0Copy the code

It is 1 only if both corresponding bits are 1

  • The bitwise or operator |
1 | 1 = 1
1 | 0 = 1
0 | 1 = 1
0 | 0 = 0
Copy the code

It’s a 1 as long as one of the two corresponding bits is a 1

  • Xor operation ^ by bit
1 to the 1 is 0, 1 to the 0 is 1, 0 to the 1 is 1, 0 to the 0 is 0Copy the code

The property of an xOR operation that is 1 only when the two corresponding bits are different: the commutative and associative laws are satisfied

  • Bitwise left-shift operation <<

Num << I The value of moving the binary representation of num by I bits to the left.

00 00 10 11 -> 11 11 << 3 -- 01 01 10 00 -> 88Copy the code
  • Move right by bit >>

Num >> I The value of moving the binary representation of num by I bits to the right.

00 00 10 11 -> 11 11 >> 2 -- 00 00 00 10 -> 2Copy the code

Use bit operation to realize fast calculation

Use <<, >> to quickly compute multiples of 2.

N << 1 -> compute n*2 n >> 1 -> compute n/2, n << m -> compute n/(2^m), n << m -> compute n/(2^m), n << m -> compute n/(2^m), n << m -> compute n/(2^m), n << m -> compute n/(2^m), That's divided by 2 to the m: 1 << n -> 2 to the nCopy the code

Swap two integers quickly by ^. Swap two integers quickly by ^.

a ^= b
b ^= a
a ^= b
Copy the code

A & (-a) quickly retrieves the integer at the last 1 position of a.

00 00 01 01 -> 5 & 11 11 10 11 -> -5-00 00 00 01 -> 1 00 00 11 10 -> 14 & 11 11 00 10 -> 14-00 00 00 10 -> 2Copy the code

The use of bit operations to achieve a set of integers

The binary representation of a number can be thought of as a set (0 means not in the set, 1 means in the set).

For example, the set {1, 3, 4, 8} can be represented as 01, 00, 01, 10, 10 and the corresponding bit operations can also be regarded as operations on the set.

Operations on elements and sets:

A | (1 < < I) - > I inserted into the collection & a ~ (1 < < I) - > I deleted from the collection of a & (1 < < I) - > whether I belong to the collection (zero does not belong to, the non-zero belongs to)Copy the code

Operations between collections:

A fill - > ~ a a/b - > a & b and b - > a | b a bad b - > a & b (~)Copy the code

Note: integers exist in memory in the form of complement, and the output naturally follows the complement output.

print(bin(3))  # 0b11
print(bin(-3))  # -0b11

print(bin(-3 & 0xffffffff))  
# 0b11111111111111111111111111111101

print(bin(0xfffffffd))       
# 0b11111111111111111111111111111101

print(0xfffffffd)  # 4294967293
Copy the code

Is it very subversive? We can see from the results:

  • Bin in Python is a negative number (in decimal notation) that outputs the binary representation of its source code plus a minus sign, the pit.
  • Integers in Python are stored as complement.
  • Integers in Python are of unlimited length and do not overflow.

Therefore, in order to obtain the complement of a negative number (expressed in decimal), it needs to be manually combined with the hexadecimal number 0xffffFFFF, and then given to bin() for output. The result is the complement representation of a negative number.

Conditional statements

If statement

Grammar:

if expression:
    expr_true_suit
Copy the code
  • Expression: conditional expression
  • Expr_true_suit: expression Code block executed when the condition is true, must have indentation

If-else statement

if expression:
    expr_true_suit
else
    expr_false_suit
Copy the code
  • Expr_false_suit: expression Code blocks executed when the condition is false must have indentation,elseWithout indentation

If-elif-else statement

Grammar:

if expression :
    expr_true_suite
elif expression2:
    expr2_true_suite
:
:
elif expressionN :
    exprN_true_suite
else:
    none_of_the_above_suite
Copy the code

case

temp = input('Please enter result :')
source = int(temp)
if 100 >= source >= 90:
    print('A')
elif 90 > source >= 80:
    print('B')
elif 80 > source >= 60:
    print('C')
elif 60 > source >= 0:
    print('D')
else:
    print('Typing error! ')
Copy the code

Assert keywords

The assert keyword is called “assertion,” and when the condition following it is False, the program crashes and throws an AssertionError.

my_list = ['lsgogroup']
my_list.pop(0)
assert len(my_list) > 0

# AssertionError
Copy the code

Looping statements

The while loop

Grammar:

while expression:
    suite_to_repeat
Copy the code

Ex. :

string = 'abcd'
while string:
    print(string)
    string = string[1:]
Copy the code

While-else loop

grammar

whileBoolean expressions: code blockselse: the code blockCopy the code

The for loop

grammar

forIteration variableinIterable: blocks of codeCopy the code

case

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

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

For-else loop

grammar

forIteration variableinIterable: blocks of codeelse: the code blockCopy the code

case

for num in range(10.20) :Iterate over numbers between 10 and 20
    for i in range(2, num):  # Iterating by factor
        if num % i == 0:  # determine the first factor
            j = num / i  # Compute the second factor
            print('%d = %d * %d' % (num, i, j))
            break  # exit the current loop
    else:  # else part of the loop
        print(num, It's a prime number.)

# 10 is 2 times 5
# 11 is a prime number
So # 12 is 2 times 6
# 13 is a prime number
# 14 is 2 times 7
So # 15 is 3 times 5
# 16 is 2 times 8
# 17 is a prime number
# 18 is 2 times 9
# 19 is a prime number
Copy the code

The range () function

grammar

range([start,] stop[, step=1])
Copy the code
  • This BIF (built-in Functions) takes three arguments, two of which are enclosed in brackets to indicate that they are optional.
  • Step =1 means that the default value of the third argument is 1.
  • Range is a BIF that generates a sequence of numbers from the start values to the stop values. The sequence contains the start values but not the stop values.

case

for i in range(2.9) :# does not contain 9
    print(i)

# 2
# 3
# 4
# 5
# 6
# 7
# 8
Copy the code

Enumerate () function

grammar

enumerate(sequence, [start=0])
Copy the code
  • Sequence: A sequence, iterator, or other object that supports iteration.
  • Start: indicates the start position of the subscript.
  • The Enumerate object is returned

case

seasons = ['Spring'.'Summer'.'Fall'.'Winter']
lst = list(enumerate(seasons))
print(lst)
# [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
lst = list(enumerate(seasons, start=1))  # The subscript starts at 1
print(lst)
# [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
Copy the code
  • Used with enumerate() in combination with the for loop.
for i, a in enumerate(A)
    do something with a 
Copy the code

Enumerate (A) not only returns the element in A, but also incidentally gives that element an index value (starting at 0 by default). In addition, enumerate(A, j) is used to determine that the index starts at J. case

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


for i, language in enumerate(languages, 2) :print(i, 'I love', language)
print('Done! ')
# 2 I love Python
# 3 I love R
# 4 I love Matlab
# 5 I love C++
# Done!
Copy the code

Break statement

The break statement breaks out of the loop at the current level

The continue statement

Continue terminates the current cycle and begins the next cycle

Pass statement

The pass statement means “do nothing,” and the interpreter will prompt you with an error if you don’t write anything where you need a statement, and the pass statement is used to solve these problems

def a_func() :
    pass
Copy the code

Pass is an empty statement that does nothing but serves as a placeholder to preserve the integrity of the program structure. Although the pass statement does nothing, if you’re unsure about what code to put in a place, you can put a pass statement in and let the code work.

The derived type

  • List derivation
[ expr for value in collection [if condition] ]
Copy the code

case

x = [-4, -2.0.2.4]
y = [a * 2 for a in x]
print(y)
# [-8, -4, 0, 4, 8]
Copy the code
  • Tuple derivation
( expr for value in collection [if condition] )
Copy the code

case

a = (x for x in range(10))
print(a)

# <generator object <genexpr> at 0x0000025BE511CC48>

print(tuple(a))

# (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
Copy the code
  • Dictionary derivation
{ key_expr: value_expr for value in collection [if condition] }
Copy the code

case

b = {i: i % 2= =0 for i in range(10) if i % 3= =0}
print(b)
# {0: True, 3: False, 6: True, 9: False}
Copy the code
  • Set derivation
{ expr for value in collection [if condition] }
Copy the code

case

c = {i for i in [1.2.3.4.5.5.6.4.3.2.1]}
print(c)
# {1, 2, 3, 4, 5, 6}
Copy the code
  • other
next(iterator[, default])
Copy the code

case

e = (i for i in range(10))
print(e)
# <generator object <genexpr> at 0x0000007A0B8D01B0>

print(next(e))  # 0
print(next(e))  # 1

for each in e:
    print(each, end=' ')

# 2 3 4 5 6 7 8 9
Copy the code

Exception handling

An exception is an error detected at runtime. Computer languages define exception types for possible errors. When an error raises the 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 for regular exceptions
  • StandardError: Base class for all built-in standard exceptions
  • ArithmeticError: The base class for all numeric calculation exceptions
  • FloatingPointError: Floating-point calculation exception
  • OverflowError: The number of operations exceeds the upper limit
  • ZeroDivisionError: The divisor is zero
  • AssertionError: The assert statement failed
  • AttributeError: Attempts to access unknown object attributes
  • EOFError: No built-in input, EOF flag is reached
  • EnvironmentError: Base class for operating system exceptions
  • IOError: the input/output operation failed
  • OSError: an exception raised by the operating system (such as opening a file that does not exist)
  • WindowsError: System call failure
  • ImportError: When importing a module fails
  • KeyboardInterrupt: The user interrupts execution
  • LookupError: Base class for invalid data queries
  • IndexError: The index is out of the range of the sequence
  • KeyError: Searches for a non-existent keyword in the dictionary
  • MemoryError: Memory overflow (memory can be freed by deleting objects)
  • NameError: Attempts to access a variable that does not exist
  • UnboundLocalError: Access an uninitialized local variable
  • ReferenceError: Weak references attempt to access objects that have already been garbage collected
  • RuntimeError: General runtime exception
  • NotImplementedError: method not yet implemented
  • SyntaxError: an exception caused by a SyntaxError
  • IndentationError: Exception caused by indentation errors
  • TabError: a combination of Tab and space
  • SystemError: General interpreter system exception
  • TypeError: Invalid operations between different types
  • ValueError: Invalid argument passed
  • UnicodeError: Unicode-related exception
  • UnicodeDecodeError: Exception during Unicode decoding
  • UnicodeEncodeError: Exception caused by A Unicode encoding error
  • UnicodeTranslateError: Exception caused by a Unicode conversion error

Summary of Python standard warnings

  • Warning: The base class for warnings
  • DeprecationWarning: A warning about deprecated features
  • FutureWarning: A warning that the semantics of a construct will change in the future
  • UserWarning: Warning generated by user code
  • PendingDeprecationWarning: warning about properties will be discarded
  • RuntimeWarning: Indicates a warning about suspicious runtime behavior
  • SyntaxWarning: Warning of suspicious syntax
  • ImportWarning: Warning to be triggered during module import
  • UnicodeWarning: Unicode-related warning
  • BytesWarning: Warning related to bytes or bytecodes
  • ResourceWarning: A warning related to resource usage

Try-except statement

grammar

try: Detection rangeexcept Exception[asReason]: Indicates the code for handling exceptionsCopy the code

The RY statement works like this:

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

Error opening file
[Errno 2] No such file or directory: 'test.txt'
Copy the code

A try statement may contain multiple except clauses to handle different specific exceptions. At most, only one branch will be executed

try:
    int("abc")
    s = 1 + '1'
    f = open('test.txt')
    print(f.read())
    f.close()
except OSError as error:
    print('Error opening file \n cause:' + str(error))
except TypeError as error:
    print('Type error \n Cause:' + str(error))
except ValueError as error:
    print('Value error \n cause:' + str(error))

# error
Invalid literal for int() with base 10: 'ABC'
Copy the code

The try-exception-else statement attempts to query for key-value pairs that are not in the dict, throwing an exception. This exception is exactly a KeyError, but because KeyError is a subclass of LookupError and puts LookupError before KeyError, the program takes precedence over the except block. So, when using multiple except blocks, you must insist on ordering them formally, from the most specific exceptions to the most generic.

dict1 = {'a': 1.'b': 2.'v': 22}
try:
    x = dict1['y']
except KeyError:
    print('Key error')
except LookupError:
    print('Query error')
else:
    print(x)

# key error
Copy the code

An except clause can handle multiple exceptions at the same time, which are grouped into a tuple in parentheses

try:
    s = 1 + '1'
    int("abc")
    f = open('test.txt')
    print(f.read())
    f.close()
except (OSError, TypeError, ValueError) as error:
    print('Wrong! \n The reason is: ' + str(error))

# Error!
Unsupported operand type(s) for +: 'int' and 'STR'
Copy the code

Try-exception-finally statement

Except Exception[as reason]: the code that handles an Exception finally: the code that will be executed anyway

The finally clause executes whether or not an exception occurs in the try clause.

Example: If an exception is thrown in the try clause without any except to stop it, then the exception will be thrown after the finally clause is executed.

def divide(x, y) :
    try:
        result = x / y
        print("result is", result)
    except ZeroDivisionError:
        print("division by zero!")
    finally:
        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'
Copy the code

Try-except-else statement

If no exception occurs when the try clause is executed, Python executes the statement following the else statement.

try: Detection rangeexcept: Code for handling exceptionselseExecute this code if there are no exceptionsCopy the code

Using except without any exception type is not a very good way to identify specific exception information through the program because it catches all exceptions.

Except (Exception1[, Exception2[,…ExceptionN]]]): Execute this code if one of the preceding exceptions occurs else: Execute this code if no exception occurs

try:
    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")
else:
    print("Content written to file successfully")
    fh.close()

The content was successfully written to the file
Copy the code

Note: The existence of an else statement must be preceded by the existence of an except statement. Using the else statement in a try statement without an except statement raises a syntax error

Raise statement

The raise statement raises a specified exception

try:
    raise NameError('HiThere')
except NameError:
    print('An exception flew by! ')
    
# An exception flew by!
Copy the code