Skip to main content

Command Palette

Search for a command to run...

Python If Else and Code Branching

Published
2 min read
Python If Else and Code Branching

Python, like most programming languages, has an if statement that provides branching in your code. An example syntax of Python’s if statement:

x = 3
y = 4

if x == y:
    print("They are equal")
else:
    print("They are not equal")

The else branch is optional:

if x == y:
    print("They are equal")

The expression can be anything that evaluates a True or False Example:

  1. if num >= 5:

  2. if str == “What’s up?”:

  3. if this != that:

  4. if SomeVar:

Take note of example 4 above — in Python, anything that does not equate to zero, Null, or an empty object is True. 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")
...     
True

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

< is Less than <= is Less than equal > is Greater than >= is Greater than or equal == is Equal != is Not equal is Is a particular object is not Is not a particular object

Boolean operations are also supported for negating and chaining expressions:

    or is Either expression can be True
    and is Both expressions must be True
    not is Negate the preceeding expression

Python also supports multiple branching using the elif 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 exp2 is True

Reference:

Build your first website with Python and Django: Build and Deploy a website with Python & Django

10 views

More from this blog

F

Freelance Full-Stack Developer | Django + React | Shopify, WordPress & Automation | I Build Web Experiences That Convert

92 posts

Freelance Full-Stack Developer | Django + React | Shopify, WordPress & Automation | I Build Web Experiences That Convert