For Loops In Python

This page will go over for loops in Python. My main reference is Starting Out With Python – Second Edition by Tony Gaddis.

 


What Is A For Loop?

A for loop is a count-controlled loop which repeats through code a certain amount of times.

 


The For Loop Structure

In a for loop, there are 4 parts:

  1. for keyword
  2. A counter_variable
  3. in
  4. A List of values or range()

 

 


range()

A compact way of representing a list of numbers such as [0, 1, 2, 3, …, n] is with the use of range(n). Do note that a list in Python starts with an index of o not 1.

 


Examples

In this section, three examples with for loops are presented.

 

Example One

This first example is a simple function which asks for the user’s name and wishes the user a Happy Birthday five times.

 

 

Example Two

In the odd_one_twenty() function, the odd numbers from 1 to 20 are printed.

 

 

Example Three

The last examples is a number countdown where the function’s argument is n. The function call has n = 20 for a countdown from 20 to 0.

 

 

Leave a Reply