Python Forum
Continue Function for Loops in Python
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Continue Function for Loops in Python
#1
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.
Reply
#2
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
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags
Download my project scripts


Reply
#3
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
Hudjefa likes this post
Reply
#4
Smile 
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.
Reply
#5
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!
Hudjefa likes this post
Reply
#6
(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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Why both loops don't work in python? nau 3 1,858 Sep-21-2022, 02:17 PM
Last Post: rob101
  Why does Python not use parenthesis to contain loops? davidorlow 3 5,399 Jun-09-2021, 06:33 AM
Last Post: Gribouillis
  Why recursive function consumes more of processing time than loops? M83Linux 9 6,055 May-20-2021, 01:52 PM
Last Post: DeaD_EyE
  How to make this function general to create binary numbers? (many nested for loops) dospina 4 6,282 Jun-24-2020, 04:05 AM
Last Post: deanhystad
  Python for loops Kristenl2784 3 69,095 Jun-16-2020, 06:01 PM
Last Post: Yoriz
  Conditionals, while loops, continue, break (PyBite 102) Drone4four 2 4,104 Jun-04-2020, 12:08 PM
Last Post: Drone4four
  For loops in python Boinbo 3 111,535 Apr-18-2020, 01:23 AM
Last Post: buran
  For loops help, using python turtle SemiBeginnerPY 2 6,779 Mar-10-2020, 10:46 AM
Last Post: SemiBeginnerPY

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020