script_24.py - While Loop with Counter
Code
#!/usr/bin/env python3
"""While loop with counter"""
count = 0
limit = int(input("Count up to: "))
while count < limit:
count += 1
print(count)
print("Done counting!")
Explanation
Line 4: count = 0
- Counter variable initialized before loop
- Integer type
- Must exist before while condition checked
Line 5: limit = int(input("Count up to: "))
- Upper bound for counting
Line 7: while count < limit:
- Loop continues while count is less than limit
- Condition checked before each iteration
- If limit=5: runs while count is 0,1,2,3,4 (stops when count=5)
Line 8: count += 1
- Increments counter (must be inside loop)
- Without this, loop would be infinite (count never changes)
- Ensures condition eventually becomes False
- += equivalent to count = count + 1
Line 9: print(count)
- Prints current value after increment
- Prints 1, 2, 3, 4, 5 (not 0)
Line 11: print("Done counting!")
- Executes after loop exits (when count >= limit)
- Not indented under while