Date

Lecture Date: Wednesday, September 21

Often there is code that we want our programs to repeat. This could be to have the program process all the items in a list, or do a number of tasks in order, or any number of other reasons. Along with if statements, loops are a core decision and control structure to write effective programs.

There are several ways to write loops in Python. We'll discuss those all today.

  • while loop - a condition-controlled loop
  • for loop using the range operator- a count-controlled loop
  • for loop using the in operator with a list
  • while loops for input validation
  • nested loops

Here are some things we might try to build:

  • a shopping cart
  • the worst roman.py solution ever
  • average of a list of numbers
  • printing a square

Some code we did today in class:

num = int(input("number? "))
roman = ""
while num > 0:
   roman += "I"
   num -= 1
print(roman)


x = 10
while x > 5:
    print(x)
    x -= 1

word = ""
while not word == "stop":
    word = input("Give me a word (stop to stop): ")
    print("You said: " + word)

ask for number between 1 and 100 (inclusive)
if not in range, ask for another
if in range, print

number = -1
while number < 1 or number > 100:
    number = int(input("Give me a number between 1 and 100: "))
print(number)

number = -1
while number not in range(1,101):
    number = int(input("Give me a number between 1 and 100: "))
print(number)   
    for i in range(0,4): # [0,1,2,3]
       print(i)

students = ['Mark', 'Colin', 'Sammy', 'Sarah', 'Laurie']

for student in students:
   print(student)

for i in range(100,21,-5):
   print(i)

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

# print this:
# 1 2 3
# 4 5 6
# 7 8 9

row_to_print = ""

for row in square:
   for col in row:
       row_to_print += str(col) + "\t"
   print(row_to_print)
   row_to_print = ""