Home Backend Development Python Tutorial Take a look at some mistakes that even Python experts can't write

Take a look at some mistakes that even Python experts can't write

Feb 05, 2021 pm 05:25 PM
python

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!')
Copy after login

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!')
Copy after login

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!')
Copy after login

or:

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

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])
Copy after login

5,

Trying to modify the value of string

results 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)
Copy after login
The correct approach is:

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

6,

Attempting to concatenate a non-string value with a string

results in "TypeError: Can't convert 'int' object to str implicitly"

This error occurs in the following code:

numEggs = 12
print('I have ' + numEggs + ' eggs.')
Copy after login
The correct approach is:

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

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

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?')
Copy after login

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)
Copy after login

9.

The method name is spelled incorrectly

leading to "AttributeError: 'str' object has no attribute 'lowerr'"

This error occurs in the following code :

spam = 'THIS IS IN LOWERCASE.'
spam = spam.lowerr()
Copy after login

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])
Copy after login

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'])
Copy after login

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
Copy after login

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
Copy after login

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()
Copy after login

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
Copy after login

(注意:在 Python 2 中 spam = range(10) 是能行的,因为在 Python 2 中 range() 返回的是list值,但是在 Python 3 中就会产生以上错误)

16、

不存在 ++ 或者 -- 自增自减操作符。

导致“SyntaxError: invalid syntax”

如果你习惯于例如 C++ , Java , PHP 等其他的语言,也许你会想要尝试使用 ++ 或者 -- 自增自减一个变量。在Python中是没有这样的操作符的。

该错误发生在如下代码中:

spam = 1spam++
正确写法:
spam = 1spam += 1
Copy after login

17、

忘记为方法的第一个参数添加self参数

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

该错误发生在如下代码中:

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

相关免费学习推荐: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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

Python vs. JavaScript: Community, Libraries, and Resources Python vs. JavaScript: Community, Libraries, and Resources Apr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

Detailed explanation of docker principle Detailed explanation of docker principle Apr 14, 2025 pm 11:57 PM

Docker uses Linux kernel features to provide an efficient and isolated application running environment. Its working principle is as follows: 1. The mirror is used as a read-only template, which contains everything you need to run the application; 2. The Union File System (UnionFS) stacks multiple file systems, only storing the differences, saving space and speeding up; 3. The daemon manages the mirrors and containers, and the client uses them for interaction; 4. Namespaces and cgroups implement container isolation and resource limitations; 5. Multiple network modes support container interconnection. Only by understanding these core concepts can you better utilize Docker.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python 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.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

What is vscode What is vscode for? What is vscode What is vscode for? Apr 15, 2025 pm 06:45 PM

VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages ​​and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.

How to install nginx in centos How to install nginx in centos Apr 14, 2025 pm 08:06 PM

CentOS Installing Nginx requires following the following steps: Installing dependencies such as development tools, pcre-devel, and openssl-devel. Download the Nginx source code package, unzip it and compile and install it, and specify the installation path as /usr/local/nginx. Create Nginx users and user groups and set permissions. Modify the configuration file nginx.conf, and configure the listening port and domain name/IP address. Start the Nginx service. Common errors need to be paid attention to, such as dependency issues, port conflicts, and configuration file errors. Performance optimization needs to be adjusted according to the specific situation, such as turning on cache and adjusting the number of worker processes.

See all articles