Home > Backend Development > Python Tutorial > Seven common mistakes among Python beginners and their solutions

Seven common mistakes among Python beginners and their solutions

爱喝马黛茶的安东尼
Release: 2019-06-03 11:23:10
forward
4836 people have browsed it

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.

Seven common mistakes among Python beginners and their solutions

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!

Related labels:
source:csdn.net
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template