search
HomeBackend DevelopmentPython TutorialSummary 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!

Statement
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
What are the alternatives to concatenate two lists in Python?What are the alternatives to concatenate two lists in Python?May 09, 2025 am 12:16 AM

There are many methods to connect two lists in Python: 1. Use operators, which are simple but inefficient in large lists; 2. Use extend method, which is efficient but will modify the original list; 3. Use the = operator, which is both efficient and readable; 4. Use itertools.chain function, which is memory efficient but requires additional import; 5. Use list parsing, which is elegant but may be too complex. The selection method should be based on the code context and requirements.

Python: Efficient Ways to Merge Two ListsPython: Efficient Ways to Merge Two ListsMay 09, 2025 am 12:15 AM

There are many ways to merge Python lists: 1. Use operators, which are simple but not memory efficient for large lists; 2. Use extend method, which is efficient but will modify the original list; 3. Use itertools.chain, which is suitable for large data sets; 4. Use * operator, merge small to medium-sized lists in one line of code; 5. Use numpy.concatenate, which is suitable for large data sets and scenarios with high performance requirements; 6. Use append method, which is suitable for small lists but is inefficient. When selecting a method, you need to consider the list size and application scenarios.

Compiled vs Interpreted Languages: pros and consCompiled vs Interpreted Languages: pros and consMay 09, 2025 am 12:06 AM

Compiledlanguagesofferspeedandsecurity,whileinterpretedlanguagesprovideeaseofuseandportability.1)CompiledlanguageslikeC arefasterandsecurebuthavelongerdevelopmentcyclesandplatformdependency.2)InterpretedlanguageslikePythonareeasiertouseandmoreportab

Python: For and While Loops, the most complete guidePython: For and While Loops, the most complete guideMay 09, 2025 am 12:05 AM

In Python, a for loop is used to traverse iterable objects, and a while loop is used to perform operations repeatedly when the condition is satisfied. 1) For loop example: traverse the list and print the elements. 2) While loop example: guess the number game until you guess it right. Mastering cycle principles and optimization techniques can improve code efficiency and reliability.

Python concatenate lists into a stringPython concatenate lists into a stringMay 09, 2025 am 12:02 AM

To concatenate a list into a string, using the join() method in Python is the best choice. 1) Use the join() method to concatenate the list elements into a string, such as ''.join(my_list). 2) For a list containing numbers, convert map(str, numbers) into a string before concatenating. 3) You can use generator expressions for complex formatting, such as ','.join(f'({fruit})'forfruitinfruits). 4) When processing mixed data types, use map(str, mixed_list) to ensure that all elements can be converted into strings. 5) For large lists, use ''.join(large_li

Python's Hybrid Approach: Compilation and Interpretation CombinedPython's Hybrid Approach: Compilation and Interpretation CombinedMay 08, 2025 am 12:16 AM

Pythonusesahybridapproach,combiningcompilationtobytecodeandinterpretation.1)Codeiscompiledtoplatform-independentbytecode.2)BytecodeisinterpretedbythePythonVirtualMachine,enhancingefficiencyandportability.

Learn the Differences Between Python's 'for' and 'while' LoopsLearn the Differences Between Python's 'for' and 'while' LoopsMay 08, 2025 am 12:11 AM

ThekeydifferencesbetweenPython's"for"and"while"loopsare:1)"For"loopsareidealforiteratingoversequencesorknowniterations,while2)"while"loopsarebetterforcontinuinguntilaconditionismetwithoutpredefinediterations.Un

Python concatenate lists with duplicatesPython concatenate lists with duplicatesMay 08, 2025 am 12:09 AM

In Python, you can connect lists and manage duplicate elements through a variety of methods: 1) Use operators or extend() to retain all duplicate elements; 2) Convert to sets and then return to lists to remove all duplicate elements, but the original order will be lost; 3) Use loops or list comprehensions to combine sets to remove duplicate elements and maintain the original order.

See all articles

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

Video Face Swap

Video Face Swap

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

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

mPDF

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),

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools