Common error prompts for python beginners

When you run or write a program and encounter an error exception, Python gives you the name of the error class to tell you what the problem is. (Python is an object-oriented language, so the exception thrown by the program is also a class.) It is very helpful to have a good understanding of the meaning represented by the class name of these error messages, which can help you find the problem in the fastest time, so as to solve the problems in the program. We’ve collected some of python’s most important built-in exception class names and briefly introduced them:

AttributeError: an AttributeError that is raised when a feature reference or assignment fails

NameError: The variable name you are trying to access does not exist

SyntaxError: SyntaxError, code form error

Exception: The base class for all exceptions. Since all Python Exception classes are a member of the Exception base class, exceptions are inherited from Exception and are defined in the Exceptions module.

IOError: IOError is usually raised when a file is opened that does not exist. It can also be interpreted as an output input error

KeyError: A keyword error raised when a key (key) that does not exist in the map is used

IndexError: IndexError. The used index does not exist

TypeError: TypeError, which is raised when a built-in operation or function should be on an object of the wrong type

ZeroDivisonError: The divisor is 0. This error is raised when the second argument is 0 in a division operation

ValueError: Incorrect type of argument passed to an object, such as a string argument to int().

1, forget to add: at the end of the if, elif, else, for, while, class,def declaration.

This error will occur in code similar to the following:

if spam == 42 print('Hello! **SyntaxError: invalid syntax**Copy the code
2, use = instead of ==.

= is the assignment operator and == is the equal comparison operation. This error occurs in the following code:

if spam = 42: print('Hello! **SyntaxError: invalid syntax**Copy the code
3. Incorrect use of indentation.

Remember that indentation only follows statements ending with:, after which it must revert to the previous indentation format. This error occurs in the following code:

if spam == 42: print('Hello! ') print('Howdy! **IndentationError: unindent does not match any outer indentation level**Copy the code

Or:

if spam == 42: print('Hello! **IndentationError: unindent does not match any outer indentation level**Copy the code
4. Forget to call len() in the for loop.

Usually you want to iterate over a list or string by index, calling the range() function. Remember to return len instead of the list.

This error occurs in the following code:

Spam = ['cat','dog', 'mouse'] for I inrange(spam): print(spam[I]Copy the code
5, try to change the value of string.

String is an immutable data type. This error occurs in code like this:

**TypeError: 'STR' object does not support item Assignment **Copy the code

What you actually want to do is:

spam = 'I have apet cat.'​
spam = spam[:13] +'r' + spam[14:]​
print(spam)
Copy the code
6. Try to concatenate a non-string value with a string.

This error occurs in the following code:

TypeError: can only concatenate STR (not "int") to STR **TypeError: Can only concatenate STR (not "int") to STR **Copy the code

What you actually want to do is:

numEggs = 12

print('I have ' +str(numEggs) + ' eggs.')
Copy the code

Or:

numEggs = 12

print('I have %seggs.' % (numEggs))
Copy the code
7. Forgetting to enclose quotation marks at the beginning and end of a string.

This error occurs in the following code:

print(Hello Python! **SyntaxError: invalid syntax**Copy the code

Or:

print('Hello Python!) **SyntaxError: invalid syntax**Copy the code

Or:

myName = 'Python' print('My name is '+ myName + . How are you? **SyntaxError: invalid syntax**Copy the code
Incorrect spelling of variable or function names.

This error occurs in the following code:

**NameError: name 'fooba' is not defined**Copy the code

Or:

NameError: name 'ruond' is not defined**Copy the code

Or:

**NameError: name 'Ruond' is not defined**Copy the code
Incorrect spelling of method name.

This error occurs in the following code:

**AttributeError: 'STR' object has no attribute 'lowerr'**Copy the code
10, reference more than list maximum index.

This error occurs in the following code:

Spam = ['cat','dog', 'mouse'] print(spam[6]Copy the code
11. Use nonexistent dictionary keys.

This error occurs in the following code:

Spam = {'cat':'Zophie', 'dog': 'Basil', 'Mouse ':' Whiskers'} print('The name ofmy pet zebra is' + spam['zebra']) **KeyError: 'zebra'**Copy the code
12. Try using Python keywords as variable names.

Python keys cannot be used as variable names. This error occurs in code like this:

**SyntaxError: Invalid syntax** Python keyword is:  and, as, assert, break, class, continue, def, del, elif,else, except, False, finally, for, from, global, if, import, in, is, lambda,None, nonlocal, not, or, pass, raise, return, True, try, while, with, yieldCopy the code
13. Use value-added operators in a defined new variable.

Do not use 0 or an empty string as an initial value when declaring a variable, as a statement of spam += 1 using the increment operator equals spam = spam + 1, which means that spam needs to specify a valid initial value.

This error occurs in the following code:

**NameError: name 'eggs' is not defined** spam = 0 spam += 42 EGGS += 42Copy the code
14. Use a local variable in a function before defining it (a global variable with the same name as the local variable exists).

This error occurs in the following code:

Def myFunction(): print(someVar) someVar (): print(someVar) someVar () Local variable 'someVar' referenced before Assignment ** ** It is complicated to use a local variable in a function that also has a global variable of the same name. If anything is defined in a function, it's local if it's only used in a function, and global if it's not. This means you can't use it as a global variable in a function before you define it. **Copy the code
15. Try using range() to create a list of integers.

Sometimes you want an ordered list of integers, so range() seems like a good way to generate this list. However, you need to remember that range() returns a “range object”, not the actual list value.

This error occurs in the following code:

**TypeError: 'range' object does not support itemAssignment **Copy the code

Maybe this is what you want to do:

Spam =list(range(10)) spam[4] = -1 ** Spam = range(10) works in Python 2 because range() returns a list, but in Python 3 it generates the above error **Copy the code
16, good in ++ or — increment and decrement operators.

If you’re used to other languages such as C++, Java, PHP, etc., you might want to try using ++ or — incrementing or decrement a variable. There is no such operator in Python.

This error occurs in the following code:

**SyntaxError: invalid syntax**Copy the code

Maybe this is what you want to do:

spam = 1

spam += 1
Copy the code
17. Forget to add self to the first argument of the method.

This error occurs in the following code:

class Foo(): def myMethod(): print('Hello! **TypeError: myMethod() takes 0 positional arguments but 1 was given**Copy the code

The above is a small editor to sort out some common novice error tips.

As a veteran Python programmer, Xiaobian also organized a set of learning programs, from the most basic Python scripts to Web development, crawlers, data analysis, data visualization, machine learning, etc.

These information have want partner can click to join learning