Notes S-09/Python 6: For and while loops

Explain loop mechanics with sums and products, then distinguish the planned in-class and homework exercises.

Slide 109 — Ranges and for loops

range() accepts a start, an exclusive stop, and an optional step.

list(range(10))
list(range(6, 10))
list(range(1, 10, 2))
for i in range(3):
    print(i)
for i in [2, 9, 7]:
    x = i * 2
    print(x)
for i in ['apple', 'orange']:
    print(i)

for can iterate over ranges and directly over list elements.

Slides 110–111 — for loops

Explain loops using \(\sum_i^n\) and \(\prod_i^n\).

n = 5
for i in range(n):
    print(i)


n = 5
for i in range(n):
    print(i, end="")


n = 5
for i in range(n):
    for j in range(n):
        print(i, j)


n = 5
for i in range(n):
    for j in range(n):
        print(i, j, end=" | ")
    print()


n = 5
for i in range(n):
    for j in range(i+1):
        print(i, j, end=" | ")
    print()


s = "Hallo"
n = 5
for i in range(n):
    print(s[i])


s = "Hallo"
for i in range(len(s)):
    print(s[i])


s = "Hallo"
for i in range(len(s)):
    print(s[i], end="")


s = "Hallo"
for i in range(len(s)):
    for j in range(i+1):
        print(s[i], end="")
    print()


s = "Hallo"
for i in s:
    print(i)

Note: 3–4 and 6–7 are homework.

  1. Write a program that will ask the user for a message and the number of times they want that message displayed.
message = input("Enter the message: ")
n = int(input("How many times should the message be displayed: "))
for i in range(n):
    print(message)
  1. Write a program that will calculate the average (mean) of a set of numbers.
n = int(input("How many numbers do you want to enter: "))
numbers = []
for i in range(n):
    numbers.append(int(input("Enter number: ")))
sum = 0
for i in range(n):
    sum = sum + numbers[i]
average = sum/n
print("The average is: ", average)
  1. Write a program that will output the numbers from 1 to 100.
for i in range(1,101):
    if i%10==0:
        print(i, " divisible by 10!")
    else:
        print(i)
  1. If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9.
msum = 0
n = int(input("Enter the upper bound: "))
for i in range(1,n):
    if(i%3==0 or i%5==0):
        msum = msum + i
print(msum)
  1. Write a program that generates a list containing the Fibonacci sequence.
n = int(input("How many numbers should be generated: "))
fib = [0,1]
for i in range(n):
    fib.append(fib[-2]+fib[-1])
print(fib)
  1. Write a program to generate n random numbers between 1 and 10.
import random

n = int(input("How many random numbers do you want to generate? "))
freqlist = [0,0,0,0,0,0,0,0,0,0]
for i in range(n):
    x = random.randint(1,10)
    freqlist[x-1] = freqlist[x-1] + 1
print(freqlist)
  1. Write a program that displays a word entered by the user as a triangle of letters.
word = input("Enter a word: ")

for i in range(len(word)):
    for j in range(i+1):
        print(word[i], end="")
    print()

☕ Break — 10 minutes

Slide 112 — while loops

A while loop repeats while its condition remains true. Its body must change the relevant state to avoid an infinite loop.

count = 0

while count < 4:
    print("The count is:", count)
    count = count + 1
names = ['Ann', 'Tom', 'Peter', 'Jens', 'Sue']

while names[0] != 'Jens':
    print(names[0])
    names.remove(names[0])

Slides 113–114 — while loops

Assign exercise 1, 5 as homework.

  1. Create a program that will keep track of items for a shopping list.
sl = []
item=input("Insert list item: ")
while item != "":
    sl.append(item)
    item=input("Insert list item: ")
for i in sl:
    print(i)




sl = []
item="x"
while item != "":
    item=input("Insert list item: ")
    if item!="":
        sl.append(item)
for i in sl:
    print(i)




sl = []
item="x"
while item != "":
    item=input("Insert list item: ")
    if item=="":
        break
    sl.append(item)
for i in sl:
    print(i)
  1. Write a Python program to guess a number between 1 to 10.
import random
target_num = random.randint(1, 10)
guess_num = 0
while target_num != guess_num:
    guess_num = int(input('Guess a number between 1 and 10 until you get it right: '))
print('Well guessed!')
  1. Rewrite the program to have the user guess a number between 1 to 100
import random
target_num = random.randint(1, 100)
guess_num = 0
while target_num != guess_num:
    guess_num = int(input("Guess a number: "))
    if(target_num<guess_num):
        print("lower")
    elif(target_num>guess_num):
        print("higher")
print('Well guessed!')
  1. Expand the previously created dice game.
import random

stake = int(input('How much money would you like to invest? '))
continue_ = True

while continue_:
    dice1 = random.randint(1,6)
    dice2 = random.randint(1,6)
    
    if dice1 == dice2:
        print("You have won!!! It's a double", dice1)
        payout = stake * dice1
        print("You get", payout, "Euro!")
        continue_ = bool(int(input('Would you like to continue? 1=yes, 0=no: ')))
        if continue_:
            stake = payout
    else:
        print("Unfortunately they lost!!! The throw brought", dice1, "and", dice2)
        continue_ = False
  1. Write a program to create the history of a loan.

Note: Remind students that exercise 5 is the same task they completed in Excel.

amount = float(input("Amount of the loan: "))
repayment = float(input("Repayment: "))
irate = float(input("Interest rate (in % and annual): "))

period = 0
while amount>0.0:
    period += 1
    interest = amount * irate/100.0/12.0
    if (amount>repayment):
        amount = amount - repayment
    else:
        repayment = amount
        amount = amount - repayment
    print ("Month:", period, " Repayment:", repayment, " interest:", round(interest,2), " Remaining:", amount)

Summary and announcements

TipNotes for improvement

Take notes on improvements and common questions during the session and add them to feedback.qmd afterwards.