17 errors frequently encountered by beginners of python, 17 Errors for beginners of python
1) forget to add (resulting in "SyntaxError: invalid syntax") at the end of the if, elif, else, for, while, class, and def declaration ")
This error will occur in code similar to the following:
if spam== 42 print('Hello!')
2) use = instead of = (resulting in "SyntaxError: invalid syntax ")
= Is the value assignment operator and = is a comparison operation. This error occurs in the following code:
if spam= 42: print('Hello!')
3) 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 after the statement ending with:, and then 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! ')
4) forget to call len () in the for loop Statement (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 iin range(spam): print(spam[i])
5) try to modify the string value (resulting in "TypeError: 'str' object does not support item assignment ")
String is an unchangeable data type. This error 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)
6) try to connect a non-string value with a string (resulting in "TypeError: Can't convert 'int' object to str implicitly ")
This error occurs in the following code:
numEggs= 12print('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 ))
7) add quotation marks at the beginning and end of the string (resulting in "SyntaxError: EOL while scanning string literal ")
This error occurs in the following code:
Print (Hello! ') Or: print ('Hello !) Or: myName = 'al' print ('My name is '+ myName +. How are you? ')
8) misspelling of variables or function names (resulting in "NameError: name 'fooba' is not defined ")
This error occurs in the following code:
Foobar = 'al' print ('My name is '+ fooba) or: spam = ruond (4.2) or: spam = Round (4.2)
9) incorrect method name spelling (resulting in "AttributeError: 'str' object has no attribute 'lowerr '")
This error occurs in the following code:
spam= 'THIS IS IN LOWERCASE.'spam= spam.lowerr()
10) Reference exceeds the maximum list index (resulting in "IndexError: list index out of range ")
This error occurs in the following code:
spam= ['cat','dog','mouse']print(spam[6])
11) use a non-existent dictionary key value (resulting in "KeyError: 'spam '")
This error occurs in 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 the variable name (resulting in "SyntaxError: invalid syntax ")
The key to Python cannot be used as a variable name. This error occurs in the following code:
Class = 'algebr'
Python3 keywords include: and, as, assert, break, class, continue, def, del, elif, else, else t, False, finally, for, from, global, if, import, in, is, lambda, None, nonlocal, not, or, pass, raise, return, True, try, while, with, yield
13) use the value-added operator in a new variable definition (resulting in "NameError: name'foobar' is not defined ")
Do not use 0 or an empty string as the initial value when declaring a variable. In this way, the use of the auto-increment operator spam + = 1 equals spam = spam + 1, this means that spam needs to specify a valid initial value.
This error occurs in the following code:
spam= 0spam+= 42eggs+= 42
14) use a local variable in the function before defining the local variable (a global variable with the same name as the 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= 42def myFunction(): print(someVar) someVar= 100myFunction()
15) 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)
16) Not bad in ++ or -- auto-incrementing auto-subtraction operator. (Cause "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= 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 )")
This error occurs in the following code:
class Foo(): def myMethod(): print('Hello!')a= Foo()a.myMethod()
Print Output Error for python beginners
In python, print is a function.
Add brackets.
For example, print ('n' = ', n) Pay attention to indent.
Python beginners
I don't know if you are familiar with the concept of "class". python is also an object-oriented language, and classes are an object that is everywhere in python.
To illustrate the attributes and methods, I will give you an example as much as possible.
Let's look at a simple one. If you don't apply classes, you can only do some simple programming, such as helloworld:
======================================
# Helloworld. py
Print "hello! World"
======================================
After you run import helloworld (or c: \ python26 \ pyhton.exe helloworld. py), the screen appears.
Hello! World
========================================================== ======================================
========================================================== ======================================
Now, I will apply the "method ".
======================================
# Hw2.py
Def printhello ():
Print "hello! By method"
Def saygoodbye ():
Print "goodbye! "
======================================
Now, the hw2.py file (as a module) has two methods: printhello and saygoodbye.
When we execute import hw2, there will be no response. Because we use "methods" for programming, "Methods won't be executed if they are not called. Of course, if you add other statements before the def line, it will be executed, because those statements do not belong to the method.
Then we enter hw2.printhello ()
Hello! appears on the screen! By method
Enter hw2.saygoodbye ()
Goodbye appears!
========================================================== ======================================
========================================================== ======================================
Finally, I want to give you an example of "attribute" and ask you to give me the best answer.
======================================
# Hw3.py
Def hello ():
Property1 = "text"
Property2 = 23
Print "hello, I know a word" & property1 "and a number" & str (property2 )&"!!! "
======================================
Then we execute:
Import hw3
Hw2.hello ()
Appears
Hello, I know a word text and a number 23
The preceding str () is because 23 is a number and must be converted to a string before it can be combined with other strings. Here, porperty1 and property2 are two attributes, but they are fixed values. You can use the variable (the full text after the method...>