Skip to content

Oct 02: Prac3, while Statements

Learning Objectives

After today's class, you should be able to:

  • Explain the syntax and meaning of a while statement.
  • Describe examples of how a while loop can be used.

Reminders

  • Due today: HW6 Reflection
  • Read Ch 7 – ideally:
    • 1st half before Friday
    • 2nd half before Monday
  • Submit HW 7 – ideally:
    • 1 and 2 before Friday
    • 3 and 4 before Monday

HW6 Debrief

  • Default arguments
  • ord() and chr()
  • Updating a dictionary
  • Unpacking a tuple
  • Starting with None

Practice Quiz 3

  • Log in as student
  • Only two windows:
    1. Thonny
    2. Web browser
  • Web traffic monitored
  • Log out when finished

Ch07 Preview

  • The "while true" loop
    • Syntax: while condition
    • Meaning: repeat the following code
  • Run examples with Thonny Debugger
Example 1: greatest common divisor

See Euclidean algorithm on Wikipedia.

x = int(input("Larger number: "))
y = int(input("Smaller number: "))
while y != 0:
    temp = y
    y = x % y
    x = temp
print("The GCD is", x)
Example 2: while input not finished
print("Give me some numbers...")
number = None
while number != 0:
    number = float(input())
    if number > 0:
        print(number, "is positive")
    elif number < 0:
        print(number, "is negative")
print("Have a nice day!")
Example 3: while not converged

See Collatz conjecture on Wikipedia.

n = int(input("Enter a positive integer: "))
while n != 1:
    print(n)
    if n % 2 == 0:
        n = n // 2
    else:
        n = 3*n + 1
print("n is now 1!")
Example 4: convert decimal to binary
n = int(input("Enter a positive integer: "))
print(n, "in binary is", end=" ")
binary = ""
while n > 0:
    r = n % 2
    n = n // 2
    binary = str(r) + binary
print(binary)
Example 5: while random game not over
import random

health = 5
while health > 0:
    print("Your health is", health)
    move = input("Attack or dodge? ")
    move = move[0].upper()

    if move == "A":
        if random.random() < 0.33:
            print("Hit! Your health increases by 1.")
            health += 1
        else:
            loss = random.randint(1, 4)
            print("Miss! You lost", loss, "health.")
            health -= loss
    elif move == "D":
        if random.random() < 0.50:
            print("Good dodge. You're still alive.")
        else:
            loss = random.randint(2, 3)
            print("Oops! You lost", loss, "health.")
            health -= loss
    else:
        print("Invalid move...you're now dead.")
        health = 0
    print()

print("Game over")