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.
Este exercício faz parte do curso
Intermediate Python for Finance
Instruções do exercício
- 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.
Exercício interativo prático
Experimente este exercício completando este código de exemplo.
# 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)