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

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

好比你要引用requests,可是本身給本身的文件起名也叫requests.py,這樣執行下面代碼python

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

就會報以下錯誤ide

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裏調試和運行通不過。調試

格式不對齊的問題

下面是一段正常代碼code

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

fun()

1.若是else不對齊rem

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後面的冒號漏寫get

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()

都會報pycharm

SyntaxError: invalid syntax

3.若是if和else下面的語句沒有縮進requests

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")
相關文章
相關標籤/搜索