Python学习笔记之缩进

来源:互联网 发布:3ds怎么网络联机 编辑:程序博客网 时间:2024/06/06 20:04

在Python语言中,对缩进十分敏感。

1、Python缩进分为空格和tab两种,要求每级缩进长度为4,可以使用4个空格或者一个tab(需要在编辑器中设置tab长度为4)

2、每一个缩进表示代码的一个逻辑层,python是通过缩进来划分程序逻辑的

在今天的学习过程中,在文件的一个操作中出现了如下错误,导致提醒I/O operation on closed file错误,实际是是缩进错误

man = []other = []try:data = open('sketch.txt')for each_line in data:try:(role,line_spoken) = each_line.split(':',1)line_spoken = line_spoken.strip()if role == 'Man':man.append(line_spoken)elif role == 'Other Man':other.append(line_spoken)except ValueError:passdata.close()except IOError:print('The datafile is missing!')print(man)print(other)

错误提示:

Traceback (most recent call last):
  File "D:\PythonLearn\HeadFirstPyhton\chapter3\filesave.py", line 5, in <module>
    for each_line in data:
ValueError: I/O operation on closed file.


错误原因是在for循环后应该关闭文件的data.close()操作,因为多了一级缩进,所以导致这一行是在for循环中的,因此关闭文件便无法完成循环

正确代码:

man=[]other=[]try:data = open('sketch.txt')for each_line in data:try:(role,line_sopken) = each_line.split(':',1)line_sopken = line_sopken.strip()if role == 'Man':man.append(line_sopken)elif role == 'Other Man':other.append(line_sopken)except ValueError:passdata.close()except IOError:print('The datafile is missing!')print(man)print(other)



在编码中,可以考虑在函数内部,对于不同逻辑层的代码适当加空行用以区分,使逻辑显示更加 清晰也易于查找错误

0 0
原创粉丝点击