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

Random recommended