Import:
LIB module files can be imported directly, if not to indicate the path
Import Class_test #具体到模块名
Class_test.add (2, 5)
Import specific to function name
From Class_test Import Add, Sub, ...
Add (5, 6)
The test code is placed below the IF
if __name__ = = ' __main__ ': #执行程序的主入口
Print ("Nice weather today!") ") # Executes the code only when you execute the code under the current module
Import time
Time.sleep (4)
Exception Handling in Python code
Exception: Error when code is running
If not processed, subsequent programs are interrupted.
1. Simplest usage Try ... except
Try: Put the code that you think is problematic, put the monitoring code
Except catching errors and handling them
First usage: Catch error, do not process
Try
Print (a)
Except: # Catch Error
Pass # Pass do nothing, ignore, release
Print ("Hello, World")
Second usage: simple handling of errors
Try
Print (a)
Except
Print ("error!!! ") Error after catching errors
Print ("Hello, World")
Third use: Print out specific errors
Try
Print (a)
Except Exception as E: #中央空调
Print ("Error:%s"% e)
Print ("Hello, World")
Nameerror ()
Try
Print (a)
Except Nameerror as E: # small Sun
Print ("Error:%s"% e)
Print ("Hello, World")
Fourth usage: try...except...finally
Try
Print (a)
Except Indexerror as E: # small Sun
Print ("Error:%s"% e)
Finally: #无论是否能捕捉到错误, the program after finally runs
Print ("Hello, World")
# Uses: Generally we use in file or database resources processing
Try
File = open (' Test.txt ', ' W ')
File.read ()
Except Exception as E:
Print ("Error:%s"% e)
Finally
File.close ()
Fifth usage: Try...except...else
Try
A = 4
B
Except Exception as E:
Print ("Error:%s"% e)
Else: # will continue to execute only if the try does not make an error
Print (a)
# The fifth way to use
# Context Manager with...as
With open ("Test.txt", ' W ') as file:
File.write ("It's a nice Day")
Print ("Inside with Code", file.closed)
Print (file.closed) # Boolean value
# When do you use it? MySQL, txt file resource
Python's try...except ... Error trapping