For the complete documentation index, see llms.txt. This page is also available as Markdown.

Extensions

Break, Continue, Enumerate, Strings as Lists, List comprehension

Break and Continue

Sometimes we want to exit a for/while loop before the defining condition is met, or skip some of the iteration steps. Break and Continue statements provide this functionality respectively - Note it is not good practice to use these unnecessarily, as you can usually just define the loop condition differently.

Break

If we want to exit a loop prematurely, we can use the break statement.

# break statement use
num = 0
while num < 10:
    if num == 5:
        break
    print(num)
    num = num + 1

# This code will print "0 1 2 3 4" - I.e. the loop  is cut short

For an actual usage example, suppose we want to find a prime number greater than 9000, but less than 10000 (not knowing if there is one in this range):

num = 9000
while num < 10000: 
    if is_prime(num): # suppose we have an is_prime() function
        print(str(num) + " is a prime number")
        break
    num = num + 1

Continue

Continue allows us to skip iteration steps inside a loop. This might be helpful if we have a complicated for loop which shouldn't carry out its usual operation in a certain case.

For example, we could print the even numbers < 10:

Note: This is not actually a sensible use of continue, as there are far better ways of printing even numbers in a range (for example, x2 every element in range/2).

Enumerate

Sometimes we want to iterate through a list, accessing its elements but also keeping track of the corresponding index. Whilst we could use a counter variable to do this manually, Python's built-in enumerate() function provides and elegant way of doing this:

Strings as lists of characters

Some of you may have noticed that we can use the "in" function on strings as well as lists:

Equivalent to

For our purposes, we can think of strings as lists of characters, and manipulate them as we would lists - slicing and all!

Here's a simple example demonstrating reverse iteration through a string:

And another example showing some contrived list slicing:

Last updated