Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

PY
Python
0/14 completed
Beginner
Hello PythonVariables and typesWorking with stringsConditions and loopsFunctions
Intermediate
Lists, tuples, dicts and setsFiles and exceptionsModules and the standard library
Advanced
Classes and OOPIterators and generatorsDecorators and context managers
Pro
Async PythonTesting and type hintsVirtual environments, packages and real projects
Tracks / Python / Beginner

Conditions and loops

Programs become useful when they make decisions and repeat work. Python has if for decisions and for / while for repetition.

if, elif, else

Python · editable

Python checks each condition from top to bottom and runs only the first block that's true. Change the input and run again.

Combining conditions

Python · editable

The one-line conditional expression

Python · editable

match: checking one value against many patterns

Python 3.10 added match, which is cleaner than a long elif chain when you compare one value against several options:

Python · editable

_ is the wildcard ("anything else"). Notice ["go", direction] also captures the second word into a variable.

for loops

A for loop runs once for each item in a sequence:

Python · editable

range(): looping a number of times

Python · editable

enumerate and zip

Python · editable

Use enumerate instead of range(len(...)) when you need the index, and zip to walk several lists together.

while loops

A while loop repeats as long as its condition is true. Use it when you don't know in advance how many times to loop:

Python · editable

⚠️ Make sure the condition eventually becomes false, or the loop runs forever. (The editor stops runaway code after 10 seconds.)

break, continue and else

Python · editable

A loop's else block runs only if the loop finished without break, which is perfect for searches:

Python · editable

Nested loops

Python · editable

A small game: guess the number

The program picks a number; each guess comes from the Input box:

Python · editable

Change the guesses in the Input box, or use import random and random.randint(1, 100) to pick a different secret each time.

Practice

  1. FizzBuzz: print the numbers 1 to 30, but "Fizz" for multiples of 3, "Buzz" for multiples of 5, and "FizzBuzz" for multiples of both.
  2. Print a triangle of * with 5 rows (hint: "*" * n).
  3. Add up all the digits of a number such as 98765 using a while loop with % 10 and // 10.
Python · editable
✎ Check your understanding

1.How many times does for i in range(2, 8, 2) run?

2.What does continue do inside a loop?

3.When does a for loop's else block run?

← Working with strings