Nearby lessons

43 of 159

Python - For Loop

📌 What You Will Learn
  • Define the for loop and the sequences it can iterate over
  • Understand the three forms of the range() function
  • Use range(n) to generate numbers from 0 to n-1
  • Use range(begin, end) to print a range of numbers
  • Use range(begin, end, step) to print even, odd and reverse-order numbers

What is a for Loop?

If we want to execute a group of statements for every element present in a sequence, we use the for loop.

A sequence can be a string, list, tuple, set, range, or dictionary.

Syntax of for Loop

Loading editor…

Another Syntax

Loading editor…

Flow of for Loop

  1. Take the first element from the sequence.
  2. Execute the loop body.
  3. Take the next element.
  4. Repeat until all elements are processed.
  5. When there are no more elements, the loop stops.

range() Function

The range() function is used to generate a sequence of numbers.

It returns a range object.

Three Forms of range()

Form Description
range(n) Generates numbers from 0 to n-1.
range(begin, end) Generates numbers from begin to end-1.
range(begin, end, step) Generates numbers using the specified step value.

Form 1 - range(n)

This form generates numbers from 0 to n-1.

Example 1 - Print Numbers from 0 to 9

Loading editor…

Explanation

range(10) generates numbers from 0 to 9.

The value 10 is not included.

Example 2 - Print "Hello" 5 Times

Loading editor…

Form 2 - range(begin, end)

This form generates numbers from begin to end-1.

Example 1 - Print Numbers from 10 to 20

Loading editor…

Explanation

The starting value is included.

The ending value is excluded.

Therefore, range(10, 21) prints numbers from 10 to 20.

Example 2 - Print Numbers from 1 to 10

Loading editor…

Example 3 - Print Numbers from 5 to 10

Loading editor…

Form 3 - range(begin, end, step)

The third argument specifies the increment or decrement.

Example 1 - Print Even Numbers

Loading editor…

Explanation

The value increases by 2 after every iteration.

Only even numbers are printed.

Example 2 - Print Odd Numbers

Loading editor…

Example 3 - Print Numbers from 10 to 1

Loading editor…

Explanation

A negative step decreases the value after every iteration.

This prints the numbers in reverse order.

Example 4 - Print Even Numbers in Reverse

Loading editor…

Example 5 - Print Numbers from 10 to 0

Loading editor…
📝 Key Takeaways
  • The for loop executes a group of statements for every element in a sequence
  • A sequence can be a string, list, tuple, set, range or dictionary
  • range() generates a sequence of numbers and returns a range object
  • range(n) generates numbers from 0 to n-1
  • A negative step value prints numbers in reverse order

🧠 Test Your Knowledge

3 Questions
Progress: 0 / 3

Finished this lesson?

Mark it as complete to track your progress and see technology completion stats.