Back to course

Conditional Statements 1: The `if` Keyword

Python Programming: The 0 to Hero Bootcamp

The if Statement

Conditional statements allow your program to make decisions: executing certain code only if a specific condition is met.

Syntax

python if condition: # Code block runs if condition is True statement_1 statement_2

Program continues here regardless

Example: Checking a Condition

We use comparison and logical operators to define the condition.

python hour = 14

if hour < 12: print("Good Morning!")

if hour >= 12: print("Good Afternoon or Evening!")

Output: Good Afternoon or Evening!

Handling Zero or Empty Values (Falsy Values)

In Python, certain values are interpreted as False in a Boolean context, known as 'Falsy' values. Everything else is 'Truthy'.

Falsy Values:

  • False
  • None
  • 0 (integer or float)
  • Empty string ''
  • Empty containers (lists [], dictionaries {}, etc.)

python user_name = '' if not user_name: print("Username cannot be empty.")

count = 0 if count: # This block is skipped because 0 is Falsy print("Count is positive.")