Python中的缩进问题


在学习的时候,即使按照教程的例子来操作;也偶尔难免会出现错误;当我参照例子输入一些命令的时候,有时候一不小心就很容易多了或者少了缩进。


举个例子,写一个名为for.py的文件:

#!/usr/bin/python 
# Filename: for.py 

for i in range(1,6): 
    print i 
else: 
print 'The for loop is over' 

然后运行它,将会返回“IndentationError: expected an indented block”的错误;提示第7行格式不对,期望一个缩进的块

# ./for.py    
  File "./for.py", line 7
    print 'The for loop is over'
        ^
IndentationError: expected an indented block

所以我们在第7行加上缩进

#!/usr/bin/python 
# Filename: for.py 

for i in range(1,6): 
    print i 
else: 
    print 'The for loop is over' 

然后再运行,就不会出错了。

 

再举个例子,写一个名为ex1.py的文件:

#!/usr/bin/python 
# Filename: ex1.py 
print "Hello World!" 
print "Hello Again" 
print "I like typing this." 
print "This is fun." 
print 'Yay! Printing.' 
print "I'd much rather you 'not'." 
    print 'I "said" do not touch this.' 

    
 然后运行它,将会返回“IndentationError: unexpected indent”的错误,提示第9行不需要缩进
 
 # ./ex1.py 
  File "./ex1.py", line 9
    print 'I "said" do not touch this.'
    ^
IndentationError: unexpected indent

根据提示,去掉第9行的缩进

#!/usr/bin/python 
# Filename: ex1.py 
print "Hello World!" 
print "Hello Again" 
print "I like typing this." 
print "This is fun." 
print 'Yay! Printing.' 
print "I'd much rather you 'not'." 
print 'I "said" do not touch this.' 

接着再运行ex1.py,就成功了。

由此可知,python对于格式的要求是非常严格的;所以刚开始学习就应该很仔细地领会这些。

Monday, March 24, 2014 | Python

文章评论

No comments posted yet.

发表评论

Please add 5 and 7 and type the answer here: