Python Forum

Full Version: Continue Function for Loops in Python
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
At the very early stages of learning Python. Currently learning Python loop functions and what they can do. I'm a bit confused about the continue function available for loops. Here's a short code that I wrote:

import random
count = 0

for attempts in range(1000):
    result = random.randint(0, 99)
    count = count + 1
    if result != 25:
        continue
    else:
        print("You got it. The number is 25")
        print("Number of attempts = " + str(count))
        break
        
For every new function that I learn I write a short code showcasing that function. I'm trying to do just that above, having just learnt the continue and break functions. It then dawned on me that the code above is a loop by default. I really don't need to add that continue there. Can anyone help me write a code where the continue is "meaningful" in the sense it isn't redundant? You can give me a simple problem that I can try to code.
A basic example would be the for loop you are using
number = 5
for i in range(10):
    if i == number: # If i is = number (5) don't print go to next
        continue
    print(i)
output
Output:
0 1 2 3 4 6 7 8 9


Using your example

from random import randint
counter = 0
for attempts in range(1, 1000):
    result = randint(1, 100)
    if result != attempts:
        counter += 1
        continue
    print(f'Number is {result}')
    print(f'Attempts: {counter}')
Output
Output:
Number is 97 Attempts: 96
It is difficult to write a short example that really shows the power of continue, because continue is tool for unknotting complicated logic. Looking at your example:

continue jumps you back to the top of the loop, so the else statement is not needed.
import random
count = 0
 
for attempts in range(1000):
    result = random.randint(0, 99)
    count = count + 1
    if result != 25:
        continue
    # cannot get here if result != 25.  No need for else
    print("You got it. The number is 25")
    print("Number of attempts = " + str(count))
    break
This works, and the continue statement is doing something useful, but the logic is awkward. I would change the condition to get rid of the continue:
import random
count = 0
 
for attempts in range(1000):
    result = random.randint(0, 99)
    count = count + 1
    if result == 25:
        print("You got it. The number is 25")
        print("Number of attempts = " + str(count))
        break

That looks better, but it looks odd having a for loop and a counter. It is possible that more than 1000 attempts are required for randint to return 25. Using a for loop is a logic error. Replace the for loop with a while loop:
count = 1
while random.randint(0, 99) != 25:
    count += 1
print("You got it. The number is 25")
print("Number of attempts = " + str(count))
This is how the code should be written. Sadly neither continue nor break are a good fit for your example.

The main use for continue is to prevent the walking indent of multiple nested if statements. Instead of:
for element in sequence:
    if condition1:
        statement1
        if condition2:
            statement2:
            if condition3:
                statement3
You can instead do:
for element in sequence:
    if not condition1:
        continue
    statement1
    if not condition2:
        continue
    statement2:
    if condition3:
        continue
    statement3
The advantage of using continue don't become apparent until statement1, 2, 3 become blocks of statements

I'm more likely to use continue when if/else results in the "else" statement being many lines below the "if" statement. Instead of this:
for element in sequence:
    if condition1:
        statement1A
        if condition2:
            statement2A
        else:
            statement2B
    else:
        statement1B
Do this:
for element in sequence:
    if not condition1:
        statement1B
        continue
    statement1A

    if not condition2:
        statement2B
        continue
    statement2A
First and foremost, muchas gracias for the posts. They're very helpful.

So continue and break functions are there to, in a sense, break/short the circuit the loop (exit the loop when certain conditions are satisfied and skip blocks of code there's no point in executing because certain conditions are not met). It also makes for better readability.

It seems I'm making a lot of mistakes in my coding. I'm just around 10 (very basic) programs in, practicing calling functions. I'll have to try solving real problems with my programs and may be all your helpful tips and pointers will begin to make sense.

Is it ok to ask such questions at my stage of learning Python? They seem like I haven't done my homework so to speak.

I have a few more questions which I hope I can ask.
The thing about Python is, there is so much information on the internet.

This is a nice page about continue, break and pass.

For more detailed information, look here or look here.

¡disfruta!
(Aug-13-2024, 06:01 AM)Pedroski55 Wrote: [ -> ]The thing about Python is, there is so much information on the internet.

This is a nice page about continue, break and pass.

For more detailed information, look here or look here.

¡disfruta!

Angel Muchas gracias