Skip to content

Intermediate Python:for loops

Run the hidden code cell below to import the data used in this course.

# Import the course packages
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# Import the two datasets
gapminder = pd.read_csv("datasets/gapminder.csv")
brics = pd.read_csv("datasets/brics.csv")

I'm learning about for loops

A for loop is a control flow statement in programming that is used to repeatedly execute a block of code based on a sequence of values, such as a list or a range of numbers.

The loop continues until all values in a sequence have been processed.

For loops are handy in a variety of programming tasks, such as:

  1. Iterating over elements in a list, tuple, or other iterable data types.
  2. Performing a specific operation a fixed number of times, such as iterating a loop for a set number of iterations.
  3. Generating sequences of numbers, for example using the range() function in Python.
  4. Processing data from external sources such as files, databases or APIs, where the data can be looped through one record or item at a time.
  5. Implementing nested loops for more complex logic, such as iterating over a matrix or a multi-dimensional array.
areas = [11.25, 18.0, 20.0, 10.75, 9.50]

# Print the original list of areas
for area in areas:
    print(area)

# Create new variables for each area and store their names in a list
area_vars = []
for i, area in enumerate(areas):
    var_name = 'a' + str(i+1)
    globals()[var_name] = area
    area_vars.append(var_name)

# Print the new variables and their values
for var_name in area_vars:
    print(var_name, '=', globals()[var_name])

using 'fam' list to loop over each value in list **

Create a for loop that iterates through the fam list and loops through each family member's height in the fam list and assigns it to a new variable with a unique name (h1, h2, etc.). The globals() function is used to create the new variables in the global namespace...

fam = [1.73, 1.68, 1.71, 1.89]

for height in fam : 
    print(height)

height_vars = []
for i, height in enumerate(fam):
    var_name = "h" + str(i+1) # create the variable name
    globals()[var_name] = height # assign the height to the variable
    height_vars.append(var_name) # add the variable name to the list
for var_name in height_vars:
    print(var_name, "=", globals()[var_name])

For Loop over list of lists

using the data set below , I'm going to do a for loop operation to print out in the form "the x is y sqm"

# house list of lists
house = [["hallway", 11.25], 
         ["kitchen", 18.0], 
         ["living room", 20.0], 
         ["bedroom", 10.75], 
         ["bathroom", 9.50]]
# Build a for loop that prints "the <room> is <area> sqm"
for room ,area in house:
    print("the" ,room ,"is" , area ,"sqm")
    print('tadaaa,' ,'there you go')

Explore Datasets

Use the DataFrames imported in the first cell to explore the data and practice your skills!

  • Create a loop that iterates through the brics DataFrame and prints "The population of {country} is {population} million!".
  • Create a histogram of the life expectancies for countries in Africa in the gapminder DataFrame. Make sure your plot has a title, axis labels, and has an appropriate number of bins.
  • Simulate 10 rolls of two six-sided dice. If the two dice add up to 7 or 11, print "A win!". If the two dice add up to 2, 3, or 12, print "A loss!". If the two dice add up to any other number, print "Roll again!".