Python没有提供大括号来指示用于类和函数定义或流控制的代码块。代码块由行缩进表示,行缩进严格执行。
缩进中的空格数是可变的,但是块中的所有语句必须缩进相同的数量。例如-
if True: print "True" else: print "False"
但是,以下块会产生错误-
if True: print "Answer" print "True" else: print "Answer" print "False"
因此,在Python中,以相同数量的空格缩进的所有连续行将形成一个块。以下示例具有各种语句块-
注意-此时请勿尝试了解逻辑。只要确保您了解各种块,即使它们没有括号也可以。
#!/usr/bin/python import sys try: # open file stream file = open(file_name, "w") except IOError: print "There was an error writing to", file_name sys.exit() print "Enter '", file_finish, print "' When finished" while file_text != file_finish: file_text = raw_input("Enter text: ") if file_text == file_finish: # close the file file.close break file.write(file_text) file.write("\n") file.close() file_name = raw_input("Enter filename: ") if len(file_name) == 0: print "Next time please enter something" sys.exit() try: file = open(file_name, "r") except IOError: print "There was an error reading file" sys.exit() file_text = file.read() file.close() print file_text