Errors that are easy to get started with Python

Source: Internet
Author: User
Php Chinese network (www.php.cn) provides the most comprehensive basic tutorial on programming technology, introducing HTML, CSS, Javascript, Python, Java, Ruby, C, PHP, basic knowledge of MySQL and other programming languages. At the same time, this site also provides a large number of online instances, through which you can better learn programming... This error occurs when a newbie first learns the Python language. we have made some summary here, hoping to give some attention to his friends who are just learning Python.

Syntax error

Syntax errors may be the most common errors when you are still learning Python.

>>> while True print "hi~"  File "
 
  ", line 1      while True print "hi~"               ^SyntaxError: invalid syntax
 

There is an arrow pointing to the first error found, which points to print, because the colon is missing after Ture.

If, elif, else, for, while, class, def is added at the end of the declaration: (resulting in "SyntaxError: invalid syntax"), this error will occur in code similar to the following:

if spam == 42 print('Hello!')

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

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

The number of indentions is incorrect. (Resulting in "IndentationError: unexpected indent", "IndentationError: unindent does not match any outer indetation level", and "IndentationError: expected an indented block") remember to add indentation only in: after the statement is ended, it must be restored to the original 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!')

In the for loop statement, you forget to call len () (resulting in "TypeError: 'list' object cannot be interpreted as an integer ") generally, you want to iterate a list or string element through an index. you need to call the range () function. Remember to return the len value instead of the list. This error occurs in the following code:

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

Try to modify the value of string (resulting in "TypeError: 'str' object does not support item assignment") string is an unchangeable data type, which occurs in the following code:

spam = 'I have a pet cat.' spam[13] = 'r' print(spam)

But you actually want to do this:

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

Try to connect a non-string value to a string (resulting in "TypeError: Can't convert 'int' object to str implicitly") This error occurs in the following code:

numEggs = 12 print('I have ' + numEggs + ' eggs.')

But you actually want to do this:

numEggs = 12 print('I have ' + str(numEggs) + ' eggs.')

Or:

 numEggs = 12 print('I have %s eggs.' % (numEggs))

This error occurs in the following code:

Print (Hello! ') Or: print ('hello !)

Or:

myName = 'Al' print('My name is ' + myName + . How are you?')

Variable or function name spelling error (resulting in "NameError: name 'fooba' is not defined") occurs in the following code:

foobar = 'Al' print('My name is ' + fooba)

Or:

spam = ruond(4.2)

Or:

spam = Round(4.2)

Method name spelling error (resulting in "AttributeError: 'str' object has no attribute 'lowerr'") occurs in the following code:

spam = 'THIS IS IN LOWERCASE.' spam = spam.lowerr()

Exception

An error may occur during execution even if the statement and expression syntax are correct. this error is called Exceptions ). Exceptions are not all fatal. you will soon learn how to handle them. Many exception programs do not handle this, but return an error message, for example:

>>> 10 * (1/0)Traceback (most recent call last):  File "
 
  ", line 1, in 
  
   ZeroDivisionError: integer pision or modulo by zero>>> 4 + git*3Traceback (most recent call last):  File "
   
    ", line 1, in 
    
     NameError: name 'git' is not defined>>> '2' + 1Traceback (most recent call last):  File "
     
      ", line 1, in 
      
       TypeError: cannot concatenate 'str' and 'int' objects>>>
      
     
    
   
  
 

The last line of the error message is the exception message, which is the exception type before the colon. The preceding ZeroDivisionError, NameError, and TypeError are built-in system exceptions.

Exception handling

You can write a program to handle exceptions. for example, in the following example, an exception is returned until the user inputs valid data.

>>> while True:...     try:...         x = int(raw_input("Please enter a number: "))...         break...     except ValueError:...         print "Oops! That was no valid number. Try again..."... Please enter a number: xOops! That was no valid number. Try again...Please enter a number: 32xOops! That was no valid number. Try again...Please enter a number: 038

Use try and ExceptionName to handle exceptions

If no exception occurs, the segment T will be skipped.

If an exception occurs somewhere, the subsequent statements will be skipped. if the generated exception type is the same as the type after T, the statement after except will be executed.

If an exception occurs, but it is different from the type after snapshot T, the exception will be passed out of the try statement. If no corresponding processing is performed, the information like in the previous example will be printed.

A try statement may have multiple corresponding T types to handle different types of exceptions. at most one type of exception can be executed. A struct T can contain multiple types of names, such:

... except (RuntimeError, TypeError, NameError):...     pass

Note that the preceding three exception types must be enclosed in parentheses, because in modern python, struct T ValueError, e means struct T ValueError as e: (What will this mean later)

The last primary T is generally not named and used to handle other cases.

import systry:    f = open('myfile.txt')    s = f.readline()    i = int(s.strip())except IOError as e:           print "I/O error({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

The try. sort T statement can also use else, for example

for arg in sys.argv[1:]:         try:        f = open(arg, 'r')       except IOError:                   print 'cannot open', arg       else:                   print arg, 'has', len(f.readlines()), 'lines'        f.close()

Note that once else is used, there must be an else after each handle T. This method is used to specify what operations are not performed for an exception.

The alias T clause can specify parameters after the exception name. These parameters are stored in the instance. arg when an exception instance is generated.

>>> 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... 
 
  ('spam', 'eggs')('spam', 'eggs')x = spamy = eggs
 

Exception handling not only handles exceptions that occur directly in try, but also can handle exceptions that call functions in try.

>>> def mp():...     x = 1/0... >>> try:...     mp()... except ZeroDivisionError as detail:...      print 'Handling run-time error:', detail... Handling run-time error: integer pision or modulo by zero

User-defined exception

The program can create an Exception class to run a new Exception. this Exception class needs to be derived from the Exception class directly or indirectly.

>>> 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 call last):  File "
 
  ", line 1, in 
  
   __main__.MyError: 'oops!'
  
 

In the above example, __init _ () overwrites the default init function. the new behavior creates the value attribute, replacing the original behavior of creating the args attribute.

You can do anything other classes can do by defining the Exception class. However, the Exception classes are always designed to be very simple. they provide some attributes, so that these attributes can be conveniently extracted during error processing. When a module is designed to handle multiple exceptions, a basic class is often defined first, and other classes are used to handle some special situations.

class Error(Exception):        """Base class for exceptions in this module."""    pass    class InputError(Error):        """Exception raised for errors in the input.        Attributes:               expr -- input expression in which the error occurred               msg  -- explanation of the error    """    def __init__(self, expr, msg):               self.expr = expr               self.msg = msgclass TransitionError(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 why the specific transition is not allowed           """    def __init__(self, prev, next, msg):                self.prev = prev                self.next = next        self.msg = msg

Use local variables in the function before defining local variables

(At this time, a global variable with the same name as a local variable exists) (resulting in "UnboundLocalError: local variable 'foobar' referenced before assignment ") it is very complicated to use local variables in a function and there are global variables with the same name at the same time. The rule is as follows: if a function defines anything, if it is used only in functions, it is local, and vice versa. This means that you cannot use it as a global variable in the function before defining it. This error occurs in the following code:

someVar = 42 def myFunction():    print(someVar)    someVar = 100    myFunction()

Try to use range () to create an integer list

(Resulting in "TypeError: 'range' object does not support item assignment") sometimes you want to get an ordered integer list, so range () seems to be 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(10) spam[4] = -1

Maybe this is what you want to do:

spam = list(range(10)) spam[4] = -1

(Note: In Python 2, spam = range (10) can work, because range () in Python 2 returns the list value, but the above errors will occur in Python 3)

The error is caused by the ++ or -- Auto-incrementing auto-subtraction operator.

(Resulting in "SyntaxError: invalid syntax") if you are used to other languages such as C ++, Java, and PHP, you may want to use ++ or -- Auto-increment to subtract a variable. There is no such operator in Python. This error occurs in the following code:

spam = 1spam++

Maybe this is what you want to do:

spam = 1 spam += 1

You forgot to add the self parameter to the first parameter of the 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.