current position:Home>Summarize some common mistakes of novices in Python development
Summarize some common mistakes of novices in Python development
2022-01-30 13:53:43 【Ice and wind all over the sky】
The file name has the same name as the package name to be referenced
For example, you have to quote requests, But I'll name my file as requests.py, So execute the following code
import requests
requests.get('http://www.baidu.com')
Copy code
The following error will be reported
AttributeError: module 'requests' has no attribute 'get'
Copy code
The solution is for you python Change the name of the file , As long as it doesn't have the same package name , If you really don't want to change the file name , You can do it in the following way
import sys
_cpath_ = sys.path[0]
print(sys.path)
print(_cpath_)
sys.path.remove(_cpath_)
import requests
sys.path.insert(0, _cpath_)
requests.get('http://www.baidu.com')
Copy code
The main principle is to exclude the current directory from python Run the search directory , This processing is then executed on the command line python requests.py It can operate normally , But in pycharm The debugging and running of the system can't get through .
The problem of format misalignment
Here's the normal code
def fun():
a=1
b=2
if a>b:
print("a")
else:
print("b")
fun()
Copy code
1. If else Not aligned
def fun():
a=1
b=2
if a>b:
print("a")
else:
print("b")
fun()
Copy code
Will report
IndentationError: unindent does not match any outer indentation level
Copy code
2. If else and if There are no pairs , For example, write one directly else Or one more else, perhaps if and else The colon is missing
def fun():
a=1
b=2
else:
print("b")
fun()
Copy code
def fun():
a=1
b=2
if a>b:
print("a")
else:
print("b")
else:
print("b")
fun()
Copy code
def fun():
a=1
b=2
if a>b:
print("a")
else
print("b")
fun()
Copy code
Metropolitan newspaper
SyntaxError: invalid syntax
Copy code
3. If if and else The following statement is not indented
def fun():
a=1
b=2
if a>b:
print("a")
else:
print("b")
fun()
Copy code
Will report
IndentationError: expected an indented block
Copy code
The string uses Chinese quotation marks
For example, use Chinese quotation marks below
print(“a”)
Copy code
Will report
SyntaxError: invalid character in identifier
Copy code
The correct way is to use single quotation marks or double quotation marks in English
print('b')
print("b")
Copy code
It's no use calling the function , Mistakenly think that the function does not execute
Consider the following code
class A(object):
def run(self):
print('run')
a = A()
a.run
Copy code
The procedure is normal , There is no error during operation , But you may wonder why there is no printout , The reason, of course, is because a.run The reference of the returned function , It's not implemented , To be called a.run() Will find a printout . If you modify the code , Change to
class A(object):
def run(self):
return 1
a = A()
print(a.run+1)
Copy code
You will see the error report
TypeError: unsupported operand type(s) for +: 'method' and 'int'
Copy code
Change to a.run()+1 Then it's normal .
String formatting
This is a normal procedure
a = 1
b = 2
print('a = %s'%a)
print('a,b = %s,%s'%(a,b))
Copy code
1. If you write less %s
a = 1
b = 2
print('a = '%a) # error
print('a,b = %s'%(a,b)) # error
Copy code
Will be submitted to the
TypeError: not all arguments converted during string formatting
Copy code
2. If you write more %s
a = 1
b = 2
print('a = %s,%s'%a)
print('a,b = %s,%s,%s'%(a,b))
``
Will be submitted to the
```bash
TypeError: not enough arguments for format string
Copy code
3. If the formatted string is incorrect , For example, written in capital letters s
a = 1
b = 2
print('a = %S'%a)
print('a,b = %S,%S'%(a,b))
Copy code
Will be submitted to the
ValueError: unsupported format character 'S' (0x53) at index 5
Copy code
4. If % There's nothing in the back
a = 1
b = 2
print('a = %'%a)
print('a,b = %,%'%(a,b))
Copy code
Will be submitted to the
ValueError: incomplete format
Copy code
Yes None Error report of operation
For example, this code
a = [3,2,1]
b = a.sort()
print(a)
print(b)
Copy code
a The sorted value is [1,2,3],sort The return value of the function is None, therefore b Real time value of None, Not at all [1,2,3].
If you operate at this time b Take for example b The first element of
print(b[0])
Copy code
May be an error
TypeError: 'NoneType' object is not subscriptable
Copy code
Like copying arrays
print(b*2)
Copy code
May be an error
TypeError: unsupported operand type(s) for *: 'NoneType' and 'int'
Copy code
Such as execution extend function
b.extend([4])
Copy code
May be an error
AttributeError: 'NoneType' object has no attribute 'extend'
Copy code
Divide an integer by
python2 The default integer division is to return the integer part
print(3/2)
Copy code
Return is 1 and python3 It returns a decimal number
print(3/2)
Copy code
Return is 1.5 So the following code
a = [1,2,3]
print(a[len(a)/2])
Copy code
stay python2 You can get a value of 2, And in the python3 In the execution, you will get an error report
TypeError: list indices must be integers or slices, not float
Copy code
There are two ways to modify 1. Convert the result to an integer
a = [1,2,3]
print(a[int(len(a)/2)])
Copy code
2. use // Number
a = [1,2,3]
print(a[len(a)//2])
Copy code
These two expressions also apply to python2, Therefore, if you expect an integer to return, it is recommended to use the double division sign , Express your intention explicitly
The primary key does not exist
The dictionary obtained does not exist
a = {'A':1}
print(a['a'])
Copy code
Will report a mistake
KeyError: 'a'
Copy code
pip Network timeout while installing package
Similar to the following error bash WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x7f3b6ea319b0>, 'Connection to files.pythonhosted.org timed out. (connect timeout=15)')': /packages/xxxxxx
It is recommended to set the image source , For example, replace it with Tsinghua source , Reference resources Portal
It's also possible to meet someone who doesn't add trusted-host The following error occurred due to parameter
Collecting xxx
The repository located at pypi.tuna.tsinghua.edu.cn is not a trusted or secure host and is being ignored. If this repository is available via HTTPS it is recommended to use HTTPS instead, otherwise you may silence this warning and allow it anyways with ‘--trusted-host pypi.tuna.tsinghua.edu.cn’.
Could not find a version that satisfies the requirement xxx (from versions: )
No matching distribution found for xxx
Copy code
Installation command added --trust-host that will do pip install -i pypi.tuna.tsinghua.edu.cn/simple --trusted-host pypi.tuna.tsinghua.edu.cn xxx
copyright notice
author[Ice and wind all over the sky],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201301353418390.html
The sidebar is recommended
- Python code reading (Part 44): find the location of qualified elements
- Elegant implementation of Django model field encryption
- 40 Python entry applet
- Pandas comprehensive application
- Chapter 2: Fundamentals of python-3 character string
- Python pyplot draws a parallel histogram, and the x-axis value is displayed in the center of the two histograms
- [Python crawler] detailed explanation of selenium from introduction to actual combat [1]
- Curl to Python self use version
- Python visualization - 3D drawing solutions pyecharts, Matplotlib, openpyxl
- Use python, opencv's meanshift and CAMSHIFT algorithms to find and track objects in video
guess what you like
-
Using python, opencv obtains and changes pixels, modifies image channels, and trims ROI
-
[Python data collection] university ranking data collection
-
[Python data collection] stock information collection
-
Python game development, pyGame module, python takes you to realize a magic tower game from scratch (2)
-
Python solves the problem of suspending execution after clicking the mouse in CMD window (fast editing mode is prohibited)
-
[Python from introduction to mastery] (II) how to run Python? What are the good development tools (pycharm)
-
Python type hints from introduction to practice
-
Python notes (IX): basic operation of dictionary
-
Python notes (8): basic operations of collections
-
Python notes (VII): definition and use of tuples
Random recommended
- Python notes (6): definition and use of lists
- Python notes (V): string operation
- Python notes (IV): use of functions and modules
- Python notes (3): conditional statements and circular statements
- Python notes (II): lexical structure
- Notes on python (I): getting to know Python
- [Python data structure series] - tree and binary tree - basic knowledge - knowledge point explanation + code implementation
- [Python daily homework] Day7: how to combine two dictionaries in an expression?
- How to implement a custom list or dictionary in Python
- 15 advanced Python tips for experienced programmers
- Python string method tutorial - how to use the find() and replace() functions on Python strings
- Python computer network basics
- Python crawler series: crawling global airport information
- Python crawler series: crawling global port information
- How to calculate unique values using pandas groupby
- Application of built-in distribution of Monte Carlo simulation SciPy with Python
- Gradient lifting method and its implementation in Python
- Pandas: how to group and calculate by index
- Can you create an empty pandas data frame and fill it in?
- Python basic exercises teaching! can't? (practice makes perfect)
- Exploratory data analysis (EDA) in Python using SQL and Seaborn (SNS).
- Turn audio into shareable video with Python and ffmpeg
- Using rbind in python (equivalent to R)
- Pandas: how to create an empty data frame with column names
- Talk about quantifying investment using Python
- Python, image restoration in opencv - CV2 inpaint
- Python notes (14): advanced technologies such as object-oriented programming
- Python notes (13): operations such as object-oriented programming
- Python notes (12): inheritance such as object-oriented programming
- Chapter 2: Fundamentals of python-5 Boolean
- Python notes (11): encapsulation such as object-oriented programming
- Python notes (10): concepts such as object-oriented programming
- Gradient lifting method and its implementation in Python
- Van * Python | simple crawling of a site course
- Chapter 1 preliminary knowledge of pandas (list derivation and conditional assignment, anonymous function and map method, zip object and enumerate method, NP basis)
- Nanny tutorial! Build VIM into an IDE (Python)
- Fourier transform of Python OpenCV image processing, lesson 52
- Introduction to python (III) network request and analysis
- China Merchants Bank credit card number recognition project (Part I), python OpenCV image processing journey, Part 53
- Python practice - capture 58 rental information and store it in MySQL database