Backend Development
Python Tutorial
Take a look at some mistakes that even Python experts can't write
For those who are just getting started with Pythonista, they will more or less encounter some errors when running the code during the learning process, and it may seem difficult at first. As the amount of code accumulates, practice makes perfect and you can quickly locate the original problem when encountering some runtime errors. Below we have compiled some 17 common errors. When the code you write does not have these errors, your Python skills will reach a higher level. In other words, when you become a qualified Python developer, you may make mistakes like " can't even write ".
Free learning recommendation: python video tutorial
1,
Forget about if, for , adding :
at the end of declarations such as def, elif, else, class, etc. will result in "SyntaxError: invalid syntax" as follows:
if spam == 42
print('Hello!')
2,
Using = instead of ==
will also cause "SyntaxError: invalid syntax"
= is the assignment operator and == is the equal comparison operation. This error occurs in the following code:
if spam = 42:
print('Hello!')
3,
Incorrect use of indentation
results in "IndentationError: unexpected indent", " IndentationError: unindent does not match any outer indetation level" and "IndentationError: expected an indented block"
Remember that the indentation increase is only used after the statement ending with:, and then the previous indentation must be restored Format. This error occurs in the following code:
print('Hello!')
print('Howdy!')
or:
if spam == 42:
print('Hello!')
print('Howdy!')
4,
Forgot to call len()## in the for loop statement
#Causes "TypeError: 'list' object cannot be interpreted as an integer" Usually you want to iterate 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. This error occurs in the following code:spam = ['cat', 'dog', 'mouse'] for i in range(spam): print(spam[i])
5,
Trying to modify the value of stringresults in "TypeError: 'str' object does not support item assignment" string is an immutable data type. This error occurs in the following code: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,
Attempting to concatenate a non-string value with a stringresults in "TypeError: Can't convert 'int' object to str implicitly"This error occurs in 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,
Forgot at the beginning and end of the string Adding quotes results in "SyntaxError: EOL while scanning string literal" The error occurs in the following code:print(Hello!')
print('Hello!)
myName = 'Al'
print('My name is ' + myName + . How are you?')
8,
Spelling errors in variable or function names results in "NameError: name 'fooba' is not defined"This error occurs in the following code:foobar = 'Al'
print('My name is ' + fooba)
spam = ruond(4.2)
spam = Round(4.2)
9.
The method name is spelled incorrectlyleading to "AttributeError: 'str' object has no attribute 'lowerr'"This error occurs in the following code :spam = 'THIS IS IN LOWERCASE.' spam = spam.lowerr()
10,
The reference exceeds the maximum index of list resulting in "IndexError: list index out of range"This The error occurs in the following code:spam = ['cat', 'dog', 'mouse'] print(spam[6])
11,
Using a non-existent dictionary key value results 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,
Trying to use Python keywords as variable names results in " SyntaxError: invalid syntax”Python key cannot be used as a variable name. This error occurs in the following code: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,
In a Using the value-added operator when defining a new variable results in "NameError: name 'foobar' is not defined" Do not use 0 or an empty string as the initial value when declaring a variable. Use it automatically. The sentence spam = 1 of the increment operator is equal to spam = spam 1, which means that spam needs to specify a valid initial value. This error occurs in the following code:spam = 0 spam += 42 eggs += 42
14,
Use local variables in the function before defining them (at this time there are A global variable with the same name as a local variable exists) Causes "UnboundLocalError: local variable 'foobar' referenced before assignment" When a local variable is used in a function and a global variable with the same name exists at the same time It's very complicated. The usage rules are: if anything is defined in a function, if it is only used in the function, it is a local variable, otherwise it is a global variable. This means that you cannot use it as a global variable in a function before defining it. This error occurs in the following code:someVar = 42 def myFunction(): print(someVar) someVar = 100 myFunction()
15,
Trying to use range() to create a list of integers results "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 the actual list value. This error occurs in the following code:spam = range(10) spam[4] = -1 正确写法: spam = list(range(10)) spam[4] = -1
(注意:在 Python 2 中 spam = range(10) 是能行的,因为在 Python 2 中 range() 返回的是list值,但是在 Python 3 中就会产生以上错误)
16、
不存在 ++ 或者 -- 自增自减操作符。
导致“SyntaxError: invalid syntax”
如果你习惯于例如 C++ , Java , PHP 等其他的语言,也许你会想要尝试使用 ++ 或者 -- 自增自减一个变量。在Python中是没有这样的操作符的。
该错误发生在如下代码中:
spam = 1spam++ 正确写法: spam = 1spam += 1
17、
忘记为方法的第一个参数添加self参数
导致“TypeError: myMethod() takes no arguments (1 given)”
该错误发生在如下代码中:
class Foo():
def myMethod():
print('Hello!')
a = Foo()
a.myMethod()
相关免费学习推荐:python教程(视频)
The above is the detailed content of Take a look at some mistakes that even Python experts can't write. For more information, please follow other related articles on the PHP Chinese website!
Python: Automation, Scripting, and Task ManagementApr 16, 2025 am 12:14 AMPython excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.
Python and Time: Making the Most of Your Study TimeApr 14, 2025 am 12:02 AMTo maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.
Python: Games, GUIs, and MoreApr 13, 2025 am 12:14 AMPython excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.
Python vs. C : Applications and Use Cases ComparedApr 12, 2025 am 12:01 AMPython is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.
The 2-Hour Python Plan: A Realistic ApproachApr 11, 2025 am 12:04 AMYou can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.
Python: Exploring Its Primary ApplicationsApr 10, 2025 am 09:41 AMPython is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.
How Much Python Can You Learn in 2 Hours?Apr 09, 2025 pm 04:33 PMYou can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.
How to teach computer novice programming basics in project and problem-driven methods within 10 hours?Apr 02, 2025 am 07:18 AMHow to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...


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

Dreamweaver Mac version
Visual web development tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 English version
Recommended: Win version, supports code prompts!

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),





