OIM3640 - Problem Solving and Software Design

2026 Spring

Session 09 (2/19)

contain

Today's Agenda

Announcements/Updates

  • Repo Checkpoints - starting now, I will review your repos every ~2 weeks
    • This is a standing routine, not announced each time. It could be any day.
    • Keep your notebooks/, logs/, and code/ up to date and pushed to GitHub at all times
  • Mini Project 1 - start working on it now!
    • Submit PROPOSAL.md first, then code iteratively
    • Goal: finish in 2-3 weeks
  • Getting Help
    • Office Hours: By appointment (in-person preferred or Webex)
    • Email: Specify course # in subject, e.g., "OIM3640: GitHub settings"
  • Questions?

What We've Learned So Far

  • Variables & Types: int, float, str, bool, NoneType
  • Operators: +, -, *, /, //, %, **
  • Functions:
    • def, parameters, arguments, return vs print()
    • Scope, docstrings, decomposition, abstraction
    • Incremental development, boolean functions, composition
  • for loop: for i in range(n):
  • Turtle: Drawing shapes with loops and functions
  • Conditionals: if/elif/else, boolean expressions, logical operators

🙋 Review Questions

  1. What will be printed if score = 95?

    if score >= 60:
        print("Pass")
    elif score >= 90:
        print("A")
    else:
        print("Fail")
    
  2. How would you fix the code above so it prints "A" for scores >= 90?

🙋 Review Questions (continued)

  1. What will be the output?

    def mystery(x):
        if x > 0:
            return "positive"
        print("done")
    
    result = mystery(5)
    print(result)
    
  2. What is the type and value of this expression?

    x = 15
    x > 10 and x < 20
    

🙋 Review Questions (continued)

  1. What does this print?

    def check(n):
        if n % 2 == 0:
            if n % 3 == 0:
                print("A")
            else:
                print("B")
        else:
            print("C")
    
    check(8)
    check(6)
    
  2. Rewrite question 5 using elif instead of nested if (hint: use and).

Chapter 7 - Iteration and Search

What we'll learn:

  • The while loop
  • for vs while - when to use which?
  • break and continue
  • for loops on strings (not just range)
  • The in operator and the search pattern

The while Loop

We know for i in range(n): repeats a known number of times.

while keeps going until a condition becomes False:

n = 3
while n > 0:
    print(n)
    n -= 1
print("Go!")
# 3, 2, 1, Go!

Key difference:

  • for iterates over a known sequence
  • while keeps going until a condition changes

for vs while - Same Task, Two Ways

Task: Print numbers 1 through 5

# Using for
for i in range(1, 6):
    print(i)
# Using while
i = 1
while i <= 5:
    print(i)
    i += 1

Which is cleaner? When would while be the better choice?

When to Use while

Task: Keep asking until the user says "quit"

response = ""
while response != "quit":
    response = input("Enter command: ")
    print(f"You said: {response}")

You can't do this with for - you don't know how many times the user will respond!

Rule of thumb: If you know the count, use for. If you're waiting for a condition, use while.

break and continue

# break - exit the loop immediately
for word in words:
    if word == "target":
        print("Found it!")
        break
# continue - skip to the next iteration
for num in range(10):
    if num % 2 == 0:
        continue
    print(num)  # prints odd numbers only

for Loops on Strings

for can iterate over any sequence, not just range:

for letter in 'Gadsby':
    print(letter, end=' ')

Output: G a d s b y

Let's check if a word contains the letter 'e':

def has_e(word):
    for letter in word:
        if letter == 'e' or letter == 'E':
            return True
    return False

Where you place return False matters! (Why not inside the loop?)

The in Operator

The in operator checks if a character is in a string:

'e' in 'Gadsby'    # False
'e' in 'Emma'      # True

This simplifies has_e dramatically:

def has_e(word):
    return 'e' in word.lower()

One line! The in operator replaces the entire loop.

The Search Pattern

What if we need to check for any of several letters?

def uses_any(word, letters):
    for letter in word.lower():
        if letter in letters.lower():
            return True
    return False
uses_any('banana', 'aeiou')   # True
uses_any('apple', 'xyz')      # False

This is linear search: loop through, return True early if found, return False at the end.

⚠️ A Common Bug

# INCORRECT - can you spot the bug?
def uses_any_wrong(word, letters):
    for letter in word.lower():
        if letter in letters.lower():
            return True
        else:
            return False   # Bug! Exits after checking only the FIRST letter
uses_any_wrong('banana', 'aeiou')   # False  (checks 'b', not a vowel, returns False!)

return False must be outside the loop - only after checking ALL letters.

Reading the Word List

Download words.txt to your data folder.

URL: https://raw.githubusercontent.com/AllenDowney/ThinkPython/v3/words.txt

(Also available at resources/code/data)

# Read and process every word
for line in open('data/words.txt'):
    word = line.strip()
    if has_e(word):
        print(word)

The file has 113,783 English words. About 67% contain the letter 'e'!

Counting with Loops

Updating variables with +=:

total = 0
count = 0
for line in open('data/words.txt'):
    word = line.strip()
    total += 1
    if has_e(word):
        count += 1

print(f"{count} out of {total} words contain 'e'")
# 76162 out of 113783 words contain 'e'

📝 Your Turn

Open Chapter 7 notebook and download words.txt

Work through the examples and exercises:

  • has_e and uses_any functions
  • Search exercises with the word list
  • Try the Spelling Bee puzzle exercise!
  • Challenge: Write your own examples to summarize when to use for vs while (AI assistance is welcome, but make sure you understand each example)

Questions? Ask now!

Before You Leave (5 min)

  • Any questions so far?
  • Start your Learning Log for this week (logs/wk05.md)
  • Work on Chapter 7 exercises
  • Continue working on Mini Project 1
  • Push your work to GitHub

Next session: Strings (Chapter 8)

global styles