Python: Flow Control

Materials by: John Blischak and other Software Carpentry instructors (Joshua R. Smith, Milad Fatenejad, Katy Huff, Tommy Guy and many more)

In this lesson we will cover how to write code that will execute only if specified conditions are met.

If statements

One of the simplest ways to construct a "condition" is with conditional operators:

  • < less than
  • > greater than
  • <= less than or equal to
  • >= greater than or equal to
  • == equals
  • != not equals

    Here's how you can use them in conditional statements


In [ ]:
x = 5
if x < 0:
    print "x is negative"

In [ ]:
x = -5
if x < 0:
    print "x is negative"

In [ ]:
x = 5
if x < 0:
    print "x is negative"
else:
    print "x in non-negative"

In [ ]:
x = 5
if x < 0:
    print "x is negative"
elif x == 0:
    print "x is zero"
else:
    print "x is positive"

Be careful because the computer interprets comparisons very literally.


In [ ]:
'1' < 2

In [ ]:
True == 'True'

In [ ]:
False == 0

In [ ]:
'Bears' > 'Packers'

Indentation

Indentation is a feature of python intended to make it more human-readable (though some people hate it). Some other programming languages use brackets to denote a command block. Python uses indentation. The amount of indentation doesn't matter, so long as everything in the same block is indented the same amount. The IPython notebook automatically converts tabs to 4 spaces, and any decent text editor will do the same (though not necessarily by default).

But you should pick a number of spaces (specifically 4, as this is the standard) and stick to that!

Short Exercise

Write a function using an if statement that prints whether x is even or odd.


In [ ]:
def even_or_odd(x):
    return "I have no idea!" # Fix that!