17 common mistakes novice, beginner Python give you!

When he did not learn Python, meaning the error message you want to understand Python may be a bit complicated. Here are some common programs let you crash a runtime error.

1) Forget added at the end if, elif, else, for, while, class, def statement :( lead to "SyntaxError: invalid syntax")

This error occurs in a similar code is as follows:

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

2) instead of using == = (resulting in "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. (Resulting in "IndentationError: unexpected indent", "IndentationError: unindent does not match any outer indetation level" and "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!')

或者:

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

4) In the for loop statement forget to call len () (results in "TypeError: 'list' object can not 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:

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

5) attempts to modify the value of the string (resulting in "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)

And you actually want to do this:

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

6) attempts to connect to a non-string value string (resulting in "TypeError: Can not convert 'int' object to str implicitly")

This error occurs when the following code:

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

And you actually want to do this:

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

or:

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

7) end to end forget quoted string (resulting in "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 (resulting in "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) the method name misspelled (resulting in "AttributeError: 'str' object has no attribute 'lowerr'")

This error occurs when the following code:

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

10) cited more than list the maximum index (resulting in "IndexError: list index out of range")

This error occurs when the following code:

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

11) using the key does not exist in the dictionary (resulting in "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 (cause "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) using a value in defining new operator variable (resulting in "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) prior to the definition of local variables used in the function local variable (in this case has the same name as a global variable and a local variable is present) (resulting in "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 (resulting in "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

Perhaps this is what you want to do:

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) Yes ++ or - increment and decrement. (Resulting in "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++

Perhaps this is what you want to do:

spam = 1
spam += 1

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

This error occurs when the following code:

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

In the process of learning Python, many small partners often because there is no information or guidance resulting in no one do not want to learn anymore, so I had prepared a large number of PDF books, video tutorials, this skirt plus years plus 592 539 176 are free to everyone! Whether you are a zero-based foundation can still get into their corresponding learning package! Including Python software tools and the latest entry to the combat tutorial 2019

Guess you like

Origin www.cnblogs.com/chengxyuan/p/12653790.html