总结一些python开发新手常见错误

文件名与要引用的包名同名

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

import requests
requests.get('http://www.baidu.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.baidu.com')
复制代码

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

格式不对齐的问题

下面是一段正常代码

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

fun()
复制代码

1.如果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
复制代码

2.如果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
复制代码

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

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

fun()
复制代码

就会报

IndentationError: expected an indented block
复制代码

字符串使用中文的引号

比如下面用中文引号

print(“a”)
复制代码

就会报

SyntaxError: invalid character in identifier
复制代码

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

print('b')
print("b")
复制代码

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

比如下面的代码

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))
复制代码

1.如果少写了%s

a = 1
b = 2
print('a = '%a) # 错误
print('a,b = %s'%(a,b)) # 错误
复制代码

会报

TypeError: not all arguments converted during string formatting
复制代码

2.如果多写了%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
复制代码

3.如果格式化的字符串不对,比如写成大写的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
复制代码

4.如果%后面什么都没写

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里面返回是小数

print(3/2)
复制代码

返回是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安装包的时候网络超时

类似如下错误 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 建议设置镜像源,比如更换为清华源,参考传送门

也有可能碰到没有加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


作者:冰风漫天
链接:https://juejin.cn/post/7023700981665759240
来源:稀土掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一个乖乖码字的程序猪

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值