程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

總結一些python開發新手常見錯誤

編輯: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
來源:稀土掘金
著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請注明出處。


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved