
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Lines and Indentation in Python
Python provides no braces to indicate blocks of code for class and function definitions or flow control. Blocks of code are denoted by line indentation, which is rigidly enforced.
The number of spaces in the indentation is variable, but all statements within the block must be indented the same amount. For example −
if True: print "True" else: print "False"
However, the following block generates an error −
if True: print "Answer" print "True" else: print "Answer" print "False"
Thus, in Python all the continuous lines indented with same number of spaces would form a block. The following example has various statement blocks −
Note − Do not try to understand the logic at this point of time. Just make sure you understood various blocks even if they are without braces.
#!/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
- Related Articles
- Statement, Indentation and Comment in Python
- Why is indentation important in Python?
- Detection of ambiguous indentation in python
- Code indentation in Lua Programming
- Text Indentation using CSS
- Text Indentation Working with CSS
- How to wrap long lines in Python?
- Difference between Transmission Lines and Distribution Lines
- What are parallel lines and intersecting lines?
- Random access to text lines in Python (linecache)
- Number of Lines To Write String in Python
- Removing Horizontal Lines in image (OpenCV, Python, Matplotlib)
- How to annotate the end of lines using Python and Matplotlib?
- How can we print multiple blank lines in python?
- Iterate over lines from multiple input streams in Python

Advertisements