Module 1 · Lesson 3

Control Flow — Conditionals & Loops

Make your programs smart with if/else decisions and powerful with loops that repeat actions.

Audio: Control Flow — Conditionals & Loops
0:000:00

Control Flow — Conditionals & Loops

So far, your programs execute every line from top to bottom. But real programs need to make decisions and repeat actions. That's what control flow gives you.

Conditionals: If / Else

Conditionals let your program choose different paths based on conditions:

  • if: "If this condition is true, do this"
  • else if / elif: "Otherwise, if this other condition is true, do that"
  • else: "If nothing above was true, do this as a fallback"

The condition is always an expression that evaluates to true or false.

Comparison Operators

| Operator | Meaning | |----------|---------| | == | Equal to | | != | Not equal to | | > | Greater than | | < | Less than | | >= | Greater than or equal | | <= | Less than or equal |

Loops: For and While

Loops repeat a block of code:

  • For loop: When you know how many times to repeat
  • While loop: When you repeat until a condition becomes false

Avoiding Infinite Loops

A while loop runs forever if its condition never becomes false. Always make sure something inside the loop changes the condition — otherwise your program will freeze.

Try It Yourself

  • Change the temperature value and run again — see which branch executes
  • Write a loop that prints the first 10 even numbers
  • Create a "guess the number" game using a while loop

Code Playground

Edit the code below and click Run to see the output. Switch between languages using the tabs.

Loading editor...

Enjoying the lesson? Unlock the full Programming Fundamentals from $4.99/mo.

See plans →