Conditional Statements & Control Flow

Conditional Statements & Control Flow#

if-then-else#

From Busbee and Braunschweig’s “Selection Control Structures” from Programming Fundamentals:

  • “The basic attribute of a selection control structure is to be able to select between two or more alternate paths. This is described as either two-way selection or multi-way selection. A question using Boolean concepts usually controls which path is selected. All of the paths from a selection control structure join back up at the end of the control structure, before moving on to the next lines of code in a program.”

  • “The if then else control structure is a two-way selection”

In Python, this logic is expressed using the if, else, and elif syntax. From W3Schols, “Python Conditions”:

  • “An ‘if statement’ is written by using the if keyword”

  • “The elif keyword is Python’s way of saying ‘if the previous conditions were not true, then try this condition’”

  • “The else keyword catches anything which isn’t caught by the preceding conditions”

# assign variables
x = 5
y = 7

# if statement
if x > y:
    print("The value of x is greater than the value of y")

# else if statement
elif x == y:
    print("The value of x is equal to the value of y")

# else statement
else:
    print("The value of x is less than the value of y")

To frame this another way:

  • if introduces and evaluates an initial condition. The lines of code indented under if will only run when the if statement is True

  • else-if or elif introduces and evaluates another condition. The lines of code indented under elif will only run when the elif statement is True

  • else does not introduce a new condition. The lines of code indented under else will only run when the preceeding if/elif statements are not true

For more background on if-then-else logic in Python:

Iteration#

But let’s review the definition of iteration as a control structure. From Busbee and Braunschweig’s “Iteration Control Structures,” in Programming Fundamentals:

“In iteration control structures, a statement or block is executed until the program reaches a certain state, or operations have been applied to every element of a collection. This is usually expressed with keywords such as while, repeat, for, or do..until. The basic attribute of an iteration control structure is to be able to repeat some lines of code. The visual display of iteration creates a circular loop pattern when flowcharted, thus the word ‘loop’ is associated with iteration control structures.”

Breaking down that definition:

  • Iteration (repetition of a process) is a type of control structure

  • In programming languages, iteration involves lines of code repeating until a condition is met of the end of a group of values has been reached.

  • Because iteration in this context involves a circular pattern, many object-oriented programming languages refer to these structures as loops

The power of iteration as a control structure comes from a programming concept called loops.

Most high-level programming languages support two main types of loops: event-controlled and count-controlled

  • Event-controlled loops test for an initial condition, and execution continues as long as the initial condition is True. How many times the loop will execute is not known.

  • Count-controlled loops (sometimes called counter-controlled loops) continue executing for a pre-determined number of times. The number of times the loop will execute is known because the loop is iterating through a collection of objects/values (i.e. a string or list), or the iteration when the initial condition will no longer be True is known.

while#

In Python, event-controlled loops are written using a while statement and are called while loop. A while statement tests for an initial condition, and the lines of code indented under while run only when the initial condition is True.

In each iteration through the while loop, Python will:

  • Evaluate the initial condition (which is a Boolean true/false expression)

  • If the condition is False, exit the loop and continue the program

  • If the condition is True, then execute other statements in the body of the loop and return to the beginning of the loop

The basic syntax for a while loop:

# while loop sample syntax
while condition:
	statement(s)

To express this logic another way:

# while loop sample syntax
while THIS CONDITION IS TRUE:
	DO THIS THING

For example, let’s look at a guessing game program that uses a while statement:

# correct answer
secret = 7

# guess
guess = int(input("Guess a number: "))

# while statement
while guess != secret:
  if guess > secret:
    print("Your guess is too high. Better luck next time")
    guess = int(input("Guess again. Enter another number: "))
  else:
    print("Your guess is too low. Better luck next time.")
    guess = int(input("Guess again. Enter another number: "))


print("Congrats, you guessed the secret number!")

This is an example of a while loop. Because the number of times the loop will execute is not known, this is an example of an event-controlled loop. That is, the loop will continue executing (looping) until the initial condition (guess != secret) is no longer true.

for#

In Python, count-controlled loops are written using a for statement and are called for loop. A for loop iterates over each value in a group of values- the lines of code nested under the initial statement run for each iteration.

for loops let us iterate through a definite set of objects. In each iteration through the for loop, Python will:

  • Extract one element from the dataset

  • Execute the body of the for loop using the item bound to the element

  • Go back to the first step

  • Keep iterating through the loop until reaching the end of the dataset

The basic syntax in a for loop:

# sample for loop syntax
for item in dataset:
 statement(s)

In this syntax, item is a placeholder for each element in dataset. We can replace item with another word or letter character.

# sample for loop syntax
for i in dataset:
	statement(s)

In this syntax, dataset stands for the group of items we want Python to iterate over. That group of items could be a list, a list variable, string, string variable, etc.

Let’s say we have a list of numbers, and we want Python to iterate through each number in the list and print the number.

for i in [0, 1, 2, 3]:
 print(i)

Alternatively, we could create a variable for our list of numbers.

# create list of numbers
number_list = [0, 1, 2, 3]

# for loop
for i in number_list:
 print(i)

The loop command steps through the list one value at a time. The loop continues until it reaches the end of the list.

We can also use a for loop to iterate over a list of strings. Let’s say we have a list of pepper types.

peppers = ["bell", "poblano", "jalapeno", “banana”, “chile”, “cayenne”]

We can use a for loop to iterate over each string in the list.

peppers = ["bell", "poblano", "jalapeno", “banana”, “chile”, “cayenne”]

for x in peppers:
 print(x)

We can also use a for loop to iterate through characters in a single string. Let’s say we want to iterate over the characters in the string elements.

for x in 'elements':
 print(x)
# another example of iterating over characters in a string

string = 'elements'

for x in string:
 print(x)

Application#

Q3: In your own words, what is iteration?

Q4: In your own words, what is the difference between a for loop and a while loop?

Additional Resources#

For more background on iteration & loops in Python: