


In the first few weeks of learning Python language programming, beginners will encounter a large number of syntax errors and other errors. But as long as you persist in overcoming difficulties and practice programming over a period of time, these errors will be significantly reduced. Some common errors and their solutions are listed below for beginners’ reference.
1. SyntaxError syntax error
(1) The quotation marks used to represent strings do not appear in pairs.
Error message:
SyntaxError: EOL while scanning stringliteral
Error example:
print('hello)
Solution:
Wrap the string within a pair of double quotes. When a string contains single or double quotes, it is easy to have unmatched quotes.
(2) Parentheses do not appear in pairs.
Error message:
SyntaxError: unexpected EOF while parsing
Error example 1:
a= (1 (2 / 3) * 4
Error example 2:
print('hello'
Solution:
Make parentheses appear in pairs. When writing complex expressions or calling functions This error is often encountered.
(3) The syntax of Python 2 is used when calling the print() function.
Error message:
SyntaxError: Missing parentheses in call to'print'
Error example:
print 'hello'
Solution:
Use Python 3 syntax The format calls the print() function, that is, print('hello'). When beginners switch from Python 2 to Python 3, they often make this mistake habitually.
(4) Error using self-operation operator or – etc.
Error message:
SyntaxError: invalid syntax
Error example:
a = 1
a
Solution:
In the Python language, there is no self-operation operator such as the or – in the C language. The usage of similar functions is the = or -= operator .For example, use the following code to increment variable a by 1.
a = 1
(5) Try to use the equal sign (=) to judge Whether the two operands are equal.
Error message:
SyntaxError: invalid syntax
Error example:
if a = 1:
Print('hello')
Solution:
Use two equal signs (==) in Python language as the relational operator to determine whether two operands are equal, and The equal sign (=) is the assignment operator.
(6) Misuse of Python language keywords as variable names.
Error message:
SyntaxError: can't assign to keyword
Error example:
True = 1
Solution:
Do not use Python language keywords as variable names, function names, or class names etc. In the Python Shell window, use the help('keywords') command to view the keyword list of the Python language.
(7) Forgot to add a colon (:) at the end of if/elif/else/while/for/def/class and other statements.
Error message:
SyntaxError: invalid syntax
Error example 1:
a = 2
if a > 0
print(' ')
Error example 2:
def sayhello()
print('hello')
Solution :
Just add a colon (:) at the end of if/elif/else/while/for/def/class and other statements. Keep the grammar rules in mind and it will become a habit.
2. IndentationError Indentation error
Error message:
IndentationError: unindent does not match any outer indentation level
IndentationError: expected an indentedblock
Error example:
a = 2
if a > 0:
print(' ')
print(a)
else:
print('-')
Note: The reason for the error is that the code indentation in the if statement body in the above code is not aligned.
Solution:
Use indentation correctly to format your code. This error is more common when code is copied and pasted from elsewhere.
3. NameError Name error
When the variable name, function name or class name is written incorrectly, or the function is written before it is defined In the case of functions, etc., it will lead to name errors.
Error message:
NameError: name 'pirnt' is not defined
NameError: name 'sayhello' is not defined
Error example 1:
pirnt('hello')
Note: The cause of the error is a typo in print.
Error example 2:
sayhello()
def sayhello():
pass
Note: The cause of the error is in the function Call the function before defining it.
Solution:
Write the variable name, function name or class name correctly, assign the value before using the variable, put the function definition before the function call, etc. That is to ensure that a certain name (identifier) exists before it can be used.
4. TypeError type error
(1) Integers and strings cannot be connected.
Error message:
TypeError: Can't convert 'int' object tostr implicitly
TypeError: unsupported operand type(s) for : 'float' and 'str'
Error example 1:
print('score:' 100)
Error example 2:
print(9.8 'seconds')
Solution:
In Before concatenating an integer, floating point number or Boolean value with a string, use the str() function to convert it to a string type.
(2) The number of parameters when calling the function is incorrect, or the parameters are not passed.
Error message:
TypeError: input expected at most 1arguments, got 2
TypeError: say() missing 1 requiredpositional argument: 'words'
Error example 1:
input('Enter name', 'Age')
Note: The cause of the error is trying to provide the second parameter to the input() function.
Error example 2:
def say(words):
print(words)
say()
Note: Error The reason is that no parameters are passed when calling the function.
Solution:
Remember the function usage, understand the parameter definition of the function, and use the correct method to call the function.
5. KeyError key error
This error occurs when you use a non-existent key name to access an element in the dictionary.
Error message:
KeyError: 'c'
Error example:
d= {'a':1, 'b':2}
print(d['c'])
Solution:
When accessing elements in the dictionary, first use the in keyword to check whether the key name to be accessed is exists, or to safely access dictionary elements using the dictionary's get() method.
6. IndexError Index error
When the index of the access list exceeds the list range, an index error occurs.
Error message:
IndexError: list index out of range
Error example:
a = [1, 2, 3]
print(a[3])
Note: The reason for the error is that the fourth index does not exist in list a. Remember that the indexes of lists are numbered starting from 0.
Solution:
Get the length of the list through the len() function, and then determine whether the index to be accessed exceeds the range of the list.
7. UnboundLocalError Uninitialized local variable error
In a function, if you modify an undeclared global variable, you will encounter to this error.
Error message:
UnboundLocalError: local variable 's'referenced before assignment
Error example:
s = 1
def test():
s = 1
print(s)
test()
Note: The reason for the error is that the code is not declared within the function The global variable s has been incremented. Python treats the variable s as a local variable, but the variable is not initialized.
Solution:
When using global variables within a function, just declare them using the global keyword.
Summary
In short, it is inevitable to encounter errors in actual programming. But don't worry, they are just paper tigers. Beginners should be good at using search engines to find and solve problems, and check for any errors they encounter. As long as you enter the content of the error message into the search box of a search engine, you can find a lot of information on how to solve the error.
The above is the detailed content of Seven common mistakes among Python beginners and their solutions. For more information, please follow other related articles on the PHP Chinese website!

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于Seaborn的相关问题,包括了数据可视化处理的散点图、折线图、条形图等等内容,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于进程池与进程锁的相关问题,包括进程池的创建模块,进程池函数等等内容,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于简历筛选的相关问题,包括了定义 ReadDoc 类用以读取 word 文件以及定义 search_word 函数用以筛选的相关内容,下面一起来看一下,希望对大家有帮助。

VS Code的确是一款非常热门、有强大用户基础的一款开发工具。本文给大家介绍一下10款高效、好用的插件,能够让原本单薄的VS Code如虎添翼,开发效率顿时提升到一个新的阶段。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于数据类型之字符串、数字的相关问题,下面一起来看一下,希望对大家有帮助。

pythn的中文意思是巨蟒、蟒蛇。1989年圣诞节期间,Guido van Rossum在家闲的没事干,为了跟朋友庆祝圣诞节,决定发明一种全新的脚本语言。他很喜欢一个肥皂剧叫Monty Python,所以便把这门语言叫做python。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于numpy模块的相关问题,Numpy是Numerical Python extensions的缩写,字面意思是Python数值计算扩展,下面一起来看一下,希望对大家有帮助。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version
Visual web development tools

Notepad++7.3.1
Easy-to-use and free code editor

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft
