17 Common Mistakes of Python, you have encountered what?

For just getting started Pythoner run the code in the learning process is more or less will encounter some errors, the beginning may seem more strenuous. With the accumulation amount of code, practice makes perfect when encountered some problems can quickly locate run-time error when the original title. The following finishing the 17 common mistakes, hoping to help to you

 

1、

Forget that if, for, def, elif, else, class and other end statement added:

It will lead to "SyntaxError: invalid syntax" as follows:

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

 

 

2、

Use = instead of ==

It can lead to "SyntaxError: invalid syntax"

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

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

 

 

3、

Improper use Indent

导致“IndentationError:unexpected indent”、“IndentationError:unindent does not match any outer indetation level”以及“IndentationError:expected an indented block”

Remember indentation in order to increase only: after the end of the statement, and then must be restored to the previous indentation. This error occurs when the following code:

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

 

 

or:

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

 

 

4、

In the for loop statement forget to call len ()

导致“TypeError: 'list' object cannot be interpreted as an integer”

Usually you want to iterate over the elements of a list or string through the index, you need to call this range () function. Remember to return len value instead of returning to this list.

This error occurs when the following code:

= from spam [ ' CAT ' , ' Dog ' , ' Mouse ' ]
 for i in the Range (from spam):
   Print (from spam [i])
 # Xiao Bian finishing a set of Python data and PDF, you need to learn Python learning materials can be added to the group : 631 441 315, anyway idle is idle it, it is better to learn a lot friends ~ ~

 

 

 

 

5、

Attempts to modify the value of the string

导致“TypeError: 'str' object does not support item assignment”

a type of the data string is immutable, the error occurs in the code as follows:

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

 

 

The correct approach is:

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

 

 

6、

Attempts to connect to a non-string values ​​and string

导致 “TypeError: Can't convert 'int' object to str implicitly”

This error occurs when the following code:

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

 

The correct approach is:

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

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

 

 

7、

Quoted in the string end to forget

导致“SyntaxError: EOL while scanning string literal”

This error occurs when the following code:

print(Hello!')

print('Hello!)

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

 

 

8、

Variable or function name misspelled

导致“NameError: name 'fooba' is not defined”

This error occurs when the following code:

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

spam = ruond(4.2)

spam = Round(4.2)

 

 

9、

Method name misspellings

导致 “AttributeError: 'str' object has no attribute 'lowerr'”

This error occurs when the following code:

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

 

 

10、

Exceeding maximum reference index list

导致“IndexError: list index out of range”

This error occurs when the following code:

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

 

 

11、

Use a dictionary key does not exist

Cause "KeyError: 'spam'"

This error occurs when the following code:

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

 

 

12、

Try to use the Python keyword as a variable name

导致“SyntaxError:invalid syntax”

Python key variable names can not be used, the error occurs in the code as follows:

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、

Operator using the value defined in a new variable

导致“NameError: name 'foobar' is not defined”

Do not declare a variable used in the empty string or 0 as the initial value, so that the use of an increment operator of spam + = 1 equals spam = spam + 1, which means spam specify a valid initial value.

This error occurs when the following code:

spam = 0
spam += 42
eggs += 42

  

 

14、

Local variables used in the function prior to define local variables (in this case has the same name as a global variable and a local variable exists)

导致“UnboundLocalError: local variable 'foobar' referenced before assignment”

When using a local in a function change to that and at the same time there is the same name as a global variable is very complex, using rule is: If you define anything in the function, if it is only used in the function that it is local, the contrary is global variable.

This means that you can not define it before using it as a global variable in the function.

This error occurs when the following code:

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

 

 

15、

 

Try to use the range () to create a list of integers

导致“TypeError: 'range' object does not support item assignment”

Sometimes you want to get an ordered list of integers, so the range () appears to be a good way to generate this list. However, you need to remember range () returns "range object", rather than the actual value of the list.

This error occurs when the following code:

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

 

Correct wording:

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

 

(Note: in the Python 2 spam = range (10) can do is, because in the Python 2 range () returns the list of value, but it will produce more than an error in Python 3)

 

16、

Increment and decrement - ++ or absent.

导致“SyntaxError: invalid syntax”

If you are used to other languages ​​such as C ++, Java, PHP, etc., you might want to try using the + or - increment decrement a variable. In Python is no such operator.

This error occurs when the following code:

spam = 1
spam++

 

Correct wording:

spam = 1
spam += 1

 

 

17、

Forget the first argument for the method of adding the self argument

导致“TypeError: myMethod() takes no arguments (1 given)”

This error occurs when the following code:

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

 

Guess you like

Origin www.cnblogs.com/qingdeng123/p/11323931.html