Programming · StudentHub Lesson

Loops

Learn how to repeat actions efficiently in code using for and while loops.

18 minBeginner
01

What you will learn

  • Differentiate between for and while loops
  • Use range() to control loop iterations
  • Write a while loop with a stopping condition
  • Avoid infinite loops
  • Use loops to process lists of data
02

Watch the lesson

Python for Beginners – Full Course [Programming Tutorial] · freeCodeCamp.org

Watch on YouTube
03

Topic notes

Main Idea

Loops let a program repeat a block of code multiple times without rewriting it.

Key Concepts

  • for loops iterate a fixed number of times or over a collection
  • while loops repeat as long as a condition remains true
  • range() generates a sequence of numbers for looping
  • Loops can be stopped early using break or skipped using continue

Definitions

  • Iteration: one full pass through a loop's code block
  • Infinite loop: a loop that never stops because its condition is always true
  • break: keyword that exits a loop immediately

Syntax

```python

for i in range(1, 6):

print(i)

count = 0

while count < 5:

print(count)

count += 1

```

Examples

  • Printing numbers 1 to 5 using a for loop
  • Repeating a prompt until valid input is given using a while loop

Common Mistakes

  • Forgetting to update the loop variable in a while loop, causing infinite loops
  • Off-by-one errors with range() bounds
04

Key concepts

for loopswhile loopsrange()break and continueinfinite loops
05

Important terms

Iteration
One complete pass through the body of a loop
Infinite loop
A loop whose condition never becomes false, causing it to run forever
06

Worked examples

Problem

Print 1 to 5 in Python

  1. 1. Use range(1,6)
  2. 2. for i in range(1,6): print(i)

Answer: 1 2 3 4 5

07

Quick revision

  • for loops iterate a known number of times
  • while loops repeat based on a condition
  • range(1,6) produces 1,2,3,4,5
  • break exits a loop early
  • Always update loop variables to avoid infinite loops
08

Check your understanding

Question 1 · Multiple choice

Which loop is best when you know exactly how many times to repeat?

Question 2 · Multiple choice

What does range(1, 4) produce?

Question 3 · True or false

A while loop can run forever if its condition never becomes false.

Question 4 · Short answer

What keyword immediately exits a loop?

Question 5 · Short answer

Write a loop condition to repeat while a variable x is less than 10.

Done with Loops?

Sign in to save your progress across the library.