Python beginners learn common mistakes

When first learning Python, trying to understand the meaning of Python's error messages can be a bit complicated. Here is a list of common runtime errors that can crash your program.

1) Forgot to  add: at the end of 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 == 42
    print('Hello!')
 

2) Use = instead of == (results in " SyntaxError: invalid syntax ")

= is an assignment operator and == is an equality comparison. The error occurs in the following code:

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

 

3) Wrong use of indentation. (resulting in " IndentationError: unexpected indent ", " IndentationError: unindent does not match any outer indetation level ", and " IndentationError: expected an indented block ")

Remember that indentation increments are only used after statements ending in :, and must then revert to the previous indentation format. The error occurs in the following code:

print('Hello!')
    print('Howdy!')

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

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

 

4) Forgot to call len() in the  for  loop statement   (resulting in " TypeError: 'list' object cannot be interpreted as an integer ")

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

The error occurs in the following code:

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

 

5) Attempt to modify the value of string (resulting in " TypeError: 'str' object does not support item assignment ")

string is an immutable data type and the error occurs in code like this:

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)

 

6) Attempt to concatenate non-string value with string (results in " TypeError: Can't convert 'int' object to str implicitly ")

The error occurs in the following code:

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

 

And you actually want to do this:

numEggs = 12print('I have ' + str(numEggs) + ' eggs.')
or:
numEggs = 12print('I have %s eggs.' % (numEggs))
 

7) Forgetting to put quotes at the beginning and end of the string (resulting in " SyntaxError: EOL while scanning string literal ")

The error occurs in the following code:

print(Hello!')
or:
print('Hello!)

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

8) The variable or function name is misspelled (resulting in " NameError: name 'fooba' is not defined ")

The error occurs in the following code:

foobar = 'Al'print('My name is ' + fooba)
or:
spam = ruond (4.2)
or:
spam = Round(4.2)
 

9) Method name misspelled (resulting in " AttributeError: 'str' object has no attribute 'lowerr '")

The error occurs in the following code:

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

 

10) The reference exceeds the maximum index of the list (resulting in " IndexError: list index out of range ")

The error occurs in the following code:

spam = ['cat', 'dog', 'mouse']
print(spam[6])

 

11) Using a dictionary key that doesn't exist (results in "KeyError: 'spam'")

The error occurs in the following code:

spam = {'cat': 'Zophie', 'dog': 'Basil', 'mouse': 'Whiskers'}
print('The name of my pet zebra is ' + spam['zebra'])

 

12) Attempting to use Python keywords as variable names (results in " SyntaxError: invalid syntax ")

Python keys cannot be used as variable names, the error occurs in code like this:

class = 'algebra'

Python3的关键字有: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, yield

 

13) Using the increment operator in a variable that defines a new variable (results in " NameError: name 'foobar' is not defined ")

Do not use 0 or an empty string as an initial value when declaring a variable, so that a sentence using the auto-increment operator spam += 1 is equal to spam = spam + 1, which means that spam needs to specify a valid initial value.

The error occurs in the following code:

spam = 0spam += 42eggs += 42

 

14) Use a local variable in a function before defining a local variable (there is a global variable with the same name as the local variable at this time) (resulting in " UnboundLocalError: local variable 'foobar' referenced before assignment ")

It's complicated to use a local variable in a function while there is a global variable of the same name. The rule of use is: if anything is defined in the function, if it's only used in the function then it's local, otherwise it's global variable.

This means you can't use it as a global variable in a function before defining it.

The error occurs in the following code:

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

 

15) Attempting to use range() to create a list of integers (results in " TypeError: 'range' object does not support item assignment ")

Sometimes you want to get 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 an actual list value.

The 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: spam = range(10) works in Python 2 because range() returns list values ​​in Python 2, but in Python 3 the above error will occur)

 

16) Nice in ++ or — increment and decrement operators. (results in " SyntaxError: invalid syntax ")

If you're used to other languages ​​like C++, Java, PHP, etc., maybe you'll want to try using ++ or - incrementing/decrementing a variable. There is no such operator in Python.

The error occurs in the following code:

spam = 1spam++

Maybe this is what you want to do:

spam = 1spam += 1

17) Forgot to add the self parameter to the first parameter of the method (resulting in "TypeError: myMethod() takes no arguments (1 given)")

The error occurs in the following code:

class Foo(): def myMethod(): print('Hello!') a = Foo() a.myMethod()

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325329534&siteId=291194637