Python Base---exception

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.