新手常见6种的python报错及解决方法


Posted in Python onMarch 09, 2018

此篇文章整理新手编写代码常见的一些错误,有些错误是粗心的错误,但对于新手而已,会折腾很长时间才搞定,所以在此总结下我遇到的一些问题。希望帮助到刚入门的朋友们。

1.NameError变量名错误

报错:

>>> print a
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined

解决方案:

先要给a赋值。才能使用它。在实际编写代码过程中,报NameError错误时,查看该变量是否赋值,或者是否有大小写不一致错误,或者说不小心将变量名写错了。

注:在Python中,无需显示变量声明语句,变量在第一次被赋值时自动声明。

>>> a=1
>>> print a
1

2.IndentationError代码缩进错误

点击返回目录

代码:

a=1
b=2
if a<b:
print a

报错:

IndentationError: expected an indented block

原因:

缩进有误,python的缩进非常严格,行首多个空格,少个空格都会报错。这是新手常犯的一个错误,由于不熟悉python编码规则。像def,class,if,for,while等代码块都需要缩进。

缩进为四个空格宽度,需要说明一点,不同的文本编辑器中制表符(tab键)代表的空格宽度不一,如果代码需要跨平台或跨编辑器读写,建议不要使用制表符。

解决方案:

a=1
b=2
if a<b:
 print a

3.AttributeError对象属性错误

报错:

>>> import sys

>>> sys.Path
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'Path'

原因:

sys模块没有Path属性。

解决方案:

python对大小写敏感,Path和path代表不同的变量。将Path改为path即可。

>>> sys.path
['', '/usr/lib/python2.6/site-packages']

python知识拓展:

使用dir函数查看某个模块的属性

>>> dir(sys)

['__displayhook__', '__doc__', '__egginsert', '__excepthook__', '__name__', '__package__', '__plen', '__stderr__', '__stdin__', '__stdout__', '_clear_type_cache', '_current_frames', '_getframe', 'api_version', 'argv', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dont_write_bytecode', 'exc_clear', 'exc_info', 'exc_type', 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info', 'getcheckinterval', 'getdefaultencoding', 'getdlopenflags', 'getfilesystemencoding', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'gettrace', 'hexversion', 'maxint', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1', 'ps2', 'py3kwarning', 'setcheckinterval', 'setdlopenflags', 'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'subversion', 'version', 'version_info', 'warnoptions']

4.TypeError类型错误

4.1入参类型错误

代码:

t=('a','b','c')
for i in range(t):
 print a[i]

报错:

TypeError: range() integer end argument expected, got tuple.

原因:

range()函数期望的入参是整型(integer),但却给的入参为元组(tuple)

解决方案:

将入参元组t改为元组个数整型len(t)

将range(t)改为range(len(t))

4.2入参个数错误

4.2.1关于元组作为入参

代码:

# coding=utf-8
'''
Created on 2016-7-21
@author: Jennifer
Project:显式等待
'''
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from time import ctime

driver=webdriver.Firefox()
driver.get(r'http://www.baidu.com/')
loc=(By.ID,'kw')
print ctime()
element=WebDriverWait(driver,5,0.5).until(EC.visibility_of_element_located(*loc))
element.send_keys('selenium')
print ctime()
driver.quit()

报错:

Traceback (most recent call last):

 File "D:\system files\workspace\selenium\autotestcombat\test_4_7_1_webdriverwait.py", line 18, in <module>
 element=WebDriverWait(driver,5,0.5).until(EC.visibility_of_element_located(*loc))
TypeError: __init__() takes exactly 2 arguments (3 given)

原因:

类的函数__init__()需要两个参数,但实际上给了三个。
EC.visibility_of_element_located类的入参应该是两个入参: self和元组。但却给了三个参数 self和*loc中的两个元素作为入参。

解决方案:

这里要将EC.visibility_of_element_located(*loc)改为EC.visibility_of_element_located(loc),入参为元组,而不是元组里边的两个值。

python知识拓展:

关于入参*的用法
以元组作为函数入参,如果元组前加*号,说明传递的入参为元组中的各个元素。如果元组前没有加*号,说明传递的入参为元组本身。

举例说明:
loc =(By.NAME,'email')
element1=WebDriverWait(driver,5,0.5).until(EC.visibility_of_element_located(loc)) #只要一个参数(不考虑self情况下),元组loc,即:(By.NAME,'email')。 直接传loc。
element2=driver.find_element(*loc)#需要两个参数,元组loc的元素,即:By.NAME,'email'。直接传*loc 

4.2.2其他

报错:

>>> import os

>>> os.listdir()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: listdir() takes exactly 1 argument (0 given)

原因:

listdir()函数需要一个入参,但是只给了0个入参。

解决方案:

加一个入参

>>> os.listdir('/home/autotest')
['hello.py', 'email126pro']

python知识拓展:

如何查看某个函数的使用,可以使用help查看。

>>> help(os.listdir)
Help on built-in function listdir in module posix:

listdir(...)
listdir(path) -> list_of_strings

Return a list containing the names of the entries in the directory.

path: path of directory to list

说明:os.listdir()函数需要一个path路径入参,函数结果返回值是由字符串组成的列表。

4.3非函数却以函数来调用

报错:

>>> t=('a','b','c')
>>> t()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object is not callable

原因:

t为元组,元组不能被调用,不能加()。初学者编写代码时,偶尔粗心会将变量当做方法来调用(不小心加了括号)。所以要认真检查下是否变量加了括号,或者方法漏加了括号。

解决方案:

将括号去除。

>>> t
('a', 'b', 'c')

5.IOError输入输出错误

5.1文件不存在报错

报错:

>>> f=open("Hello.py")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: [Errno 2] No such file or directory: 'Hello.py'

原因:

open()函数没有指明mode,默认为只读方式,如果该目录下没有Hello.py的文件,则会报错,可查看是否拼写有错误,或者是否大小写错误,或者根本不存在这个文件。

解决方案:

该目录下有hello.py文件,打开该文件即可。

>>> f=open("hello.py")

python知识拓展:

如何查看python解释器当前路径:

>>> import os
>>> os.getcwd()
'/home/autotest'

查看python解释器当前路径下有哪些文件:

>>> os.listdir('/home/autotest')
['hello.py', 'email126pro']

5.2因文件权限问题报错

报错:

>>> f=open("hello.py")

>>> f.write("test")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: File not open for writing

原因:

open("hello.py")如果入参没有加读写模式参数mode,说明默认打开文件的方式为只读方式,而此时又要写入字符,所以权限受限,才会报错。

解决方案:

更改模式

>>> f=open("hello.py",'w+')
>>> f.write("test")

6.KeyError字典键值错误

报错:

常见报错有,测试一接口,接口返回数据一般是json格式,而测试该接口校验某个值是否正确,如果key拼写错了,就会报KeyError。简单举例如下:

>>> d={'a':1,'b':2,'c':3}
>>> print d['a']
1
>>> print d['f']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'f'

解决方案:

访问d中有的键值,如a,b或c。

推荐书单:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
详解python的数字类型变量与其方法
Nov 20 Python
python批量导入数据进Elasticsearch的实例
May 30 Python
Pandas读取MySQL数据到DataFrame的方法
Jul 25 Python
Django框架使用富文本编辑器Uedit的方法分析
Jul 31 Python
python基于socket进行端口转发实现后门隐藏的示例
Jul 25 Python
python编写计算器功能
Oct 25 Python
python多线程案例之多任务copy文件完整实例
Oct 29 Python
基于python使用tibco ems代码实例
Dec 20 Python
np.random.seed() 的使用详解
Jan 14 Python
python匿名函数lambda原理及实例解析
Feb 07 Python
详解Python中的编码问题(encoding与decode、str与bytes)
Sep 30 Python
只用20行Python代码实现屏幕录制功能
Jun 02 Python
Python 函数基础知识汇总
Mar 09 #Python
Python 使用with上下文实现计时功能
Mar 09 #Python
TensorFlow搭建神经网络最佳实践
Mar 09 #Python
TensorFlow实现Batch Normalization
Mar 08 #Python
用Django实现一个可运行的区块链应用
Mar 08 #Python
Python pyinotify日志监控系统处理日志的方法
Mar 08 #Python
TensorFlow模型保存和提取的方法
Mar 08 #Python
You might like
PHP 防注入函数(格式化数据)
2011/08/08 PHP
php下载文件的代码示例
2012/06/29 PHP
PHP多维数组转一维数组的简单实现方法
2015/12/23 PHP
基于php实现的php代码加密解密类完整实例
2016/10/12 PHP
Linux下源码包安装Swoole及基本使用操作图文详解
2019/04/02 PHP
jQuery中fadeIn、fadeOut、fadeTo的使用方法(图片显示与隐藏)
2013/05/08 Javascript
JS实现随机化快速排序的实例代码
2013/08/01 Javascript
如何设置iframe高度自适应在跨域情况下的可用方法
2013/09/06 Javascript
JavaScript中this的使用详解
2013/11/08 Javascript
浅谈JS中的!=、== 、!==、===的用法和区别
2016/09/24 Javascript
vue实现商城上货组件简易版
2017/11/27 Javascript
React Native 使用Fetch发送网络请求的示例代码
2017/12/02 Javascript
使用vue如何构建一个自动建站项目
2018/02/05 Javascript
详解elementui之el-image-viewer(图片查看器)
2019/08/30 Javascript
浅谈vue中$bus的使用和涉及到的问题
2020/07/28 Javascript
如何使用原生Js实现随机点名详解
2021/01/06 Javascript
vue二选一tab栏切换新做法实现
2021/01/19 Vue.js
pycharm设置鼠标悬停查看方法设置
2019/07/29 Python
Matplotlib使用Cursor实现UI定位的示例代码
2020/03/12 Python
解决Python Matplotlib绘图数据点位置错乱问题
2020/05/16 Python
对pytorch中x = x.view(x.size(0), -1) 的理解说明
2021/03/03 Python
Flask中jinja2的继承实现方法及实例
2021/03/03 Python
html5 Canvas实现图片旋转的示例
2018/01/15 HTML / CSS
elf彩妆英国官网:e.l.f. Cosmetics英国(美国平价彩妆品牌)
2017/11/02 全球购物
澳大利亚在线家具、灯饰和家居装饰店:LivingStyles
2018/11/20 全球购物
世嘉游戏英国官方商店:SEGA Shop UK
2019/09/20 全球购物
解释一下Windows的消息机制
2014/01/30 面试题
传播学专业毕业生自荐信
2013/11/04 职场文书
公益广告宣传方案
2014/02/28 职场文书
财务总监岗位职责
2015/02/03 职场文书
2016元旦晚会主持词开场白和结束语
2015/12/04 职场文书
在校大学生才艺比赛策划书怎么写?
2019/08/26 职场文书
《敬重卑微》读后感3篇
2019/11/26 职场文书
python munch库的使用解析
2021/05/25 Python
IDEA使用SpringAssistant插件创建SpringCloud项目
2021/06/23 Java/Android
Redis实现短信验证码登录的示例代码
2022/06/14 Redis