Python Forum

Full Version: While Loop Problem
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,
i'm very very new to python, but familiar with vba, so understand how basics work and in this case a loop.

I have the following code:

i = 1
num_page = 1
bar = progressbar.ProgressBar(max_value=response['meta']['total'], widgets=widgets).start()
print("Total number of records : ", response['meta']['total'])
while i <= response['meta']['total']:
...more code here to retrieve records...

bar.update(i)
        i = i + 1
Run ok, but then I get an error:
Error:
Total number of records : 494 [Elapsed time: 0:06:18] |**********************************| (ETA: 00:00:00) Traceback (most recent call last): File "C:\Users\Admin\Downloads\patients_wip.py", line 118, in <module> bar.update(i) File "C:\Users\Admin\AppData\Local\Programs\Python\Python311\Lib\site-packages\progressbar\bar.py", line 672, in update raise ValueError( ValueError: Value 495 is out of range, should be between 0 and 494 [Elapsed time: 0:06:19] |**********************************| (Time: 0:06:19)
I've tried changing from
while i <= response
to
while i < response

I have made it print at each i, and it will print up to the total number of records.

Any advice and guidance would be greatly appreciated.
Which of the many progressbar packages are you using?

Python indexing starts with 0, not 1. "i" should be initialized to 0, not 1. You are skipping doing something with your first record.

But there is something else going on that you aren't showing. How is "i" getting to 495 if there are 494 records? Does response['meta']['total'] change inside the loop? Is there another place where "i" is changed inside the loop?

It is unusual seeing a while loop in Python. for loops are the loop of choice for a counting loop. I might write your code like this:
bar = progressbar.ProgressBar(max_value=response['meta']['total'], widgets=widgets).start()
print("Total number of records : ", response['meta']['total'])
for i in range(response['meta']['total']):
    . . .
    bar.update(i)