Python缩进问题

来源:互联网 发布:矩阵分解 als 编辑:程序博客网 时间:2024/05/01 12:22

Python缩进问题

Python中,是通过代码的缩进,来决定代码的逻辑的。通俗的说,Python中的代码的缩进,不是为了好看,而是觉得代码的含义,上下行代码之间的关系。缩进弄错了,就会导致程序出错,执行结果变成不是你想要的了。

强制缩进其实是Python保持代码风格统一且可读性良好的机制。

python是用缩进来标识语句块的。

学python需要游标卡尺。

import csvcand_path = './candidates.csv' def readCSV(filename):     lines = []     with open(filename, "rb") as f:         csvreader = csv.reader(f)         for line in csvreader:             lines.append(line)     return lines  cands = readCSV(cand_path)  print cands

return的位置缩进不一样,会导致不一样的结果

import csvcand_path = './candidates.csv' def readCSV(filename):     lines = []     with open(filename, "rb") as f:         csvreader = csv.reader(f)         for line in csvreader:             lines.append(line)             return lines  cands = readCSV(cand_path)  print cands

测试结果

import csvcand_path = './candidates.csv' lines = []     with open('./candidates.csv', "rb") as f:         csvreader = csv.reader(f)         for line in csvreader:             lines.append(line)         print lines

解决方法

采用sublime 或者Pycharm编辑来减少Python缩进问题。

python问题:IndentationError:expected an indented block错误

Python语言是一款对缩进非常敏感的语言,最常见的情况是tab和空格的混用会导致错误,或者缩进不对。

s = 200if s >=0:print sFile "C:\Users\bids\Desktop\test.py", line 3print s        ^IndentationError:expected an indented block

在编译时会出现这样的错IndentationError:expected an indented block说明此处需要缩进,你只要在出现错误的那一行,按空格或Tab(但不能混用)键缩进就行。

s = 200if s >=0:    print selse    print -s

References

http://blog.csdn.net/qq_15437667/article/details/52558999

0 0
原创粉丝点击