How to think like a programmer -- Python Loops and Iterations

Assumed audience: You are a TechLabs student pursuing the Data Science track. You require little hand-holding and prefer to refer to textbooks or denser materials if a concept doesn't make sense to you.

Context

We need ways to control the flow of our program. Loops and Iterations let you do that.

While loops

x = 0
while x < 5:
  print(x)
  x += 1

You need to learn how to construct while loops.

A while loop takes a condition that must evaluate to True and it will execute the code inside the loop until the condition becomes False.

You need an exit condition because otherwise while loops run forever or until it runs out of memory.

What's the exit condition in my program?

It's x < 5.

But it won't stop unless you write the logic necessary for the condition to turn False.

In this case it's x += 1.

This reads: "Add 1 to the value of x each loop".

We use assignment and a plus sign operator in one expression.

The loop will print the value of x until it reaches the exit condition.

for loops


collection = ["apple", "peer", "orange"]

for item in collection:
  print('Fruit: ', item)

This code reads like this: "for every item in the List called 'collection' run the code in the loop".

You can name item whatever you want. It's just the iterator variable that you use to refer to an item in the list.

Let's say you only want to perform a task on a single item in the list or whenever a condition is met.

for item in collection:
  if item != "peer":
    continue
  else:
    print(item)

You can use an if statement to specify the condition that must be met.

In this piece of code we use continue to say "if the item in the List is not peer then you can skip to the next item, otherwise print the item in the list.

We iterate through Lists or other data structures by constructing for loops.

With the continue key word we can move to the next iteration by ending the current iteration.

You can use break to exit the loop whenever a condition is met.

Think about what happens here before reading the answer.

for item in collection:
  if item == "peer":
    break
  else:
    print(item)

As soon as we hit "peer" in the loop the for loop exits. We don't reach "orange" at all.

Practice tasks

I use Google Colab to work with the provided Jupyter notebooks.

Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number.

def numbersGame ():

  inp = input('Give me a number or say done. ')
  numbers = []
  
  while (inp != 'done'):
   
    try:
      if int(inp):
        print(inp)
        numbers += [int(inp)]
        inp = input('Give me a number or say done ')
   
    except Exception as error:
      # use this line to print the actual error
      # print("An exception occurred:", error)
      print('Not a valid number.')
  print('You said done.')
  print(numbers)
  print('Smallest number:', min(numbers))
  print('Largest number:', max(numbers))

numbersGame()

I came up with my own examples a week after going through the material because spaced repetition is important for learning.

Find the largest number in a list

L1 = [2, 300, 4, 79, 32]

MAX_NUM = 0
for n in L1:
  if n > MAX_NUM:
    MAX_NUM = n 
print(MAX_NUM)

# not efficient though

Sum all the numbers in a list

L1 = [2, 300, 4, 79, 32]

SUM = 0
for n in L1:
  SUM += n
  
print(SUM)

Average the numbers in the previous list

SUM = 0
number_of_items = len(L1)
for n in L1:
  SUM += n
  
print(SUM / number_of_items)

Create a filter for a list of your choosing. Find a value of your choosing. Then break the loop.

L1 = [30, 400, 56, 91, 2, 10, 35, 110]

for item in L1:
  print(item)
  if item == 10:
    print("10 is in the list! Breaking loop!")
    break 

curating the best of the web -

come explore!

media garden about ethos home