Control Flow, Loops, and Functions in Python

In this week’s workshop, you will learn how to make your Python code more powerful and flexible using control flow, loops, and functions. This is the foundation of writing reusable and efficient Python code.

Lab Logo Introduction

Live Logo Live coding

Review the material that we explored in Week 5’s live-coding session.

Lab Logo Lab

Exercise: Write functions to explore Gapminder dataset


You will Use the gapminder dataset:

  1. Write a function filter_country_year() that returns data for a specified country and year.
  2. Write a function calculate_gdp() that adds a new column total_gdp by multiplying gdpPercap and pop.
  3. Use a loop to calculate and print the average lifeExp for each country.
  4. Use a loop to identify and print the country with the highest total_gdp for each year.
  5. Handle possible errors using try-except when country names are not found.
  6. Save the final dataframe with total_gdp column to gapminder_final.csv.
  7. Commit and push your code to GitHub.

Lab Logo Further reading