Break Statement—Python

I’ve done a few posts now on loops. To review, Python has two kinds of loops: while loops and for loops.

I can think of plenty of times that we want to create an infinate loop. To review, an infintate loop is a loop that never ends. Consider this code.

while True:
    pass

Should you run this code, the program will never terminate because the loop condition is always True. In many cases, infinate loops are the result of programming errors, but let’s consider a menu driven program like this:

while True:
    print('1) New File')
    print('2) Open File')
    print('3) Save File')
    print('4) Exit...')

    choice = input('Enter choice => ')
    if choice == 1:
        pass # do something with a new file
    elif choice == 2:
        pass # do something to open a file
    elif choice == 3:
        pass # do something to save a file
    elif choice == 4:
        break # exit this loop and end the application

In this case, we want the program to program to continue to repeat this main menu until the user enters 4. That’s where the magic break keyword comes into play.

The break keyword liternally means to break out of a loop. This example is a common application of the loop but it doesn’t always have to be used in infinate loops. Let’s try and example with the for loop.

names = ['Bob Belcher',
         'Linda Belcher',
         'Louise Belcher',
         'Tina Belcher',
         'Gene Belcher']

bob = ''
for name in names:
    if 'Bob' in name:
        bob = name
        break   # There's no need to keep looping through
                # the rest of the list because we have found Bob
Advertisements

Nested Loops

In previous posts, we covered while and for loops. Python let’s us nest loops. Let’s start with an example.

grid = [
    [1, 2, 3, 4, 5, 6, 7, 8, 9],
    [9, 8, 7, 6, 5, 4, 3, 2, 1],
]

for row in grid:
    for cell in row:
        print(str(cell))
    print('\n', end=' ')

When run, we get the following output

1 2 3 4 5 6 7 8 9

9 8 7 6 5 4 3 2 1

So why does this work? In our example, we have data structure that can be thought of in terms of an x,y grid. Basically, it’s a list that contains two lists: one list for each row.

When we begin our loop with for row in grid: we are starting a for loop with a variable named row. Everytime this loop updates, the row variable is assigned the next list object inside of the grid variable.

Now our next line of code is also a for loop: for cell in row. Remeber that row is a list object that corresponds to a row in the grid list. Each item inside of row is a number, so when this loop runs, the variable cell gets updated with a number inside of the list that is currently assigned to the row variable.

We can mix our loops also

grid = [
    [1, 2, 3, 4, 5, 6, 7, 8, 9],
    [9, 8, 7, 6, 5, 4, 3, 2, 1],
]

for row in grid:
    index = 0
    while index < len(row):
        print(str(row[index]))
        index += 1

This code delivers the same output as the first example. The differnce is that this time, we have a while loop as our nested loop rather than a for loop. As you can see, this code is a little more complex than the first example, but the point of it was to demonstrate that it's possible to mix and match loops.

Also keep in mind that you can have loops that are infintely nested as long as your hardware can handle it. However, if you find that you are nesting loops deeper than two loops, then consider restructing your code since nesting loops that deep will impact the code's reability and make it difficult to debug.

While Loops—Python

Sometimes we need to repeat code in our programs for a certain number of executions. Let’s consider the classic triangle problem:

=
==
===
====
=====
======
=======
========
=========
==========

This is a typical problem that computer science students use to learn about loops. In this problem, we have to print a triangle to the console where the size is specified by the user. Since we don’t know the size of the triangle ahead of time, we won’t be able to do something like this:

print('=')
print('==')
print('===')
# continued...

Our issue is that right now, this code can only print a triangle that has a base size of three. If the user wants ten, we are out of luck. What we need is a programming construct that will continue to build the triangle until it hits the proper size.

Here is the example code of how to do this

size = int(input('Enter the size of the triangle => '))
counter = 0

while counter < size:  # counter < size is the terminating condition.
    # The next two lines repeat as long as condition < size
  print('=' * counter) # Print the triangle
  counter += 1 # Important! Update the counter variable! 

This code accomplishes what we want it to do. This is the output we get when we run this code.

Enter the size of the triangle => 5

=
==
===
====

Let’s talk about why this works. While loops begin with the while keyword followed by a condition. The loop will repeat code inside of the while block as long as the condition is true.

In our case, the condition is counter < size so as long as our counter is less than the size of the triangle that the user specified, our condition will be true and the loop will continue to repeat. As soon as size >= counter the loop will terminate and the program will return to it’s normal execution flow.

Inside of the triangle, we print our triangle and then update our counter variable by 1. It is critical that we update our counter variable because without it, the loop will run forever.

while counter < size:
    print('=' * counter)
print('Loop is over') # Note! We never get to this statement! How come?

The code above will run forever in what is called an 'infinate loop'. The reason this happens is that we fail to increment the counter variable. Remember that loops always run while the terminating condition is true. Since counter is always less than size, our condtion never becomes false and the loop runs forever.
Sometimes we make infinate loops on purpose

while True:
    print('Infinate loop')

Since we are passing the contant True to our loop here, our loop will run forever. It’s on the developer at this point to kill the loop, which will learn when we cover the break keyword.

Finally, Python let’s us add an else statement to while loops that will run once the loop is over.

size = int(input('Enter the size of the triangle => '))
counter = 0

while counter < size:
    print('=' * counter)
    counter += 1
else:
    print('triangle complete') # This code runs when the loop is over

For Loops—Python

Python has a for loop which is allows us to step through each element in an iterable (generally anything that defines __iter__ or __getitem__ such as files, lists, tuples, etc.).

First let’s go through an example of a for loop

for i in range(10):
    print(str(i))

When run, this code produces the following output

0
1
2
3
4
5
6
7
8
9

Let’s discuss how this works. Our loop begins with the keyword for followed by a variable or variables. After the variable, we have the in keyword followed by an iterable. The loop continues until there are no more items in the iterable.

In our example, the iterable is the range function. So when we have range(10) we are making a sequence of ten numbers 0-9. Everytime range produces a number, it gets assigned to the variable i. We then use print(str(i)) to print the value of i to the console.

Here is another demonstration of the for loop, this time using a list

names = ['Bob', 'Tina', 'Gene', 'Linda']

for name in names:
    print(name)

Lists implement the correct protocals that allow them to be used in for loops. In this case, we populate a list with some names. Everytime the loop executes, the name variable is updated with the next name in the list. We then print the name to the console.

The for loop let’s us have more than one variable in the loop.

names = [['Bob', 'Belcher'], 
        ['Tina', 'Belcher'], 
        ['Gene', 'Belcher'], 
        ['Linda', 'Belcher']]
        
for fname, lname in names:
    print(fname, ' ', lname)

Keep in mind that when you do this, your update variables need to match the number of variables in your sequence. So if we had three variables here, we would get an exception.

Conditions—Python

Most of the time in programming, our programs execute one line at a time. So for example we might see something like this:

name = input('Enter your name => ')  # This statement runs first
print('Hello ', name)  # Now this statement runs next

Sometimes our programs hit a fork in the road and they need to make a decision about the direction they are going to take. Python gives us conditional statements to help make such decision.

A conditional statement is a condition that changes the course of the program’s execution based on a true or false evaluation. Let’s start with a code example to help make this more clear.

gender = 'F'
name = input('Enter your name => ')

if gender == 'F':
    print('Hello Ms. ', name)   # This code only executes for women
                                # (gender == 'F')
else:
    print ('Hello ', name)  # This code executes for anyone else
                            # (gender != 'F')

This code snippet demonstrates a conditional statement. We begin with a variable named gender that is set to the value ‘F’ for female. Ideally, if we know the gender of a person, we should offer the correct greeting for that person.

The if gender == 'F': is the conditional statement. What this statement is doing is using a true/false expression to decide if we should print ‘Hello Ms.’ instead of just the standard ‘Hello’ greeting. If our gender variable is ‘F’, we will print the ‘Hello Ms.’, otherwise we print the ‘Hello’ greeting.

We can handle multiple conditions with the elif keyword. Let’s build on our example:

gender = 'F'
name = input('Enter your name => ')

if gender == 'F':               # First check if the gender is F
    print('Hello Ms. ', name)   # This code only executes for women
                                # (gender == 'F')

elif gender == 'M':             # Now check if gender is M
    print ('Hello Mr. ', name)  # This time print a greeting for men
                                # (gender == 'M')
else:
    print ('Hello ', name)  # This code executes for anyone else
                            # (gender != 'F')

Adding the elif keyword is a way to stack up multiple conditions and define an action for each condition. Now I should point out at this time that elif and else are completely optional. So it is ok to do this:

gender = 'F'
if gender == 'F':
    print('Found female')
print ('Done checking for m/f') # At this point, the code continues
                                # executing normally

We can also check for false conditions by using the != operator.

gendar = 'F'
if gender != 'M':   # Execute the code inside of the if block if
                    # if the gender is not male
    print('Found female')
print('Done checking for m/f') # Return to normal execution

Bubble Sort—Java

The bubble sort is a very common algorithm that many computer science students are expected to learn. Yesterday I did a post that shows a Python implementation of the bubble sort which you can view here. Today I will demonstrate the same technique in Java.

import java.util.Arrays;

public class BubbleSort {

public static void main(String [] args){
Integer [] nums = {9, 4, 2, 1, 10};
System.out.println("Unsorted is " + Arrays.toString(nums));

bubbleSort(nums);
System.out.println("Sorted is " + Arrays.toString(nums));
}

public static<T extends Comparable> void bubbleSort(T [] array){
int n = array.length;
T temp;

for(int i = 0; i < n; i++){
for (int j = 1; j  0){
//Swap the elements
temp = array[j - 1];
array[j - 1] = array[j];
array[j] = temp;
}
}
}
}
}

Java is a little more verbose than Python. Since it is a statically typed language (which means you have to declare the data type up front, as opposed to Python’s duck typing method), I chose to use generics to implement this sort.

Generics were introduced in JDK 1.5. They allow us to write code that is widely applicable to many types of objects without forcing us to use the Object class. You can find a wide use of generics in the java.util package.

In this case, I declared my generic method like this

public static<T extends Comparable> void bubbleSort(T [] array){

Let’s go through this one word at a time.

  1. public—This is the keyword that makes this method publically available
  2. static—This keyword attaches this method to the class rather than an object
  3. <T extends Comparable>—This is the code that declares this method to be a generic method. T is the type of the object, followed by extends Comparable which means that any object that implements the Comparable interface is accetable to this method.
  4. T [] array—This declares an array of type T (which is any class that implements Comparable in this case)

Now that we have declared this to be a generic method, this method will work with any object that implements the Comparable interface. The Comparable interface is widely used throughout Java in sorting. It declares a compareTo(T obj) method which returns a positive number when an item is greater than the comparing object, zero when the two objects are equal, and a negative number when the comparing object is less than the other object.

Since this interface exists, Java lets us sort anything that implements this interface easily. That allows programmers a high degree of freedom and flexibility when creating custom classes because the programmer gets to decide how one object is greater than, less than, or equal to another object.

We apply the Comparable interface to this bubble sort method here

if(array[j - 1].compareTo(array[j]) > 0){
//Swap the elements
temp = array[j - 1];
array[j - 1] = array[j];
array[j] = temp;
}

If the left hand portion array[j - 1].compareTo(array[j]) is 0, then these two items are 0. If the result is a negative number then array[j - 1] is less than array[j], otherwise array[j - 1] is greater than array[j] and it needs to get swapped.

When run, we get this output

Unsorted is [9, 4, 2, 1, 10]
Sorted is [1, 2, 4, 9, 10]

Bubble Sort—Python

Many computer science students are expected to perform sorting. Here is an example of doing a bubble sort in Python.

def bubble_sort(array):
    # Grab the length of the array
    n = len(array)

    # Iterate through array from 0 to n
    for i in range(len(array)):

        # Iterate through array from 1 to n - i
        for j in range(1, n - i):

            # Now check if the element at array[j - 1] is larger than array[j]
            if array[j - 1] > array[j]:
                # Perform a swap of the elements
                temp = array[j - 1]
                array[j - 1] = array[j]
                array[j] = temp

if __name__ == '__main__':
    unsorted = [10, 5, 2, 3, 1]
    print('Unsorted list is: ', unsorted)

    bubble_sort(unsorted)
    print('Sorted list is now: ', unsorted)