Programming in Python

BEES 2023

Agenda

  • More Control Flow
    • For Loops and List Iteration
    • Nested Loops
    • Break Statement
    • Continue Statement
  • Some Examples of Control Flow

For loops

0
 Advanced issues found
 
  • The for loop is "syntactic sugar", that is it combines the concept of looping (like the while loop) with the idea of iterating, either using a counter or elements in a sequence, such as a Python list.

  • You can always create equivalent code using a while loop and additional variables, but 'for' is often more convenient.

 

 

 

# While loop version
i = 0

while(i < 10):
  print("i is: " + str(i))
  i = i + 1
# The for loop version

for i in range(10): 
  # Range returns an iteratable sequence 
  # from 0 (inclusive) to 10 (exclusive)
  print("i is: " + str(i))

Examples of for loops

# Range can do all sorts of fancy iterations
for i in range(9, -1, -1): # Backwards
  print("i is: " + str(i))
# Jumping two steps at a time
for i in range(0, 10, 2): 
  print("i is: " + str(i))
# For loops also allow iteration over sequences, such as lists:
# Note: we'll cover lists in detail later

for color in [ "pink", "yellow", "blue", "green" ]:
  print("My favorite color is now " + color)

An aside example of list

  • We saw nested conditionals, we can also nest loops.

  • While loops, for loops and other control flow elements can all be nested together.

# Example of nested for loops

for i in range(4): 
  for j in range(4): 
    print("The values are, i: " + str(i) + " j: " + str(j))
    
# This may mess with you, but it is just the logical extension
# of the ideas we've covered.

nesting loops

Break & Continue

  • Break:
    • Jumps out of a block

 

 

 

  • Continue:
    • Jumps to the beginning of the block
i = 1
while True:
  print(i)
  i = i + 1
  if i > 10:
    break
i = 0
while True:
  print(i)
  i = i + 1
  if i < 5:
    continue
  if i >= 10:
    break

Example 1: break

Example 2: Continue

Counting digits

Example

Lecture 4 challenge

Questions?

BEES 2023 - Lecture 4

By Narges Norouzi

BEES 2023 - Lecture 4

  • 213