Python开发新手常见错误及解决办法

464 阅读4分钟

文件与要引用的包同名

比如你要引用requests,但是自己给自己的文件起名也叫requests.py,这样执行下面代码

import requests
requests.get('http://www.zhijiancode.com')

#会报错 AttributeError: module 'requests' has no attribute 'get'

解决方法是给你的python文件名换个名字,只要不和包名相同就行,如果实在不想改文件名,可以用下面的方法

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.zhijiancode.com')

主要原理是将当前目录排除在python运行是的查找目录,这种处理后在命令行执行python requests.py是可以正常运行的,但是在pycharm里调试和运行通不过。

缩进问题

正确缩进对齐方式

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

fun()
  • 如果else没对齐

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

    fun()

    #会报错 IndentationError: unindent does not match any outer indentation level

  • 如果else和if没有成对出现,比如直接写一个else或者多写了一个else,或者if和else后面的冒号漏写

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

    fun()

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

    fun()

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

    fun() ##都会报错 SyntaxError: invalid syntax

  • 如果if和else 下面的语句没有缩进

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

    fun()

    #会报错 IndentationError: expected an indented block

字符串使用中文引号

比如下面使用中文引号

print(“指尖编程”)

#会报错 SyntaxError: invalid character in identifier

正确的打开方式是使用英文的单引号或者双引号

print('指尖编程')
print("指尖编程")

没有调用函数误认为函数不执行

如下代码

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

a = A()
a.run

程序是正常的,运行也没有报错,但是可能好奇为什么没有打印输出,原因当然是因为a.run返回的函数的引用,并没有执行,要调用a.run()才会发现有打印输出。

如果修改下代码,改成

class A(object):
    def run(self):
        return 1

a = A()
print(a.run+1)

#会看到报错 TypeError: unsupported operand type(s) for +: 'method' and 'int'

改成a.run()+1后便正常了。

字符串格式化

正确的写法

a = 1
b = 2
print('a = %s'%a)
print('a,b = %s,%s'%(a,b))

少写了%s

a = 1
b = 2
print('a = '%a) # 错误
print('a,b = %s'%(a,b)) # 错误

#会报错 TypeError: not all arguments converted during string formatting

多写了%s

a = 1
b = 2
print('a = %s,%s'%a)
print('a,b = %s,%s,%s'%(a,b))
``
#会报错
```bash
TypeError: not enough arguments for format string

格式化的字符串不对,比如写成大写的S

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

#会报错 ValueError: unsupported format character 'S' (0x53) at index 5

如果%后面什么都没有写

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

#会报错 ValueError: incomplete format

对None操作的报错

比如这段代码

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

a排序后的值是[1,2,3],sort函数的返回值是None,所以b的值其实时None,并不是[1,2,3]。

如果这时候去操作b

比如取b的第一个元素

print(b[0])

#会报错 TypeError: 'NoneType' object is not subscriptable

复制数组

print(b*2)

#会报错 TypeError: unsupported operand type(s) for *: 'NoneType' and 'int'

执行extend函数

b.extend([4])

#会报错 AttributeError: 'NoneType' object has no attribute 'extend'

整数相除

Python2里面默认整数相除是返回整数部分

print(3/2)

#返回是1
#而Python3里返回是小数1.5

所以下面代码

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

在Python2里可以得到值为2,而在Python3里执行却会报错

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

修改方法有两种

1.把结果转为整数

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

2.用“//”号

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

这两种写法同样适用于Python2

主键不存在

获取的键字典中不存在

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

#会报错 KeyError: 'a'

pip安装工具包时网络超时

类似如下错误

建议设置镜像源,比如更换为清华源

也有可能碰到没有加trusted-host参数而出现如下错误

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

安装命令增加–trust-host即可

pip install -i pypi.tuna.tsinghua.edu.cn/simple --trusted-host pypi.tuna.tsinghua.edu.cn xxx

指尖编程,了解更多Python知识。