总结一些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")
相关文章
相关标签/搜索