Common errors and try-except usage in Python

Source: Internet
Author: User
Tags float number

1. Common Mistakes

We will appear in the process of using Python:

(1) SyntaxError syntax error.

(2) Indentationerror indentation error.

(3) nameerror variable undefined error.

(4) TypeError type error.

2. Handling Exceptions

We use Try...except to handle exceptions:

Basic syntax:

Try

Segment

Except

Segment

Executes the TRY clause first, and if no exception occurs, the EXCEPT clause does not execute. If an exception occurs executing a try clause, the clause is ignored and the corresponding except clause is executed if the exception matches the specified exception type after the except keyword. Then continue executing the code after the try statement.

If the corresponding processing statement is not found, the program terminates.

Def get_number ():    "Returns a float number"    number=float (Input ("Enter a float Number:"))    return Numberwhile True:    Try:        print (Get_number ())    except ValueError:        print ("You entered a wrong value.")

When we enter a floating-point number, the floating-point number is output. When we enter a letter, throw ValueError, when we press CTRL + C, causing keyboardinterrupt, this exception is not captured in except, so the program is terminated.

Common errors and try-except usage in Python

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.