python開発者のいくつかの一般的な間違いを要約します(上)

ファイル名は、引用するパッケージ名と同じです。

たとえば、リクエストを引用したいが、独自のファイルにも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")

おすすめ

転載: blog.51cto.com/15060785/2576603