总结一些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")

猜你喜欢

转载自blog.51cto.com/15060785/2576603