Skip to content

Sep 23: Searching, Modifying Lists, while statements

Learning Objectives

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

  • Summarize which operators can be applied to a list.
  • Summarize built-in functions and methods for a list.
  • Write a program that manipulates and searches a list.
  • Explain the syntax and meaning of a while statement.
  • Describe examples of how a while loop can be used.

Reminders

List Operations

  • Useful documentation
  • A method is a function bound to an object
    • Called with the dot operator (.)
  • Some methods to learn:
    • append(v) – adds value v to the end
    • pop() – removes value from the end
    • pop(i) – removes value at index i
    • insert(i, v) – insert v at index i
    • remove(v) – removes first element v
    • count(v)– number of value v in list
    • index(v) – index of first element v
  • You don't need to memorize!
    • Use the help() function in the Shell
    • Use the "Object inspector" in Thonny

Activity One: Little Free Library

photo of little free library

A Little Free Library is a community library that lets people borrow and contribute books. The library survives on the "take a book, leave a book" principle. If someone takes a book (like "Project Hail Mary"), they have to add another book to the library (like "The Martian"). It’s a great way for people to share books!

Step 1: Setup

In this lab, you will create a library.py program to simulate a Little Free Library. At the top of your program, after the docstring, assign a variable named books that contains the list of books in the library:

books = ["Project Hail Mary", "The Hobbit", "Sherlock Holmes", "The Hobbit", "Dune"]

(Note: If we were to submit this lab, which we won't, then Gradescope would replace the contents of this variable with other books.)

The first thing the program should do is display a title, the number of books in the library, and all the books, followed by a blank line:

= Little Free Library =
Count: 5 book(s)
['Project Hail Mary', 'The Hobbit', 'Sherlock Holmes', 'The Hobbit', 'Dune']

Step 2: count()

The program should then ask the user which book they would like and tell the user how many copies of that book are available:

Enter the title of a book to find: The Hobbit
We have 2 copies of "The Hobbit" available.

Step 3: pop()

Then, the program should ask the user for the index of a book to take, print the name of the book, then remove it from the list and print the updated list, followed by a blank line:

Enter the index of a book to take: 1
You took "The Hobbit".
['Project Hail Mary', 'Sherlock Holmes', 'The Hobbit', 'Dune']

Step 4: append()

Finally, ask the user for the name of a book they would like to leave, and put the book at the end of the list. Print out the full list of books again to show what the list looks like now.

What book would you like to leave? The Martian
['Project Hail Mary', 'Sherlock Holmes', 'The Hobbit', 'Dune', 'The Martian']

Step 5: Extra

Find at least one way to extend the lab in a direction of your choice. For example, you can change the word "copies" to "copy" of the count is 1. Or you can demonstrate calling other methods of list. What else can you do with this example program?

Step 6: Demo your work for activity credit

Demo your work to Dr. Simmons or Dylan to receive credit.

Next Topic: While loops

Introduction to while loops   [5 min]

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