We're making some improvements. Some features may be temporarily unavailable.
beginner25 min

Control Flow

Making decisions with if/else and repeating with loops

Making Decisions: if/elif/else

Programs need to make decisions. Python uses if, elif (else if), and else:

Basic if/else

Output
Run your code to see output here

Important: Indentation Matters!

Python uses indentation (spaces at the start of a line) to define blocks of code. The standard is 4 spaces. Every line inside an if block must be indented at the same level.

Comparison Operators

Output
Run your code to see output here

Logical Operators

Combine conditions with and, or, not:

Logical Operators

Output
Run your code to see output here

Loops: Doing Things Repeatedly

For Loops

Use for to iterate over a sequence:

For Loop Basics

Output
Run your code to see output here

While Loops

Use while to repeat as long as a condition is true:

While Loop

Output
Run your code to see output here

Check Your Understanding

What keyword do you use for 'else if' in Python?

Check Your Understanding

How many times will this loop run: `for i in range(3):`?

Exercise

Write a program that prints all even numbers from 2 to 20 (inclusive). Use a for loop and an if statement to check if a number is even (hint: use the modulo operator `%`).

Python will load on first run

Questions & Discussion

Sign in to ask a question or join the discussion.

Loading comments...