Python Basics 6 - Loops

One of the most important features of Python is its ability to execute loops. In this blog post, we'll dive into what Python loops are, how they work, and some common use cases. A loop is a sequence of instructions that is executed repeatedly until a certain condition is met.

Updating variables

A common pattern in assignment statements is an assignment statement that updates a variable, where the new value of the variable depends on the old.

x = x + 1

This means “get the current value of x, add 1, and then update x with the new value.” If you try to update a variable that doesn’t exist, you get an error.

while statement

Looping programs are programs that repeat themselves until they satisfy some condition.

while <condition>:
    <expression>
  • The <condition> will evaluate either a True or False value.

  • If the <condition> is true, the while loop will run the <expression> below it.

  • The while loop will then check the <condition> again.

  • It will keep running the <expression> beneath it until the <condition> is False.

For example:

n = 1
while n < 5:
    print(n)
    n = n + 1
Output
1
2
3
4

The while loop above will keep running until n is not less than five.

Iteration

Iteration is the repetition of a process in order to generate a (possibly unlimited) sequence of outcomes. Each repetition of the process is a single iteration, and the outcome of each iteration is then the starting point of the next iteration. - Wikipedia

One characteristic of looping programs is a iteration loop variable. Loop variables are:

  • Initialized (created) outside of the loop.

  • Changed inside the loop.

  • Used in the true/false test to determine whether the loop should continue.

x=3
ans = 0
itersLeft = x
while (itersLeft != 0):
    ans = ans + x
    itersLeft = itersLeft – 1
print(str(x) + '*' + str(x) + ' = ' + str(ans))

In above example itersLeft is the iteration variable.

For Loop

Sometimes we want to loop through a set of things. When we have a list of things to loop through, we can construct a definite loop using a for statement. It’s general format is:

for <variable> in <expression>:
    <expression>

For example:

for n in range(5):
    print(n)

#above program prints from 0 to 4
  • The range() operator returns a list of values (in this case 0 to 4).

  • The first time the program goes through the for loop, it will treat n as the first value in the expression ( in this case, the expression is range(5) ).

  • The program will do whatever the bottom expression says while treating n as the first value in the expression (which is in this case 0).

  • The next time the program runs through the for loop, it will treat n as the second value in the expression (it will do the same thing but treat n as, in this case, 1).

  • The program will keep doing this until it has done this for all the values in the expression.

The <variable> used in for loops is simply a placeholder for the actual values the loop will be running through the expression below.

Range Function

range(start,stop,step)

  • The start is the start value for the range() function (included in output).

  • The stop is the end value for the range() function (not included in output).

  • The step is the number of values to skip between each outputted value.

  • default values are start = 0 and step = 1 and is optional

For example:

range(1, 10, 2)          #will return 1, 3, 5, 7, 9

Looping through Strings

A lot of computations involve processing a string one character at a time. Often they start at the beginning, select each character in turn, do something to it, and continue until the end. This pattern of processing is called a traversal. One way to write a traversal is with a while loop:

fruit = "aaple"
index = 0
while index < len(fruit):
    letter = fruit[index]
    print(letter)
    index = index + 1

The above program will return:

a
a
p
l
e

This loop traverses the string and displays each letter on a line by itself. The loop condition is index < len(fruit), so when index is equal to the length of the string, the condition is false, and the body of the loop is not executed. The last character accessed is the one with the index len(fruit)-1, which is the last character in the string.

Loop control statements

The break and continue statements are two loop control statements that allow you to change the flow of a loop

break

The break statement is used to terminate a loop early. When the break statement is encountered, the loop is immediately terminated, and the program execution continues with the next statement after the loop. Here's an example of how to use the break statement in a for loop:

fruit = "aaple"
for letter in fruit:
    if letter == "l":
        break
    print(letter)

The above program will return:

a
a
p

In this example, the break statement is used to terminate the loop early when the letter is l

continue

The continue statement The continue statement is used to skip the current iteration of a loop and move on to the next iteration. When the continue statement is encountered, the current iteration of the loop is immediately terminated, and the program execution continues with the next iteration. Here's an example of how to use the continue statement in a for loop:

fruit = "aaple"
for letter in fruit:
    if letter == "p":
        continue
    print(letter)

The above program will return:

a
a
l
e

In this example, the continue statement is used to skip the iteration of the loop when letter is p

The break and continue statements are often used in loops to control the flow of the loop. Here are some common use cases for these statements:

  • To exit a loop early when a certain condition is met.

  • To skip certain iterations of a loop when a certain condition is met.

  • To improve the efficiency of a loop by reducing the number of iterations required.

And by this we end python basic series, later in The Pythonic Way we will explore more advanced python programs in next blogs 😄. Liked this article. Follow me on twitter 🐦

References

(Dr. Charles R. Severance, Python for Everybody : Exploring Data Using Python 3 , Chapter 5: Iterations)