Get startedGet started for free

Controlling loop execution

A typical pattern is to create a while loop with True as its condition and use a break statement to end it. In this exercise, your manager wants you to assemble a list of the five most recent years that the US had a positive trade gap. The dictionary nea is a mapping of datetimes to floats representing the net export for a given year. An empty list named surplus_years and a datetime named query_date are supplied.

This exercise is part of the course

Intermediate Python for Finance

View Course

Exercise instructions

  • Create a loop with a condition that is always true.
  • Skip steps where net exports are less than zero.
  • Check the number of surplus years gathered.
  • Stop the loop once five years have been gathered.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Loop while true
while ____:
    net_exports = nea.get(query_date, -1)
    query_date = datetime(query_date.year - 1, 1, 1)
    # Skip if net exports are not positive
    if net_exports < 0:
        ----   
    surplus_years.append(query_date)
    # Check if 5 years have been collected
    ____ len(surplus_years) == 5:
        # Stop the loop
        ----
print(surplus_years)
Edit and Run Code