Lesson 11 of 4028%

(Progress persistence is disabled until Phase 9)

Python
Beginner

Conditional Statements

Learn how to make decisions in your code.

Conditional Statements

What You’ll Learn

You’ll learn how to run different blocks of code based on certain conditions using if statements.

The if Statement

The if keyword is used to test a condition. If the condition evaluates to True, the indented block of code below it is executed.

age = 18

if age >= 18:
    print("You are an adult.")
    print("You can vote!")

Expected Output:

You are an adult.
You can vote!

Notice that both print statements are indented, so they both belong to the if block.

What if it’s False?

If the condition is False, Python skips the indented block entirely.

age = 15

if age >= 18:
    print("You are an adult.")

print("End of program")

Expected Output:

End of program

Common Mistakes

  • Missing the colon: Forgetting the : at the end of the if line is a very common syntax error.
  • Indentation errors: Forgetting to indent the block of code inside the if statement will cause an IndentationError.

Lesson Progress

Take QuizBuild a Python Project