Loop Structures

Python has two types of loops. For loop was introduced in the earlier lab. It iterates through items of a list, a tuple, a dictionary, a set, or a string.

While loop executes a block of statements repeatedly as long as the condition is TRUE.

Programmers should use efficient types of loops. Appropriate types of loop depend on the requirements of each program.
https://www.softwaretestinghelp.com/python/looping-in-python-for-while-nested-loops/

For Loop

Let's review for loop we have done before.

for <variable> in <sequence>:
    <body>

The following example asks the user how many numbers we would like to add. Because the for loop is a definite loop, we have to determine the number of iterations at the beginning of the loop.

def main():
    n = int(input("How many numbers would you like to add? "))
    sum = 0.0
    for i in range (n):
        number = float(input("Enter a number: "))
        sum = sum + number

    print("The sum of ", n,"numbers is ", sum)
main()

We cannot use for loop unless we know the number of iterations ahead of time. However, the indefinite loop or conditional loop keeps looping until certain conditions are met.

While loop

Indefinite loop is a loop that will continue to run infinite number of times until it is asked to stop.

In Python, an indefinite loop is implemented using while loop. https://realpython.com/python-while-loop/

while <condition>:
  <body>

As long as the condition is true, the body of the while loop executes repeatedly. The loop stops when the condition is false.

The condition is tested at the beginning of the loop, before the loop body is executed. If the condition is false at the beginning, the loop body will not be executed at all.

https://www.freecodecamp.org/news/python-while-loop-tutorial-do-while-true-example-statement/

Here is an example of a while loop and a for loop performing the same task.

i = 0 # initializing i before the loop
while i<= 5:
    print(i)
    i = i + 1 # incrementing i value by one at the bottom of the loop, so we don't have an infinite loop

-------------------


for i in range(6):# The loop variable i is handled automatically
    print(i)

If you run into an infinite loop, you can use Ctrl-C to stop it if you are in a UNIX environment. You can click on the stop button if you are in a Python IDE environment.

Interactive Loops

The interactive loop involves input from the user each time through.

The following program asks the user every time for input to continue or to quit the program.

def main():
  sum = 0.0
  i = 0
  answer = "Yes"
  while answer == "Yes":
    x = float(input("Enter a number: "))
    sum = sum + x
    i += 1 # same as i = i + 1
    answer = input("Do you want to continue? (Yes/No) ")
  print("The sum of ",i,"numbers is: ", sum)

main()

Output

Enter a number: 23
Do you want to continue? (Yes/No) Yes
Enter a number: 12
Do you want to continue? (Yes/No) Yes
Enter a number: 89
Do you want to continue? (Yes/No) No
The sum of 3 numbers is:  124.0

Sentinel Loops

It is quite tedious being asked every time when you are trying to add a number. We can try to use sentinel loop.

A sentinel value is a special input value that tests the condition within the while loop.

We are using -1 as the special sentinel value for the same example.

def main():
  sum = 0.0
  i = 0
  x = float(input("Enter a number, enter -1 to quit. ")) #Ask the user for a value
  while x != -1: 
    sum = sum + x
    i += 1 # same as i = i + 1
    x = float(input("Enter a number: "))#ask the user for a value again at the end of while loop

  print("The sum of ",i,"numbers is: ", sum)
main()

Output

Enter a number, enter a negative number to quit. 56
Enter a number: 23
Enter a number: 89.24
Enter a number: -8
The sum of 3 numbers is:  168.24

The above program still not perfect since we cannot add -1. One solution is to use an empty string, "".

If a user press the return key, Python returns an empty string.

def main():
  sum = 0.0
  i = 0
  x = input("Enter a number, press enter to quit. ")#Ask the user for a value
  while x != "": 
    y = float(x)
    sum = sum + y
    i += 1 # same as i = i + 1
    x = input("Enter a number: ")#ask the user for a value again at the end of while loop

  print("The sum of ",i, "numbers is: ", sum)
main()

Output

Enter a number, press enter to quit. 45
Enter a number: 142.6
Enter a number: -78
Enter a number: 0
Enter a number: 
The sum of  4 numbers is:  109.6

File Loops

We used a for loop for file input and output in the earlier lab. You can check file IO examples from the earlier lab.

The lines of a file can be read one at a time using readline() method since it reads the next line from a file as a string.

At the end of a file, readline() returns an empty string, which is the sentinel value being used as an end-of-file (EOF) loop.

def main():
    infile = open("input.txt", 'r')
    data = infile.readline() #read in the first value
    sum = 0
    
    while data != "":
        sum = sum + float(data)
        data = infile.readline() #read in the next value
    print("The total is:", sum)
    infile.close()
main()

Input file input.txt has the following numbers in it.

230.78
500.34
100.50
25
600

While loop with break statement

The break statement is used inside the loop to exit out of the loop.

If the break statement is used inside a nested loop (loop inside another loop), it will terminate the innermost loop.

#The program will keep going as long as the user enters an even number
def main():
  while True:
    num = int(input("Enter an integer: "))
    if num %2 != 0:
      print("Odd number.")
      break
    print("even number.")
main()

Output

Enter an integer: 34
even number.
Enter an integer: 0
even number.
Enter an integer: 726
even number.
Enter an integer: -1234
even number.
Enter an integer: 5
Odd number.

While loop with continue statement

The continue statement skips the current iteration and moves to the next iteration.

When the continue statement is encountered inside the loop, it skips all the statements below it and immediately jumps to the next iteration.

# Prints all letters except h, i
i = 0
s = "hiyou"
print(s);
while i < len(s):
    if s[i] == 'h' or s[i] == 'i':
        i = i + 1
        continue      
  
    print(s[i], end='')
    i = i + 1
print()

What is the output?

Here are more examples on break and continue statements.

https://pynative.com/python-break-continue-pass/
https://www.geeksforgeeks.org/python-break-statement/?ref=lbp
https://www.geeksforgeeks.org/python-continue-statement/?ref=lbp
https://www.javatpoint.com/python-break
https://www.javatpoint.com/python-continue

Nested Loops

Nested loops are loops inside of a loop.

Let's look at the following examples.

The multiple for loops are used to print the patterns where the first outer loop is used to print the number of rows, and the inner loop is used to print the number of columns.

Most of the patterns use the following concepts.

  1. The outer loop prints the number of rows.
  2. The inner loop prints the number of columns.
  3. The variables to print symbols or whitespaces according to the program requirement.
def main():
    n = int(input("Input size of the triangle: ")) 
    # outer loop determines number of rows
    for i in range(0, n):
        # inner loop determines number of columns
        for j in range(0, i+1):
            # printing stars
            print("* ",end="")#end="" pass the white space to the end parameter not a newline char
        # line return after each row
        print()
main()

Output

Input size of the triangle: 5
*
* *
* * *
* * * *
* * * * *

Another example on nested for loops. This example is more complicated since we want to print a pyramid shape. So we need to add another loop to print spaces in front of stars.

def main():
    n = int(input("Input size of the pyramid: "))   
    # m is the number of spaces in the front 
    m = n - 1
    # outer loop determines number of rows
    for i in range(0, n):
	# inner loop to handle number of columns  
        for j in range(0, m): 
            print(end=" ")# printing spaces in front of the stars
        # update m after each loop
        m = m - 1 
        for j in range(0, i+1):
            print("* ", end="")# printing stars after spaces
        # line return after each row
        print() 
main()

Output

Input size of the pyramid: 5
    * 
   * * 
  * * * 
 * * * * 
* * * * * 

The following examples demonstrate nested while loops.

"""
Using nested while loops 
to print a multiplication table
"""
def main():
    print("The multiplication table has i X j format.")
    a = int(input("Enter table number (i): "))
    b = int(input("Enter the number to which table is to print to (j): "))
    i=1
    while i<=a:
        j = 1
        while j <= b:
            print(i,"x",j,"=",i*j)
            j = j+1
        i=i+1
        print()
main()

Output

The multiplication table has i X j format.
Enter table number (i): 2
Enter the number to which table is to print to (j): 8
1 x 1 = 1
1 x 2 = 2
1 x 3 = 3
1 x 4 = 4
1 x 5 = 5
1 x 6 = 6
1 x 7 = 7
1 x 8 = 8

2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
2 x 5 = 10
2 x 6 = 12
2 x 7 = 14
2 x 8 = 16

For more examples on nested loop structures, check the following links.

https://www.w3schools.com/python/gloss_python_for_nested.asp
https://pynative.com/python-nested-loops/
https://pynative.com/python-if-else-and-for-loop-exercise-with-solutions/

Lab Assignment

1. Online Music Store

For your birthday, you received a $10 gift certificate for an online music store. The cheapest song in the store costs $0.99. You can buy songs until you can't afford any more songs.

Requirement

Sample output:


Enter the cost of the song, $0.99, $1.99 or $2.99: 0.99
Song purchased for $ 0.99; enjoy!
The remaining balance is 9.01
Enter the cost of the song, $0.99, $1.99 or $2.99: 1.99
Song purchased for $ 1.99; enjoy!
The remaining balance is 7.02
Enter the cost of the song, $0.99, $1.99 or $2.99: 2.99
Song purchased for $ 2.99; enjoy!
the remaining balance is 4.03
Enter the cost of the song, $0.99, $1.99 or $2.99: 1.99
Song purchased for $ 1.99; enjoy!
The remaining balance is 2.04
Enter the cost of the song, $0.99, $1.99 or $2.99: 2.99
Your choice is too expensive. Choose another song.
The remaining balance is:2.04
Enter the cost of the song, $0.99, $1.99 or $2.99: 1.99
Song purchased for $ 1.99; enjoy!
The remaining balance is 0.05
Sorry, the balance is $ 0.05. You can't buy more songs.

2. Complete the program ph_level.py to determine the pH of a solution.

A solution with a pH level less than 7 is acidic; otherwise, it is basic. Determining the pH of a solution is important, since many organisms and micro-organisms can only live in a limited pH range.

Instructions:

Your program should print something like this:

Sample Output:


This program calculates pH level of a solution.
Enter 0 to quit the program.
Please input the concentration of hydroxide: 0.002
The ph level of solution 0.0020000000 is 11.3010299957. The solution is basic.

Please input the concentration of hydroxide: 0.00006
The ph level of solution 0.0000600000 is 9.7781512504. The solution is basic.

Please input the concentration of hydroxide: 0.000000007
The ph level of solution 0.0000000070 is 5.8450980400. The solution is acidic.

Please input the concentration of hydroxide: 0.0000000009
The ph level of solution 0.0000000009 is 4.9542425094. The solution is acidic.

Please input the concentration of hydroxide: 0
You entered 0, so quit the program.