How to perform a loop action at least once and also when a condition is true
<p>I am looking for a  Python logical equivalent of a <code>do while</code> loop in other languages. I have page results I am iterating through. The results structure:</p>

<pre><code>1, 2, 3, 4 , ... NEXT
</code></pre>

<p>Each element there is a link. only the last page has no <code>NEXT</code> element so I have identified <code>NEXT</code> as the condition that i need to check for when iterating.  </p>

<p>I have identified it using :</p>

<p><code>next_link = driver.find_element_by_id('anch_25')</code></p>

<p>So I have a function <code>my_function()</code> that i want to run on each page where <code>next_link</code> exists then click the next_link using a <code>click()</code> function. If the element does not exist it means either there is only 1 page result or I am on the last page of results. Either way, I still want <code>my_function</code> to run in either case.</p>

<p>So i have:</p>

<pre><code>def my_function():
    print "Another result page"

###This is where I am trying to loop through the results pages

next_link = driver.find_element_by_id('anch_25')

if next_link:
    my_function()
    next_link.click()
else:
    my_function()
</code></pre>

<p>Unfortunately, this is only working for the first page and does not iterate over the other pages.</p>

<p>I have also tried this, </p>

<pre><code>while next_link:
    my_function()
    next_link.click()
my_function()
</code></pre>

<p>It doesn't seem to work either. Any suggestions?</p>

<p>Check for the next link <strong>after</strong> calling your function. Then use <code>break</code> to break out of the loop instead of using <code>next_link</code> as the <code>while</code> condition.</p>

<pre><code>while True:
    my_function()
    next_link = driver.find_element_by_id('anch_25')
    if not next_link:
        break
    next_link.click()
</code></pre>

python for-loop while-loop pagination do-while