current position:Home>Python Basics: from variables to exception handling

Python Basics: from variables to exception handling

2022-01-30 15:36:50 chaoyu

brief introduction

Python It's a universal programming language , It is widely used in scientific computing and machine learning .

python Operation mode

  • shell Interactive interpreter
  • File mode , Extension py

Install third-party plug-in package

pip install [pkgName]
 Copy code 

Output :print function

grammar :

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
 Copy code 
  • Format and output the object as a string to the stream file object file in . All non keyword parameters are pressed str() Method to convert to string output ;
  • Key parameters sep It's the implementation separator , For example, when multiple parameters are output, you want to output the middle separator character ;
  • Key parameters end Is the character at the end of the output , The default is line break \n;
  • Key parameters file Is the file that defines the output of the stream , Can be standard system output sys.stdout, It can also be redefined as another file ;
  • Key parameters flush Is to output the content to the stream file immediately , No caching .

【 Example 】 Without parameters , Each output will wrap .

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 code 

Input : input function

input() The returned type is string type

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

style

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

There are two situations in which a line can be wrapped directly without line continuation

  1. parentheses 、 brackets 、 The inside of curly braces can be written in multiple lines
  2. The string under three quotation marks can be written across lines
print('''hi everybody, welcome to python, what is your name?''')
 Copy code 
  • One line, many sentences

use ;

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

Python Use the same indentation to represent the same level statement block Increasing the indent indicates the beginning of the statement block Reducing the indent indicates the exit of the statement block

Operator

The operator name Example
+ Add 1 + 1
- reduce 2 - 1
* ride 3 * 4
/ except 3 / 4
// to be divisible by ( Floor removal ) 3 // 4
% Remainder 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 code 
  • Comparison operator
The operator name Example
> Greater than 2 > 1
>= Greater than or equal to 2 >= 4
< Less than 1 < 2
<= Less than or equal to 5 <= 2
== be equal to 3 == 4
!= It's 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 code 
  • Logical operators
The operator name Example
and And (3 > 2) and (3 < 5)
or or (1 > 3) or (9 < 2)
not Not not (2 > 1)

【 Example 】

print((3 > 2) and (3 < 5))  # True
print((1 > 3) or (9 < 2))  # False
print(not (2 > 1))  # False
 Copy code 
  • An operator
The operator name Example
~ According to the not ~4
& Bitwise AND 4 & 5
` ` Press bit or
^ Bitwise XOR 4 ^ 5
<< Move left 4 << 2
>> Move right 4 >> 2

【 Example 】 About binary operations , See “ An operation ” Part of the explanation .

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 code 
  • Ternary operator

With the conditional expression of this ternary operator , You can use one statement to complete the above conditional judgment and assignment operations .

【 Example 】

x, y = 4, 5
small = x if x < y else y
print(small)  # 4
 Copy code 
  • Other operators
The operator name Example
in There is 'A' in ['A', 'B', 'C']
not in non-existent 'h' not in ['A', 'B', 'C']
is yes "hello" is "hello"
not is No "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 code 

【 Example 】 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
 Copy code 

【 Example 】 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
 Copy code 

Be careful :

  • is, is not Compare the memory addresses of the two variables

  • ==, != You compare the values of two variables

  • Compare the two variables , It points to the immutable type of address (str etc. ), that is,is not and ==,!= It's completely equivalent .

  • Compare the two variables , It points to a variable address type (list,dict,tuple etc. ), There is a difference between the two .

  • Operator precedence

Operator describe
** Index ( Highest priority )
~+- Flip by bit , One yuan plus sign and minus sign
* / % // ride , except , Mold and division )
+ - addition and subtraction
>> << Move right , Shift left operator
& position ‘AND’
^ An operator
<=<>>= Comparison operator
<>==!= Equals operator
=%=/=//=-=+==*= Assignment operator
is is not Identity operator
in not in member operator
not and or Logical operators

【 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 code 

Variables and assignments

  • Before using variables , It needs to be assigned first .
  • Variable names can include letters 、 Numbers 、 Underline 、 But the variable name cannot start with a number .
  • Python Variable names are case sensitive ,foo != Foo.

【 Example 】

teacher = " Old horse's procedural life "
print(teacher)  #  Old horse's procedural life 

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

myTeacher = " Old horse's procedural life "
yourTeacher = " Pony's procedural life "
ourTeacher = myTeacher + ',' + yourTeacher
print(ourTeacher)  #  Old horse's procedural life , Pony's procedural life 
 Copy code 

Data types and transformations

  • Basic types : integer 、 floating-point 、 Boolean type
  • Container type : character string 、 Tuples 、 list 、 Dictionaries and collections
type name Example
int integer <class 'int'> -876, 10
float floating-point <class 'float'> 3.149, 11.11
bool Boolean type <class 'bool'> True, False
  • integer

python 2 Support adding after plastic surgery “L” Long integer

【 Example 】 adopt print() It can be seen that a Value , And classes (class) yes int.

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

Python All things in it are objects (object), Integer is no exception , As long as it's an object , There are corresponding properties (attributes) And methods (methods).

【 Example 】 Find a binary representation of an integer , Then return its length .

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

【 Example 】

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

Sometimes we want to keep floating point numbers after the decimal point n position . It can be used decimal In the bag Decimal Objects and getcontext() Method to implement .

  • Boolean type

Boolean (boolean) Type variable can only take two values ,True and False. When Boolean variables are used in numerical operations , use 1 and 0 representative True and False.

【 Example 】

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

In addition to assigning values directly to variables True and False, You can also use bool(X) To create variables

【 Example 】bool Acting on basic type variables :X As long as it's not an integer 0、 floating-point 0.0,bool(X) Namely True, 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 code 

determine bool(X) The value of is True still False, Just look X Is it empty , Empty words are False, If it's not empty, it's True.

  • For numerical variables ,0, 0.0 Can be considered empty .
  • For container variables , If there is no element in it, it is empty .

Get type information

Get type information type(object) 【 Example 】

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

notes :

  • type() A subclass is not considered a superclass type , Do not consider inheritance relationships .
  • isinstance() Think of a subclass as a superclass type , Consider inheritance relationships .

It is recommended if you want to determine whether two types are the same isinstance().

Type conversion

Convert to integer int(x, base=10) Convert to string str(object='') Convert to floating point float(x) 【 Example 】

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 code 

An operation

  • Original code 、 Inverse and complement

Binary has three different representations : Original code 、 Inverse and complement , Complement code is used inside the computer to express .

Original code : Is its binary representation ( Be careful , There is a sign bit ).

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

Inverse code : The inverse of a positive number is the original code , The inverse of a negative number is a sign bit invariant , The rest of the bits are reversed ( The corresponding positive number is negated by bit ).

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

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

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

Sign bit : The highest bit is the sign bit ,0 It means a positive number ,1 A negative number . In the in place operation, the symbol bit also participates in the operation .

Bitwise operation

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

~ hold num In the complement of 0 and 1 All reversed (0 Turn into 1,1 Turn into 0) The sign bit of a signed integer is ~ In the operation, it will also take negation .

  • Press bit and operate &
1 & 1 = 1
1 & 0 = 0
0 & 1 = 0
0 & 0 = 0
 Copy code 

Only two corresponding bits are 1 Only when 1

  • To press or operate |
1 | 1 = 1
1 | 0 = 1
0 | 1 = 1
0 | 0 = 0
 Copy code 

As long as one of the two corresponding bits 1 When it comes to time 1

  • Operate by bitwise exclusive or ^
1 ^ 1 = 0
1 ^ 0 = 1
0 ^ 1 = 1
0 ^ 0 = 0
 Copy code 

It is only when two corresponding bits are different 1 Nature of XOR operation : Satisfy the law of exchange and the law of union

  • Shift left by bit operation <<

num << i take num The binary representation of moves to the left i The value obtained by bit .

00 00 10 11 -> 11
11 << 3
---
01 01 10 00 -> 88 
 Copy code 
  • Shift right by bit operation >>

num >> i take num The binary representation of moves to the right i The value obtained by bit .

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

Using bit operation to realize fast calculation

adopt <<,>> Fast calculation 2 The multiple problem of .

n << 1 ->  Calculation  n*2
n >> 1 ->  Calculation  n/2, Negative odd operations are not available 
n << m ->  Calculation  n*(2^m), That's multiplied by  2  Of  m  Power 
n >> m ->  Calculation  n/(2^m), Divided by  2  Of  m  Power 
1 << n -> 2^n
 Copy code 

adopt ^ Quickly swap two integers . adopt ^ Quickly swap two integers .

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

adopt a & (-a) Get... Quickly a The last is 1 Integer of position .

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

Using bit operation to realize integer set

The binary representation of a number can be regarded as a set (0 Not in the set ,1 In a set ).

For example, a collection {1, 3, 4, 8}, It can be expressed as 01 00 01 10 10 The corresponding bit operation can also be regarded as the operation on the set .

Operation of elements and collections :

a | (1<<i)  ->  hold  i  Insert into collection 
a & ~(1<<i) ->  hold  i  Remove from collection 
a & (1<<i)  ->  Judge  i  Whether it belongs to the collection ( Zero does not belong to , Nonzero belongs to )
 Copy code 

Operations between collections :

a  repair    -> ~a
a  hand over  b -> a & b
a  and  b -> a | b
a  Bad  b -> a & (~b)
 Copy code 

Be careful : Integers exist in memory in the form of complements , Naturally, the output is also output according to the complement .

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

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

print(bin(0xfffffffd))       
# 0b11111111111111111111111111111101

print(0xfffffffd)  # 4294967293
 Copy code 

Isn't it subversive , We can see from the result that :

  • Python in bin A negative number ( Decimal means ), The output is the binary representation of its original code plus a minus sign , crater .
  • Python Integers in are stored as complements .
  • Python The integer is unlimited in length and will not overflow .

So in order to get negative numbers ( Decimal means ) Complement , You need to manually combine it with a hexadecimal number 0xffffffff Do bit and operation , Give it back bin() For the output , What you get is the complement of a negative number .

Conditional statements

if sentence

grammar :

if expression:
    expr_true_suit
 Copy code 
  • expression: Conditional expression
  • expr_true_suit: expression Condition is true Execute code block , It has to be indented

if - else sentence

if expression:
    expr_true_suit
else
    expr_false_suit
 Copy code 
  • expr_false_suit: expression Condition is false Execute code block , It has to be indented ,else Don't indent

if - elif - else sentence

grammar :

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

example

temp = input(' Please enter the grade :')
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(' Input error !')
 Copy code 

assert key word

assert We call this key word “ Assertion ”, When the following condition of the keyword is False when , The program automatically crashes and throws AssertionError It's abnormal .

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

# AssertionError
 Copy code 

Loop statement

while loop

grammar :

while expression:
    suite_to_repeat
 Copy code 

example :

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

while - else loop

grammar

while  Boolean expression :
     Code block 
else:
     Code block 
 Copy code 

for loop

grammar

for  Iterative variable  in  Iteratable object :
     Code block 
 Copy code 

example

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 code 

for - else loop

grammar

for  Iterative variable  in  Iteratable object :
     Code block 
else:
     Code block 
 Copy code 

example

for num in range(10, 20):  #  iteration  10  To  20  Number between 
    for i in range(2, num):  #  Iterate over the factors 
        if num % i == 0:  #  Determine the first factor 
            j = num / i  #  Calculate the second factor 
            print('%d  be equal to  %d * %d' % (num, i, j))
            break  #  Jump out of current loop 
    else:  #  Cyclic  else  part 
        print(num, ' It's a prime number ')

# 10  be equal to  2 * 5
# 11  It's a prime number 
# 12  be equal to  2 * 6
# 13  It's a prime number 
# 14  be equal to  2 * 7
# 15  be equal to  3 * 5
# 16  be equal to  2 * 8
# 17  It's a prime number 
# 18  be equal to  2 * 9
# 19  It's a prime number 
 Copy code 

range() function

grammar

range([start,] stop[, step=1])
 Copy code 
  • This BIF(Built-in functions) There are three parameters , The two parameters enclosed in brackets indicate that the two parameters are optional .
  • step=1 Indicates that the default value for the third parameter is 1.
  • range This BIF The function of the is to generate a from start The value of the parameter starts to stop The value of the parameter ends with a sequence of numbers , The sequence contains start But does not contain stop Value .

example

for i in range(2, 9):  #  It doesn't contain 9
    print(i)

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

enumerate() function

grammar

enumerate(sequence, [start=0])
 Copy code 
  • sequence: A sequence 、 Iterators or other objects that support iteration .
  • start: Subscript start position .
  • return enumerate( enumeration ) object

example

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))  #  Subscript from  1  Start 
print(lst)
# [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
 Copy code 
  • enumerate() And for Combined use of recycling .
for i, a in enumerate(A)
    do something with a 
 Copy code 

use enumerate(A) Not only did it return A The elements in , By the way, give the element an index value ( The default from the 0 Start ). Besides , use enumerate(A, j) It can also be determined that the initial value caused by the cable is j. example

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 code 

break sentence

break Statement can jump out of the loop of the current layer

continue sentence

continue Terminate this cycle and start the next cycle

pass sentence

pass The meaning of the sentence is “ Not doing anything ”, If you don't write any sentences where you need them , Then the interpreter will prompt an error , and pass Sentences are used to solve these problems

def a_func():
    pass
 Copy code 

pass It's an empty statement , Do nothing , It only plays a role of occupying , Its purpose is to maintain the integrity of the program structure . Even though pass Statement does nothing , But if you're not sure what kind of code to put in one place , You can put a pass sentence , Let the code work .

The derived type

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

example

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

example

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 code 
  • Dictionary derivation
{ key_expr: value_expr for value in collection [if condition] }
 Copy code 

example

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 code 
  • Set derivation
{ expr for value in collection [if condition] }
 Copy code 

example

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 code 
  • Other
next(iterator[, default])
 Copy code 

example

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 code 

exception handling

An exception is an error detected at run time . Computer language defines exception types for possible errors , When an error throws a corresponding exception , The exception handler will be started , So as to restore the normal operation of the program

Python Summary of standard exceptions

  • BaseException: All abnormal Base class
  • Exception: Normal abnormal Base class
  • StandardError: All built-in standard exception base classes
  • ArithmeticError: The base class of all numerical computation anomalies
  • FloatingPointError: Floating point computation exception
  • OverflowError: The numerical operation exceeds the maximum limit
  • ZeroDivisionError: Divisor is zero.
  • AssertionError: Assertions (assert) Failure
  • AttributeError: Trying to access unknown object properties
  • EOFError: No built-in input , arrive EOF Mark
  • EnvironmentError: Base class for operating system exceptions
  • IOError: Input / Output operation failed
  • OSError: An exception generated by the operating system ( For example, open a file that doesn't exist )
  • WindowsError: System call failed
  • ImportError: When the import module fails
  • KeyboardInterrupt: User interrupt execution
  • LookupError: Base class for invalid data query
  • IndexError: Index out of range of sequence
  • KeyError: Look up a nonexistent keyword in the dictionary
  • MemoryError: out of memory ( You can free memory by deleting objects )
  • NameError: Try to access a variable that doesn't exist
  • UnboundLocalError: Accessing an uninitialized local variable
  • ReferenceError: A weak reference attempts to access an object that has been garbage collected
  • RuntimeError: General runtime exceptions
  • NotImplementedError: A method that has not yet been implemented
  • SyntaxError: An exception caused by a grammatical error
  • IndentationError: An exception caused by an indentation error
  • TabError:Tab Mixed with Spaces
  • SystemError: General interpreter system exception
  • TypeError: Invalid operation between different types
  • ValueError: Invalid parameter passed in
  • UnicodeError:Unicode Related anomalies
  • UnicodeDecodeError:Unicode Decoding exception
  • UnicodeEncodeError:Unicode Exception caused by coding error
  • UnicodeTranslateError:Unicode Exception caused by conversion error

Python Standard warning summary

  • Warning: The base class for warnings
  • DeprecationWarning: A warning about abandoned features
  • FutureWarning: A warning about future semantic changes in construction
  • UserWarning: Warnings generated by user code
  • PendingDeprecationWarning: A warning that features will be discarded
  • RuntimeWarning: Suspicious runtime behavior (runtime behavior) Warning of
  • SyntaxWarning: Warning of suspicious grammar
  • ImportWarning: Used to trigger warnings during module import
  • UnicodeWarning: And Unicode Related warnings
  • BytesWarning: Warning related to byte or bytecode
  • ResourceWarning: Warnings related to resource usage

try - except sentence

grammar

try:
     Detection range 
except Exception[as reason]:
     Exception handling code 
 Copy code 

ry The statement works as follows :

  • First , perform try Clause ( In keywords try And keywords except The sentence between )
  • If no exceptions occur , Ignore except Clause ,try End after Clause execution .
  • If in execution try An exception occurred during clause , that try The rest of the clause will be ignored . If the type of exception and except The following names match , So the corresponding except Clause will be executed . Finally, execute try - except Code after statement .
  • If an exception is not associated with anything except matching , Then this exception will be passed to the upper level try in .
try:
    f = open('test.txt')
    print(f.read())
    f.close()
except OSError as error:
    print(' Error opening file \n as a result of :' + str(error))

#  Error opening file 
#  as a result of :[Errno 2] No such file or directory: 'test.txt'
 Copy code 

One try The statement may contain more than one except Clause , To handle different specific exceptions . At most 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 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 
#  as a result of :invalid literal for int() with base 10: 'abc'
 Copy code 

try-except-else Statement attempts to query not in dict Key value pairs in , This raises an exception . This anomaly should accurately belong to KeyError, But because of KeyError yes LookupError Subclasses of , And will LookupError in KeyError Before , Therefore, the program gives priority to the execution of the except Code block . therefore , The use of multiple except When a code block , We must adhere to the standard ranking , From the most targeted exception to the most general exception .

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 code 

One except Clause can handle multiple exceptions at the same time , These exceptions will be placed in parentheses as a tuple

try:
    s = 1 + '1'
    int("abc")
    f = open('test.txt')
    print(f.read())
    f.close()
except (OSError, TypeError, ValueError) as error:
    print(' Something went wrong !\n as a result of :' + str(error))

#  Something went wrong !
#  as a result of :unsupported operand type(s) for +: 'int' and 'str'
 Copy code 

try - except - finally sentence

try: Detection range except Exception[as reason]: Exception handling code finally: Code that will be executed anyway

No matter try Is there any exception in the clause ,finally Clause will execute .

example : If an exception is in try Thrown in Clause , And nothing except Stop it , So this exception will be in finally Clause is thrown after execution .

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 code 

try - except - else sentence

If in try No exception occurred while clause was executing ,Python Will perform else Statement after statement .

try:
     Detection range 
except:
     Exception handling code 
else:
     If there is no exception to execute this code 
 Copy code 

Use except Without any exception types , This is not a good way , We can't identify specific exception information through this program , Because it catches all the exceptions .

try: Detection range except(Exception1[, Exception2[,...ExceptionN]]]): One of the above exceptions , Execute this code else: If there is no exception to execute this code

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()

#  Content written to file successfully 
 Copy code 

Be careful :else The statement must exist in except The existence of the statement is the premise , In the absence of except Of the statement try Use in statement else sentence , It can cause grammatical errors

raise sentence

raise Statement throws a specified exception

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

copyright notice
author[chaoyu],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201301536471519.html

Random recommended