Home > Back-end >  Why does my loop counter have an unexpected value after the loop?
Why does my loop counter have an unexpected value after the loop?

Time:12-01

I have some code like:

num_grades = 0
for num_grades in range(8):
    grade = int(input("Enter grade "   str(num_grades   1)   ": "))
    # additional logic to check the grade and categorize it
print("Total number of grades:", num_grades)
# additional code to output more results

When I try this code, I find that the displayed result for num_grades is 7, rather than 8 like I expect. Why is this? What is wrong with the code, and how can I fix it? I tried adding a while loop to the code, but I was unable to fix the problem this way.

CodePudding user response:

The last value num_grades gets assigned is 7 because of the range, the num_grades 1 has no effect on the final value of num_grades

You need to either change the way num_grades changes throughout the flow of the code, or simply add a 1 to the final result.

CodePudding user response:

In python the variable(s) that you use in for loop keep last state after the loop, for num_grades in range(8): will goes from 0 to 7 so after the loop num_grads will be 7

CodePudding user response:

I would add an if-statement in the loop checking the index.

num_grades = 0
for num_grades in range(9):
    if num_grades == 0:
        continue
    grade = int(input("Enter grade "   str(num_grades)   ": "))
    # additional logic to check the grade and categorize it
print("Total number of grades:", num_grades)

I always use if-statements within loops to negate certain indexes. If you're unaware, the continue keyword in a loop resets the loop and increases the loop variable by 1, without doing anything else past it. Since a loop starts at 0, then the code sees that, and skips it. Then, you can have it print num_grades and it'll just output:

1
2
3
4
5
6
7
8
  • Related