How to Indent a Python File
- 1). Open your Python program and start a new program file.
- 2). Type the following:
myNum = 5
print "Hello, world!"
abs(3)
Variables, print statements or other functions that consist of one line of code do not require indenting. These lines generate an error if the parser finds any leading white space. - 3). Type the following:
if myNum == 1:
--> print "Number is 1."
elif:
--> print "Number is 2."
else:
--> print "Number is not 1 or 2."
--> print "Could not find number."
The "-->" represents an indentation, whether it be a tab or a blank space. When using an if statement, the "if," "else" and all "elif" statements are aligned with each other while all executable possibilities are aligned as well. Note that the "else" statement uses a multi-line code block, each line of which aligns with the same indenting rules. - 4). Type the following:
for x in range(1, 5):
--> if x == myNum:
--> --> print "myNum is", x
--> else:
--> --> print "myNum is not", x
These lines use an if statement nested within a for statement. The if code block follows its own indenting, all of which are added to the for statement to which it belongs. - 5). Type the following:
def simpleFunction():
--> print "This is a one-line function."
When defining a new function, do not indent the declaration (first) line. Indent every subsequent line that is part of the function at least once. - 6). Type the following:
def largerFunction():
--> print "This is a multi-line function."
--> myVar = raw_input("Type something:")
--> if isinstance(myVar, str):
--> --> if myVar == "":
--> --> --> print "You entered nothing."
--> --> else:
--> --> --> print "You entered a string."
--> else:
--> --> print "You entered a number."
Again, each code block follows its own indenting rules, which are added to those of the statement it is nested within.
Source...