Python入门-行和缩进
学习Python与其他语言最大的区别就是,Python的代码块不使用大括号({})来控制类,函数以及其他逻辑判断。python最具特色的就是用缩进来写模块。
缩进的空白数量是可变的,但是所有代码块语句必须包含相同的缩进空白数量(同一个子块的语句的缩进数量一致),这个必须严格执行。
文件操作的代码为例:
1 import sys 2 3 try: 4 #open file stream 5 file_name = 'abc.txt' 6 file_finish = 'end' 7 file = open(file_name, "w") 8 except IOError: 9 print "There was an error writing to", file_name 10 sys.exit() 11 print "Enter '", file_finish, 12 print "' When finished" 13 file_text = 'a' 14 while file_text != file_finish: 15 file_text = raw_input("Enter text: ") 16 if file_text == file_finish: 17 # close the file 18 file.close 19 break 20 file.write(file_text) 21 file.write("\n") 22 file.close() 23 24 file_name = raw_input("Enter filename: ") 25 if len(file_name) == 0: 26 print "Next time please enter something" 27 sys.exit() 28 try: 29 file = open(file_name, "r") 30 except IOError: 31 print "There was an error reading file" 32 sys.exit() 33 file_text = file.read() 34 file.close() 35 print file_text