Conditionals

Conditionals execute a block of code based on a condition.

General structure#

if condition
  instructions
elif condition
  instructions
else
  instructions
Indentation

Instructions must have more left margin than the if, elif or else line.

Basic condition#

age = 23
if age >= 18
  print "You are of legal age"
How does it work?

A condition is any value or expression that can be represented as true or false. If it’s true, the corresponding code block is executed.

age = 23
condition = age >= 18  # true

if condition  # it's met
  print "The condition is " condition

If we use another type of value, its boolean representation will be attempted. You can review this representation in Truthy values.

text = "Hello"
if text
  print "The text is not empty"

Condition with elif#

The elif is executed only if the previous condition failed.

age <- "Enter your age: "
if age >= 18
  print "You are of legal age"
elif age >= 13
  print "You are a teenager"
elif age >= 6
  print "You are a child"
Multiple elif
  • You can add as many elif branches as you need after an if.
  • Only one of the conditional blocks is executed, the first one to be true.

Condition with else#

The else is executed if none of the previous conditions are met.

age <- "Enter your age: "
if age >= 18
  print "You are of legal age"
elif age >= 13
  print "You are a teenager"
else
  print "You are a minor"
Single else

There can only be one else block at the end of a conditional structure.

Combine conditions#

Use and or or:

age = 16
if age >= 13 and age < 18
  print "You are a teenager"
else
  print "You are not a teenager"
Logical operators

To review more about logical operators (and, or, not), consult the Operators section.