Skip to content

Sep 24: Quiz2, 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: HW5 Reflection
  • Read Week 6 – ideally:
    • 1st half before Friday
    • 2nd half before Monday
  • Submit HW 6 – ideally:
    • 1 and 2 before Friday
    • 3 and 4 before Monday

HW5 Debrief

  • Helper functions like swap()
  • Passing containers to functions
    • If immutable, return new object
    • If mutable, edit existing object
  • Returning "fairness" of two sets
The Unofficial Graduation Requirement for CS/IT Majors

Students who write code like this will not be allowed to graduate:

if condition:
    return True
else:
    return False

The above code should be written without using an if statement:

return condition

Quiz 2

[25 min]

  • Log in as student
  • Start exam recording
  • Log in to Canvas only
  • Open written and coding
  • No Thonny on written

Wk06 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")