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.
Introduction
Live coding
Review the material that we explored in Week 5βs live-coding session.
Lab
Exercise: Write functions to explore Gapminder dataset
You will Use the gapminder dataset:
- Write a
function filter_country_year()that returns data for a specified country and year. - Write a function
calculate_gdp()that adds a new columntotal_gdpby multiplyinggdpPercapandpop. - Use a loop to calculate and print the average
lifeExpfor each country. - Use a loop to identify and print the country with the highest
total_gdpfor each year. - Handle possible errors using
try-exceptwhen country names are not found. - Save the final dataframe with
total_gdpcolumn togapminder_final.csv. - Commit and push your code to GitHub.
Further reading
- Beazley, D. (2023). Python Distilled. OβReilly Media. https://www.oreilly.com/library/view/python-distilled/9780134173399/
- Python Software Foundation. Python Control Flow. https://docs.python.org/3.10/tutorial/controlflow.html