Cheat Sheet Python If Else Statement

journey into python

This cheat sheet python if elif else statement comes from the Python If Else Statement learning post. You can also check out Python.org for more information on if elif else statements. Cheat Sheet Python If Else Statement is one of many cheat sheets that we are creating to help everyone out. It’s for those that always forget the small things(like me).

You can use the python if elif else statement to conditionally execute a statement or a block of statements. Conditions can be true or false. They execute one thing when the condition is true and something else when the condition is false.

Comparison operators

  • Equal To: a == b
  • Not Equal: a != b
  • Less Than: a < b
  • Less Than or Equal To: a <= b
  • Greater Than: a > b
  • Greater Than or Equal To: a >= b

Logical operators

  • b and a: True if both b and a are True. False otherwise.
  • a or b: True if either a or b or both are True. False if both are False.
  • not a: True if a is False, False if a is True.

Branching blocks

In Python, we branch our code using if, elif, and else. This is the branching syntax:

if condition1:
    body
elif condition2:
    body
else:
    body

Common Mistakes:

An elif statement must follow an if statement, and the body will only be executed if the if statement condition is False. The if body will be executed if condition 1 is True. Only the elif body will be executed if condition 1 is False and condition 2 is True. The else body will be executed when all the other specified conditions are False.

Typical use:

Python if else statements allow you to create branching for your script, this instructs your computer to make decisions based on inputs.