Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Add a for Loop

00:00 So far, the invest() function only prints the amount, rate, and years that you pass in as arguments, but of course the invest() function should do a bit more, and what it should do is print the amount of the investment rounded to two decimal places for the number of years.

00:21 I think the next good part to tackle is the number of years.

00:26 So inside the invest() function, start with a for loop: for year in years

00:34 well, actually this must be for year in range(years) because years is a number. And so for example, if the number is 4, you want to loop to the number 4.

00:47 That’s why you need the range() function call. And then you can indent the print() function call inside the for loop, but also since you have the new variable year, now it’s also a good idea to not just print the years, but to print the actual year.

01:05 That’s the step in the for loop that you are at this point. So add another print() function call, and this time you can pass in an f-string where you add in year and then in curly braces {year}, which is the variable year that’s formatted into this string.

01:25 Once you save it and you run it, you see that you now have the print year 0 and then the amount at the rate year 1, 2, and 3, which is not exactly what you want, right?

01:37 You want to start with year 1 up to year 4. So you need to adjust the arguments of the range() function call. Set the first argument to 1, and then loop until years + 1.

01:53 You stop at 5, which means then when you run the module, you will see year 1, year 2, year 3, and year 4.

Become a Member to join the conversation.