Python Spaces and Spacing

Spaces

Python is space sensitive so it is important to be careful with your whitespace.  Other programming languages will ignore all whitespace.  Python only cares about the whitespace to the left of your code.  Not above, below or to the right of your code.  Essentially it is the tabs it cares about.

Every time you tab you go from a parent to to a child block of code.  The parent will end in a colon (:) and the child will be one tab indent in from the parent.  If you look at the “if” loops you can se clearly the child parent relationship.

#im_a_parent:
    #im_a_child:
        #im_a_grandchild
    #im_another_child:
        #im_another_grand_child
#parent block of code
x = 30
if x > 10:
    #child block of code
    print("greater than 10")
    if x > 20:
        #grandchild block of code
        print("greater than 20")

Each block executes on its own.

Spacing

When outputting white space you can use a few tricks to make life easier as well. Here is the code to output a letter style format.

spaces = ' ' * 25
print('% s Mr. Ferguson' % spaces)
print('% s Cafe Ferguson' % spaces)
print('% s 555 Westside Rd' % spaces)
print()
print()
print(' Dear Sir')
print()
print(' I am on my way to get my latte - keep it warm!')
print()
print(' Please charge my account as usual.')
print()
print(' Regards')
print(' Mr. Loves Coffee')
print('% s Mr. Ferguson' % spaces)

What is this little bit of code all about you ask?   The % is a placeholder and what comes at the end of the parenthesis is the value that gets applied to the placeholder, in this case “spaces” variable which is equal to 25 spaces.