1.try-except code block
Try
Print (5/0)
Except Zerodivisionerror:
Print ("You can ' t divide by zero!")
Exceptions are handled using the TRY-EXCEPT code block. The try-except code block lets python perform the specified action and tells Python what to do if an exception occurs. When you use the TRY-EXCEPT code block, the program can continue to run even if an exception occurs.
2.else code block
Print ("Please give me Numbers")
Print ("I ll divide them")
While True:
A=input ("Please input a number:")
If a = = ' Q ':
Break
B=input ("Please input another number:")
Try
Answer=int (a)/int (b)
Except Zerodivisionerror:
Print ("B cannot be 0")
Else
Print (answer)
We let Python try to execute the division operation in a try code block that contains only the code that could cause the error. Code that relies on the try code block to execute successfully is placed in the Else code block: In this case, if the division succeeds, we use the Else code block to print the result.
3. If you do not make any prompts when the program is abnormal, you can use the PASS statement.
Try
Print (5/0)
Except Zerodivisionerror:
Pass
4. Storing data
Def greet_user ():
File_name= ' Greet.json '
Try
With open (file_name) as File_object:
Username=json.load (File_object)
Except Filenotfounderror:
Username=input ("Please input your name:")
With open (file_name, ' W ') as File_object:
Json.dump (Username,file_object)
Print ("We'll Remember You" come back, "+username+"! ")
Else
Print ("Welcome back!" +username)
Greet_user ()
The function json.dump () receives two arguments: the data to be stored and the file object that can be used to store the data.
Json.dump (Username,file_object)
The function json.load () loads the information stored in the File_object.
Username=json.load (File_object)
Python Base---exception