The if Statement and Code Branching

by Nigel George

Python, like most programming languages, has an if statement that provides branching in your code. The syntax of Python’s if statement is as follows:

if [expression is True]:
    # execute this code when True 
    # execute this code when False

The else branch is optional:

if [expression is True]:
    # only executes when True
# resume code execution

The expression can be anything that evaluates to True or False. A few examples:

  1. if num >= 10:
  2. if str == "Hello:
  3. if this != that:
  4. if SomeVar:

… and so on.

Take note of example 4 above—in Python, anything that does not equate to zero, Null, or an empty object is True. For example:

>>> s = 0
>>> if s:
...    print("True")
...    # Python returns nothing - statement is false
>>> s = 1
>>> if s:
...    print("True")
>>> s = ""
>>> if s:
...    print("True")
...    # Nothing again - statement is false
>>> s = "Hello"
>>> if s:
...    print("True")

Python includes a comprehensive range of boolean operators that you can use within your expressions:

  • <. Less than
  • <=. Less than or equal
  • >. Greater than
  • >=. Greater than or equal
  • ==. Equal
  • !=. Not equal
  • is. Is a particular object
  • is not. Isn’t a particular object

Boolean operations are also supported for negating and chaining expressions:

  • or. Either expression can be True
  • and. Both expressions must be True
  • not. Negate the proceeding expression

Python also supports multiple branching using the elif (short for “else if “) statement:

if [exp1 is True]:
    # execute if exp1 is True 
elif [exp2 is True]:
    # execute if exp2 is True 
elif [exp3 is True]:
    # execute if exp3 is True
# and so on ...

Lesson Resources

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}