Copyright Anne Dawson 2005 - 2016

This file is: http://www.annedawson.net/Python_Spaces_Indentation.html

Last updated: Saturday 10th January 2015, 12:51 PT, AD

Spaces and Indentation in Python programs

by Anne Dawson PhD

************************************************************************************


Beware of spaces!

Python program statements are written one above the other, as shown in the following example:


print ("Anne was here")
print ("again at work")
print ("having fun with Python")


The 3 line program above is correct and will run producing the expected output.



The program below will generate a syntax error 
because of the space character inserted at the start of the second line.


print ("Anne was here")
 print ("again at work")
print ("having fun with Python")





The if statement
----------------

The if statement starts with the keyword "if" 
followed by a Boolean expression (e.g. x == 10), followed by a colon (:).


x = 10
if x == 10:
   print ('x has a value of 10')
else:
   print ('x does NOT have a value of 10')



Beneath the if line, the statements to be run if the condition is true are entered 
after typing a few space characters. In the example above, three space characters are used.
Any statements to be run after the else: part of the program
also have to be spaced out to the ***same level*** 
by typing 3 space characters before the statement.

Spacing out a program in this way is known as indenting. 

Indentation is part of the syntax of the Python language.


All of the example programs
are shown correctly indented and run successfully.

Click here for the example Python 3 programs

If you use the Tab key instead of using spaces for the purpose of indenting, 
then you must always use the Tab key. 

If you use four spaces, always use four spaces. 

******The Python organisation recommends using four spaces.******



It is highly recommended to use only spaces, or to set the tab level to 4 on the IDLE editor options. 

Mixing Tabs and spaces is a syntax error, even if the program looks correct on the screen! 
You will get an "incorrect indent" error. You have been warned!






Use lots of space to make your programs more readable
----------------------------------------------------

Compare the following two Python programs
which perform exactly the same tasks when they're run.

Which of these two programs do you find easier to read and understand?


Program 1


x=10
y=20
z=30
v=x*y*z
print("Volume is: "+str(v))




Program 2


height  = 10
width   = 20
breadth = 30

volume = height * width * breadth

print ("Volume is: " + str(volume))



HINT: You can put as many blank lines as you wish ***between*** Python statements.



Click here for more on Python indentation and examples using Python 2




************************************************************************************
































Valid XHTML 1.0!

Valid CSS!

Anne Dawson © 1995-2016 | Anne Dawson All Rights Reserved.