Bugs that are prone to beginners when they first start learning python

Source: Internet
Author: User
Tags integer division
When beginners start learning the Python language, there will be errors like this, and we've done some summarizing here, hoping to give a little bit of attention to the friends who just started learning python.

Syntax error

Syntax errors are probably the most common mistakes you're still learning about Python

>>> while True print "hi~"  File "<stdin>", line 1 while      true print "hi~"               ^syntaxerror:invalid Syntax

There is an arrow pointing to the first place where the error was found, pointing to print, because the colon is missing from the ture

Forget to add at the end of the IF, elif, else, for, while, class, Def declarations: (resulting in "syntaxerror:invalid syntax") The error will occur in code similar to the following:

if spam = = Print (' hello! ')

Use = instead of = = (resulting in "syntaxerror:invalid syntax") = is the assignment operator and = = is equal to the comparison operation. This error occurs in the following code:

If spam = 42:print (' hello! ')

The amount of indentation used for the error. (resulting in "indentationerror:unexpected indent", "Indentationerror:unindent does not match any outer indetation level" and " Indentationerror:expected an indented block ") remember that the indent increment is used only after the statement that ends with: and then must revert to the previous indent format. This error occurs in the following code:

Print (' hello! ')    Print (' howdy! ')

Or:

if spam = = 42:print (' hello! ') print (' howdy! ')

Or:

if spam = = 42:print (' hello! ')

Forget to call Len () in the FOR Loop statement (cause "TypeError: ' List ' object cannot be interpreted as an integer") usually you want to iterate over an element of a list or string by index, which requires Call the range () function. Remember to return the Len value instead of returning the list. This error occurs in the following code:

Spam = [' Cat ', ' dog ', ' mouse '] for I in range (spam):      print (Spam[i])

attempt to modify the value of string (resulting in "TypeError: ' str ' object does not a support item assignment") string is an immutable data type that occurs in the following code:

Spam = ' I have a pet cat. ' Spam[13 ' = ' r ' Print (spam)

And you actually want to do this:

Spam = ' I have a pet cat. ' spam = Spam[:13] + ' r ' + spam[14:] Print (spam)

Attempting to concatenate a non-string value with a string (resulting in "Typeerror:can ' t convert ' int ' object to str implicitly") This error occurs in the following code:

Numeggs = Print (' I have ' + Numeggs + ' eggs. ')

And you actually want to do this:

Numeggs = Print (' I have ' + str (numeggs) + ' eggs. ')

Or:

Numeggs = Print (' I have%s eggs. '% (Numeggs))

Forgetting the quotation marks at the end of a string (resulting in "syntaxerror:eol while scanning string literal") This error occurs in the following code:

Print (hello! ') or: print (' hello!)

Or:

MyName = ' Al ' Print (' My name is ' + MyName +. How is it? ')

The variable or function name is misspelled (resulting in "nameerror:name ' Fooba ' is not defined") This error occurs in the following code:

Foobar = ' Al ' Print (' My name is ' + Fooba)

Or:

Spam = Ruond (4.2)

Or:

Spam = Round (4.2)

The method name is misspelled (resulting in "attributeerror: ' str ' object has no attribute ' Lowerr ') This error occurs in the following code:

Spam = ' This was in lowercase. ' Spam = Spam.lowerr ()

Abnormal

Even if the syntax of the statement and expression is correct, an error may occur at execution time, which is known as an exception (Exceptions). Exceptions are not all deadly, and you will soon learn how to deal with them. Many exception programs do not process, but instead return an error message, for example:

>>> (1/0) Traceback (most recent):  File "<stdin>", line 1, in <module>zerodivisione  Rror:integer division or modulo by zero>>> 4 + git*3traceback (most recent call last):  File "<stdin>", Line 1, in <module>nameerror:name ' git ' isn't defined>>> ' 2 ' + 1Traceback (most recent call last):  F Ile "<stdin>", line 1, in <module>typeerror:cannot concatenate ' str ' and ' int ' objects>>>

The last line of the error message is the exception message, which is the type of the exception before the colon. The above Zerodivisionerror, Nameerror, TypeError, are all system-built exceptions.

Handling Exceptions

You can write your own program to handle exceptions, such as the following example, which returns an exception until the user enters valid data.

>>> while True: ...     Try:         ... x = Int (raw_input ("Please enter a number:"))         ... Break ...     Except ValueError:         ... Print "oops! That is no valid number. Try again ... "... Please enter a number:xoops! That is no valid number. Try again ... Please enter a number:32xoops! That is no valid number. Try again ... Please enter a number:038

Using try and except exceptionname to handle exceptions

If no exception is generated, the except segment is skipped

If there is an exception, the subsequent statement will be skipped, and if the resulting exception type is the same as the type after except, the except statement will be executed

If an exception occurs, but is inconsistent with the type after except, the exception is passed to the outside of the try statement, and if there is no corresponding processing, then a message like the previous example is printed.

A try statement may have more than one except corresponding to each of the different types of exceptions, with at most one processing being executed. A except can contain more than one type name, such as:

... except (RuntimeError, TypeError, nameerror): ...     Pass

Note that the above three types of exceptions must be enclosed in parentheses, because in modern Python, except ValueError, E means except ValueError as E: (what does that mean later)

The last except typically does not specify a name to handle the rest of the situation

Import Systry:    f = open (' myfile.txt ')    s = f.readline ()    i = Int (S.strip ()) except IOError as E:           print "I/O Rror ({0}): {1} ". Format (E.errno, e.strerror) except ValueError:           print" Could not convert data to an integer. " Except:           print "Unexpected error:", Sys.exc_info () [0]           raise

Try: The except statement can also choose to use else, for example

For ARG in sys.argv[1:]:         try:        f = open (arg, ' R ')       except IOError:                   print ' cannot open ', arg       else:< C12/>print arg, ' has ', Len (F.readlines ()), ' Lines '        f.close ()

It is important to note that once you use else, each except has an else, which is used to specify what to do if an exception does not occur.

The EXCEPT clause can specify parameters after the exception name, which are stored when the exception instance is generated Instance.arg

>>> Try:     ... Raise Exception (' spam ', ' eggs ') ... except Exception as inst: ...     Print type (inst)     ... Print Inst.args     ... Print Inst     ... X, y = Inst.args     ... print ' x = ', x ...     print ' y = ', y ... <type ' exceptions. Exception ' > (' spam ', ' eggs ') (' spam ', ' eggs ') x = Spamy = Eggs

Exception handling not only handles exceptions that occur directly in the try, but also handles the exception that invokes the function in the try

>>> def mdiv ():     ... x = 1/0 ... >>> Try:     ... MDiv () ... except zerodivisionerror as detail: ...      print ' Handling run-time error: ', detail ... Handling Run-time Error:integer division or modulo by zero

User-defined exceptions

The program can command a new exception by creating an exception class that needs to be derived directly or indirectly by the Exception class.

>>> class Myerror (Exception): ...     def __init__ (self, value): ...          Self.value = value ...     def __str__ (self): ...          return repr (self.value) ... >>> try: ...     Raise Myerror (1+5) ... except Myerror as e: ...     print ' My exception occurred, value: ', E.value ... My exception occurred, value:6>>> raise Myerror (' oops! ') Traceback (most recent):  File "<stdin>", line 1, in <module>__main__. Myerror: ' oops! '

In the above example, __ init __ () overrides the default Init function, and the new behavior creates the Value property, replacing the original behavior of creating the Args property.

Other classes can do things that can be done by defining the exception class. However, the exception class is always designed to be very simple, and they provide properties that can be easily extracted from error handling. When designing a module to handle multiple exceptions, it is often necessary to define a basic class, and other classes to deal with some special cases on this basis.

class Error (Exception): "" "," "" "" "" "" "        Pass Class Inputerror (Error): "" "Exception raised for errors in the input. attributes:expr--input expression in which the error occurred MSG--explanation of the ER Ror "" "Def __init__ (self, Expr, msg): self.expr = Expr self.msg = Msgclass Transitioner                  Ror (Error): "" "raised when an operation attempts a state transition that's not allowed.                  Attributes:prev-State at beginning of transition next--attempted new state MSG--Explanation of the specific transition is not allowed "" "Def __init__ (self, prev, NEX T, msg): Self.prev = prev Self.next = Next self.msg = Msg 

Using local variables in a function before defining local variables

(There is a global variable with the same name as the local variable) (resulting in "unboundlocalerror:local variable ' foobar ' referenced before assignment") It is very complicated to use a local variable to that in a function and a global variable with the same name at the same time: if anything is defined in the function, it is local if it is used only in the function, and the other is the global variable. This means that you cannot define it before you use it as a global variable in a function. This error occurs in the following code:

Somevar = def myFunction ():    print (somevar)    Somevar =    myFunction ()

Try to create an integer list using range ()

(Causes "TypeError: ' Range ' object does not supported item assignment") Sometimes you want an ordered list of integers, so range () looks like a good way to generate this list. However, you need to remember that range () returns "Range object" instead of the actual list value. This error occurs in the following code:

Spam = Range (ten) spam[4] = 1

Maybe that's what you want to do:

Spam = List (range) Spam[4] = 1

(Note: In python 2, spam = Range (10) is OK because the range () in Python 2 returns a list value, but in Python 3 the above error is generated)

Wrong at + + or--self-increment decrement operator.

(resulting in "syntaxerror:invalid syntax") If you are accustomed to other languages such as C + +, Java, PHP, and so on, you might want to try using + + or--self-increment to subtract a variable. There is no such operator in Python. This error occurs in the following code:

Spam = 1spam++

Maybe that's what you want to do:

Spam = 1 spam + = 1

Forgetting to add the self parameter for the first parameter of a method

(resulting in "typeerror:mymethod () takes no arguments (1 given)") This error occurs in the following code:

Class Foo (): Def myMethod ():        print (' hello! ') a = Foo () A.mymethod ()
  • 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.