


Summary of common mistakes made by beginners when learning Python
I have been learning Python recently, and now I have summarized some common mistakes as follows:
1) Forgot to put at the end of if, elif, else, for, while, class, def statement Add: (Causes "SyntaxError: invalid syntax") This error will occur in code similar to the following:
if spam == 42 print('Hello!')
2) Use = instead of == (Causes "SyntaxError: invalid syntax") = is the assignment operator And == is an equal comparison operation. This error occurs in the following code:
if spam = 42: print('Hello!')
3) Wrong use of indentation. (Resulting in "IndentationError: unexpected indent", "IndentationError: unindent does not match any outer indetation level" and "IndentationError: expected an indented block") Remember that indentation increases only after statements that end with: and must be restored afterwards to the previous indentation 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) Forgot to call len() in the for loop statement (resulting in "TypeError: 'list' object cannot be interpreted as an integer") Usually you want to iterate over 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) Try to modify the value of string (resulting in "TypeError: 'str' object does not support item assignment") string is an immutable data type, this error Happens in code like:
spam = 'I have a pet cat.' spam[13] = 'r' print(spam)
whereas you actually want to do this:
spam = 'I have a pet cat.' spam = spam[:13] + 'r' + spam[14:] print(spam)
6) Try concatenating a non-string value with a string (resulting in "TypeError: Can't convert 'int ' object to str implicitly") The error occurs in code like:
numEggs = 12 print('I have ' + numEggs + ' eggs.')
whereas you actually want to do:
numEggs = 12 print('I have ' + str(numEggs) + ' eggs.')
or:
numEggs = 12 print('I have %s eggs.' % (numEggs))
7) in the character Forgot to 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!') 或者: print('Hello!)
or:
myName = 'Al' print('My name is ' + myName + . How are you?')
8) The variable or function name is spelled incorrectly ( Causes "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 incorrectly (causes "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 error occurs in the following code:
spam = ['cat', 'dog', 'mouse'] print(spam[6])
11) Using a dictionary key value that does not exist (causing "KeyError: 'spam'") This error occurs in code like this:
spam = {'cat': 'Zophie', 'dog': 'Basil', 'mouse': 'Whiskers'} print('The name of my pet zebra is ' + spam['zebra'])
12) Trying to use a Python keyword as a variable name (causing "SyntaxError: invalid syntax") Python key cannot be used as a variable name. This error occurs in the following code:
class = 'algebra'
The keywords of Python3 are: 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) Use the increment operator when defining a new variable (resulting in "NameError: name 'foobar' is not defined"). Do not use 0 or an empty string as the initial value when declaring a variable. Use the increment operator instead. The sentence spam += 1 is equivalent 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) Using a local variable in a function before defining the local variable (at this time there is a global variable with the same name as the local variable) (resulting in "UnboundLocalError: local variable 'foobar ' referenced before assignment") It is very complicated to use a local variable in a function when there is a global variable with the same name. The rule of thumb is: if anything is defined in the function, if it is only used in the function, then it is Local, otherwise it is a global variable. This means that you cannot use it as a global variable in a function before defining it. The 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 (resulting in "TypeError: 'range' object does not support item assignment") Sometimes you want to get an ordered list 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. The 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: spam = range(10) works in Python 2, because in Range() in Python 2 returns a list value, but in Python 3 the above error will occur)
16) The error lies in the ++ or -- increment and decrement operators. (Resulting in "SyntaxError: invalid syntax") If you are used to other languages such as C++, Java, PHP, etc., you may want to try using ++ or -- to increment and decrement a variable. There is no such operator in Python. The error occurs in the following code:
spam = 1 spam++
Maybe this is what you want to do:
spam = 1 spam += 1
17)忘记为方法的第一个参数添加self参数(导致“TypeError: myMethod() takes no arguments (1 given)”) 该错误发生在如下代码中:
class Foo(): def myMethod(): print('Hello!') a = Foo() a.myMethod()
The above is the detailed content of Summary of common mistakes made by beginners when learning Python. For more information, please follow other related articles on the PHP Chinese website!

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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

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

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

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.
