Here is the program that I am working on. The first part (with the “for loop”) works as expected. It prints out the following list:
Month 1 is January
Month 2 is February
Month 12 is December
I am trying to get the same output using a “while loop” but I am getting an error that x is undefined but the same coding works for the “for loop”.
make list for months of the year. Run a loop to generate month number and print Month number is correlated with month name
months_of_the_year = [“January”, “February”, “March”, “April”, “May”, “June”, “July”, “August”, “September”, “October”, “November”, “December”]
for x in range(0, 12):
print("Month " + (str(x+1)) + " is " + months_of_the_year)
i = 1
while i <= 12:
print("Month " + str(i) + " is " + (months_of_the_year)
i = i + 1
Thanks for looking at this. As I am tying to learn difference between using “for loop” and “while loop”.
I was able to get the while loop working. Not sure exactly why it works but here is what I ended up doing:
i = 0
while i in range(0, 12):
print("Month " + str(i+1) + " is " + months_of_the_year[i])
i = i+1
I think I need to better understand how the 2 different loops function and how they execute there process.
Thanks to those who considered this issue.
This is a classic off-by-one issue. Your array is indexed as 0 - 11. In your for loop, you referenced x+1 to generate 1-12. You used the RANGE function. That stops at 11. So x+1 becomes 1-12. While x itself is 0-11. So the index works fine.
When you did the while loop, you started with 1. That puts you one-off. If you want your i variable to start at 1, then you have to minus 1 for your months_of_the_year index because those are 0-11.
Many things in the world of programming start with 0 instead of 1. That’s because these are OFFSETS not COUNTS. You count from 1 because 1 means you have 1 item. But offsets (in lists) means distance from beginning. So you start those with 0. That’s why arrays are always indexed from 0. It’s always confusing.
When you see errors like this, it’s invariably an off-by-one issue.
Hopefully that helps to explain what happened.
Otherwise: The difference between a while loop and a for loop … for loops are great for working through a list. While loops are great for working until you hit a condition. Both can be effective at any task. But that’s the main difference. WHILE is like looking for a result. FOR is like working through a list.
Thanks for responding. I will try (-1). Thanks again.