Summarize some common errors for beginners in python development

File name is the same as the package name to be referenced

For example, if you want to reference requests, but name your own file also called requests.py, 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 to give your python file a different name, as long as it's not the same as the package name. If you really don't want to change the file name, you can use the following method

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 the lookup directory where python is running. Executing python requests.py on the command line after this process works fine, but debugging and running in pycharm is not possible.

Misaligned formatting

Here's a piece of normal code

def fun():
    a=1
    b=2
    if a>b:
        print("a")  
    else:
        print("b")

fun()
Copy Code

1. If else is 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 do not appear in pairs, such as writing an else directly or an extra else, or if and the colon following the else are omitted

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 the statement below if and else 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

Use quotation marks in Chinese for Strings

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 or double quotation marks in English

print('b')
print("b")
Copy Code

No call to function, mistaken for function not to execute

For example, the following code

class A(object):
    def run(self):
        print('run')

a = A()
a.run
 Copy Code

The program is normal and runs without errors, but it may be curious why there is no printout, of course, because a.run returns a reference to a function that is not executed and a is called. Run() will find the printout. If you change 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

TypeError: unsupported operand type(s) for +: 'method' and 'int'
Copy Code

Changing to a.run()+1 will work.

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

Meeting Report

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))
``
Meeting Report
```bash
TypeError: not enough arguments for format string
 Copy Code

3. If the formatted string is incorrect, such as s in uppercase

a = 1
b = 2
print('a = %S'%a)
print('a,b = %S,%S'%(a,b))
Copy Code

Meeting Report

ValueError: unsupported format character 'S' (0x53) at index 5
 Copy Code

4. If nothing is written behind%

a = 1
b = 2
print('a = %'%a)
print('a,b = %,%'%(a,b))
Copy Code

Meeting Report

ValueError: incomplete format
 Copy Code

Error on None operation

Like this code

a = [3,2,1]
b = a.sort()
print(a)
print(b)
Copy Code

The sorted value is [1,2,3], and the return value of the sort function is None, so the value of b is actually None, not [1,2,3].

If this is the time to manipulate b, such as taking the first element of B

print(b[0])
Copy Code

Error will occur

TypeError: 'NoneType' object is not subscriptable
 Copy Code

Such as copying arrays

print(b*2)
Copy Code

Error will occur

TypeError: unsupported operand type(s) for *: 'NoneType' and 'int'
Copy Code

For example, execute the extend function

b.extend([4])
Copy Code

Error will occur

AttributeError: 'NoneType' object has no attribute 'extend'
Copy Code

Integer Division

The default integer division in python2 returns the integer part

print(3/2)
Copy Code

Return 1 and return decimal in python3

print(3/2)
Copy Code

Return is 1.5 so the following code

a = [1,2,3]
print(a[len(a)/2])
Copy Code

You get a value of 2 in python2, and you do get an error executing in python3

TypeError: list indices must be integers or slices, not float
 Copy Code

There are two ways to modify this. 1. Turn the result into an integer

a = [1,2,3]
print(a[int(len(a)/2)])
Copy Code

2. Use //

a = [1,2,3]
print(a[len(a)//2])
Copy Code

Both are also appropriate for python2, so when expecting integers to return, it is advisable to use a double division sign to express your intentions explicitly

Primary key does not exist

The acquired build dictionary does not exist

a = {'A':1}
print(a['a'])
Copy Code

Errors will occur

KeyError: 'a'
Copy Code

Network timeout during pip installation

Similar to the following error bash WARNING: Retrying (total=3, connect=None, read=None, redirect=None, status=None)) after connection break by'ConnectTimeoutError (<pip. _vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x7f3b6ea319b0>,'Connection to files.pythonhosted.org timed. (connect timeout=15)'): /xpackages/xxxxxx Recommends setting up a mirror source, such as Tsinghua source, for reference Portal

You may also encounter the following error without adding the trusted-host 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 PIP install-i pypi.tuna.tsinghua.edu.cn/simple --trusted-host pypi.tuna.tsinghua.edu.cn xxx


Author: Ice wind in the sky
Links: https://juejin.cn/post/7023700981665759240
Source: Rare Earth Excavation
Copyright belongs to the author. For commercial reprinting, please contact the author for authorization. For non-commercial reprinting, please indicate the source.

Tags: Python programming language

Posted by no3dfx on Wed, 21 Sep 2022 22:29:20 +0530