Homework 1

Python Fundamentals

Author

Byeong-Hak Choe

Published

February 1, 2026

Modified

February 16, 2026

0) πŸ§‘πŸ’» Setup

Question 0a

Create a variable named github_username (string) and print it.

github_username = "YOUR_GITHUB_USERNAME"
print(github_username)

Question 0b

In one code cell, print:

  • your Python version (hint: import sys)
  • today’s date (hint: import datetime)
import sys
import datetime

print(sys.version)
print(datetime.date.today())



1) πŸ“¦ Containers: List, Tuple, Dictionary

Question 1a (List edits)

  1. Create a list named seat_numbers containing integers 2 through 9.
  2. Append 10.
  3. Remove 6.
  4. Print the final list.
seat_numbers = list(range(2, 10))  # 2 through 9
seat_numbers.append(10)
seat_numbers.remove(6)
print(seat_numbers)

Question 1b (Tuple: immutability)

Create a tuple named campus:

  • campus = ("SUNY Geneseo", 2026)

Then:

  1. Print the second element.
  2. Write one line of code that tries to change the year to 2027.
  3. In a Markdown cell, explain what happens and why.
campus = ("SUNY Geneseo", 2026)

print(campus[1])

# One line that tries to change the year (this will fail):
# campus[1] = 2027

# Demonstrate safely:
try:
    campus[1] = 2027
except:
    print("TypeError")

Explanation: Tuples are immutable, so you cannot modify an existing element after the tuple is created.

Question 1c (Dictionary: add/update/iterate)

Start with:

menu_prices = {"coffee": 2.75, "tea": 2.25, "sandwich": 6.50}
  1. Add "cookie": 1.50
  2. Update the price of "coffee" to 3.00
  3. Print:
    • all item names (keys)
    • all prices (values)
    • each (item, price) pair on its own line
menu_prices = {"coffee": 2.75, "tea": 2.25, "sandwich": 6.50}

menu_prices["cookie"] = 1.50
menu_prices["coffee"] = 3.00

print("Keys:", list(menu_prices.keys()))
print("Values:", list(menu_prices.values()))
print("Items:")

for item, price in menu_prices.items():
    print(item, price)



2) βž• Operators and Casting

Question 2a (Arithmetic operators)

Let:

x = 17
y = 4

Compute and print:

  • x + y, x - y, x * y, x ** y, x / y, x // y, x % y
x = 17
y = 4

print(x + y)
print(x - y)
print(x * y)
print(x ** y)
print(x / y)
print(x // y)
print(x % y)

Question 2b (Operators with strings and lists)

  1. Using only + and *, build and print this exact string:
  • "Go Knights! Go Knights! Go Knights!"

You may start with:

chant = "Go Knights!"
  1. Using only + and *, create a list that repeats ["lab", "lecture"] 4 times.
chant = "Go Knights!"

# Only + and * (no join)
triple = (chant + " ") * 2 + chant
print(triple)

repeat_list = ["lab", "lecture"] * 4
print(repeat_list)

Question 2c (Casting)

Given:

pi_text = "3.14159"
  1. Convert pi_text to a float named pi_value.
  2. Convert pi_value to an integer named pi_int.
  3. Print pi_text, pi_value, pi_int and their types.
pi_text = "3.14159"
pi_value = float(pi_text)
pi_int = int(pi_value)

print(pi_text, type(pi_text))
print(pi_value, type(pi_value))
print(pi_int, type(pi_int))



3) πŸ”Ž Types + Conversions Practice

Question 3a (Print value + type)

Given:

mixed = ["42", 99, 0.5, False, None, {"course": "DANL 210"}, (1, 2, 3)]

Use a for loop to print each element and its type.

mixed = ["42", 99, 0.5, False, None, {"course": "DANL 210"}, (1, 2, 3)]

for x in mixed:
    print(x, type(x))

Question 3b (Targeted conversions)

Using mixed above, do the following conversions and print results + types:

  • Convert the string "42" to an integer.
  • Convert the integer 99 to a string.
  • Convert False to an integer.
mixed = ["42", 99, 0.5, False, None, {"course": "DANL 210"}, (1, 2, 3)]

a = int(mixed[0])        # "42" -> 42
b = str(mixed[1])        # 99 -> "99"
c = int(mixed[3])        # False -> 0

print(a, type(a))
print(b, type(b))
print(c, type(c))



4) βœ… Conditions, in, f-Strings, and if Chains

Question 4a (if-elif-else)

Set:

score = 83

Print:

  • "Fail" if score < 60
  • "Pass" if 60 <= score < 80
  • "Great" if 80 <= score < 95
  • "Perfect" if score >= 95
score = 83

if score < 60:
    print("Fail")
elif score < 80:
    print("Pass")
elif score < 95:
    print("Great")
else:
    print("Perfect")

Question 4b (Nested if)

Set:

membership = "Gold"
total_spent = 120

Print:

  • "Free shipping" if membership is "Gold" and total_spent >= 100
  • "5% coupon" if membership is "Silver" and total_spent >= 100
  • "No perk" otherwise
membership = "Gold"
total_spent = 120

if membership == "Gold":
    if total_spent >= 100:
        print("Free shipping")
    else:
        print("No perk")
elif membership == "Silver":
    if total_spent >= 100:
        print("5% coupon")
    else:
        print("No perk")
else:
    print("No perk")

Question 4c (in membership test + f-string)

Given:

cities = ["Rochester", "Buffalo", "Syracuse", "Albany"]
target = "Albany"

Use in to print:

  • "Albany is on the list!" if present
  • otherwise "Albany is not on the list."

(Use an f-string.)

cities = ["Rochester", "Buffalo", "Syracuse", "Albany"]
target = "Albany"

if target in cities:
    print(f"{target} is on the list!")
else:
    print(f"{target} is not on the list.")

Question 4d (Boolean reasoning)

Compute and print the value of:

  • not (not False)
  • 7 == "7"
  • (10 > 3) and (2 >= 2)
  • (10 < 3) or (2 == 2)
print(not (not False))
print(7 == "7")
print((10 > 3) and (2 >= 2))
print((10 < 3) or (2 == 2))



5) βœ‚οΈ Slicing + len()

Question 5a (String slicing)

Given:

word = "datascience"

Print the result of each:

  1. word[:]
  2. word[4:]
  3. word[:4]
  4. word[:-3]
  5. word[2:8]
  6. word[::3]
  7. word[::-1]
word = "datascience"

print(word[:])
print(word[4:])
print(word[:4])
print(word[:-3])
print(word[2:8])
print(word[::3])
print(word[::-1])

Question 5b (List slicing)

Given:

playlist = ["Intro", "Beat", "Chorus", "Bridge", "Solo", "Outro"]

Print:

  1. the first 3 items
  2. every 2nd item starting from the beginning
  3. the last 2 items
  4. the list reversed (using slicing)
playlist = ["Intro", "Beat", "Chorus", "Bridge", "Solo", "Outro"]

print(playlist[:3])
print(playlist[::2])
print(playlist[-2:])
print(playlist[::-1])

Question 5c (len() practice)

Compute and print:

  • len("machinelearning")
  • len([10, 20, 30, 40])
  • len(playlist)
print(len("machinelearning"))
print(len([10, 20, 30, 40]))
print(len(playlist))



6) πŸ” Loops: for, while, range(), enumerate()

Question 6a (Average + labels)

Given:

temps = [32, 28, 30, 35, 27]
  1. Compute the average temperature.
  2. For each temperature, print "Above Avg" if it is above average, otherwise "Below Avg".
temps = [32, 28, 30, 35, 27]
avg = sum(temps) / len(temps)
print("Average:", avg)

for t in temps:
    if t > avg:
        print("Above Avg")
    else:
        print("Below Avg")

Question 6b (while loop: savings)

Start with:

balance = 150

Each week you save 25. Use a while loop until the balance reaches or exceeds 300.

Print the balance each week.

balance = 150

while balance < 300:
    balance += 25
    print(balance)

Question 6c (range() patterns)

Using range(), create and print:

  1. integers from 5 to 15
  2. multiples of 3 from 0 to 30
  3. countdown from 12 to 0
print(list(range(5, 16)))
print(list(range(0, 31, 3)))
print(list(range(12, -1, -1)))

Question 6d (enumerate() index + value)

Given:

tasks = ["download", "open", "run", "submit"]

Use enumerate() to print each task with its step number starting at 1 like:

  • Step 1: download
tasks = ["download", "open", "run", "submit"]

for i, task in enumerate(tasks, start=1):
    print(f"Step {i}: {task}")



7) 🧠 Comprehensions + Modifying Containers

Question 7a (List comprehension: cubes)

Use list comprehension to create a list of cubes for 1 through 6.

Store it in cubes and print it.

cubes = [x**3 for x in range(1, 7)]
print(cubes)

Question 7b (List comprehension: filter)

Given:

vals = [0, 5, 10, 0, 20, 0, 25]

Use list comprehension to create a new list that removes all zeros.

vals = [0, 5, 10, 0, 20, 0, 25]
no_zeros = [v for v in vals if v != 0]
print(no_zeros)

Question 7c (Dictionary comprehension: length of words)

Given:

words = ["data", "science", "python", "loop"]

Use dictionary comprehension to create a dictionary mapping each word to its length.

Print the dictionary.

words = ["data", "science", "python", "loop"]
word_len = {w: len(w) for w in words}
print(word_len)

Question 7d (Modify list: remove/keep/delete)

Given:

tickets = ["A", "B", "C", "B", "D", "B"]
  1. Remove only the first "B" using .remove() and print the list.
  2. Starting from the original list again, remove all "B" values using list comprehension and print.
  3. Starting from the original list again, delete the middle two elements using del with slicing and print.
tickets = ["A", "B", "C", "B", "D", "B"]

t1 = tickets.copy()
t1.remove("B")
print(t1)

t2 = [x for x in tickets if x != "B"]
print(t2)

t3 = tickets.copy()
del t3[2:4]   # delete the middle two elements (indices 2 and 3)
print(t3)

Question 7e (Modify dictionary: update + delete)

Given:

inventory = {"pens": 10, "notebooks": 5, "erasers": 2}
  1. Add "markers": 4 using .update()
  2. Change "pens" to 12 using .update()
  3. Delete "erasers" using del

Print after each step.

inventory = {"pens": 10, "notebooks": 5, "erasers": 2}

inventory.update({"markers": 4})
print(inventory)

inventory.update({"pens": 12})
print(inventory)

del inventory["erasers"]
print(inventory)



8) 🧯 Exceptions: try-except

Question 8a (Division safety)

Given:

numerator = 24
denominator = 0

Use try-except to attempt division. If an error occurs, print "Division failed!".

numerator = 24
denominator = 0

try:
    print(numerator / denominator)
except:
    print("Division failed!")

Question 8b (Convert text to number)

Given:

entries = ["10", "8", "oops", "15"]

Loop through entries and try to convert each to an integer.

  • If conversion works, print the integer.
  • If it fails, print "Not a number: oops" (use the actual bad value).
entries = ["10", "8", "oops", "15"]

for e in entries:
    try:
        print(int(e))
    except:
        print(f"Not a number: {e}")

Question 8c (Missing values)

Given:

hours = {"Mon": 2, "Tue": None, "Wed": 3, "Thu": None, "Fri": 4}

Compute the total of non-missing hours and print the total.

hours = {"Mon": 2, "Tue": None, "Wed": 3, "Thu": None, "Fri": 4}

total = 0
for day, h in hours.items():
    if h is not None:
        total += h

print(total)

Question 8d (Missing dictionary key)

Given:

capitals = {"NY": "Albany", "CA": "Sacramento"}

Try to print capitals["TX"]. Handle the error so the program prints "State not found".

capitals = {"NY": "Albany", "CA": "Sacramento"}

try:
    print(capitals["TX"])
except:
    print("State not found")



9) πŸ“š Imports (Modules / Packages)

Question 9a (math)

Import math and compute math.sqrt(144). Print the result.

import math
print(math.sqrt(144))

Question 9b (import ... as ...)

Import math as m. Compute and print:

  • m.sqrt(144)
  • m.floor(9.99)
  • m.ceil(9.01)
import math as m
print(m.sqrt(144))
print(m.floor(9.99))
print(m.ceil(9.01))

Question 9c (from ... import ...)

Import only ceil from math and compute ceil(12.2). Print it.

from math import ceil
print(ceil(12.2))



10) 🧩 Mini Task: Put It All Together

Question 10 (Workout summary)

You are given:

exercises = ["pushups", "plank", "squats", "jog"]
minutes   = [10, 5, 12, 20]

Write code that:

  1. Uses enumerate() to print:

    • 1) pushups
    • 2) plank
    • …
  2. Computes the average minutes.

  3. For each exercise, print a line like:

  • "squats: 12 min (Above Avg)" or "plank: 5 min (Below Avg)" (Use f-strings.)
  1. Create a dictionary exercise_to_minutes using dictionary comprehension.

  2. Use try/except to attempt to print exercise_to_minutes["stretch"].

    • If missing, print "stretch is not in the plan."
exercises = ["pushups", "plank", "squats", "jog"]
minutes   = [10, 5, 12, 20]

# 1) enumerate
for i, ex in enumerate(exercises, start=1):
    print(f"{i}) {ex}")

# 2) average minutes
avg = sum(minutes) / len(minutes)
print("Average minutes:", avg)

# 3) above/below average
for i in range(len(exercises)):
    ex = exercises[i]
    m  = minutes[i]
    label = "Above Avg" if m > avg else "Below Avg"
    print(f"{ex}: {m} min ({label})")

# 4) dictionary comprehension
exercise_to_minutes = {exercises[i]: minutes[i] for i in range(len(exercises))}
print(exercise_to_minutes)

# 5) try/except for missing key (catch KeyError specifically)
try:
    print(exercise_to_minutes["stretch"])
except:
    print("stretch is not in the plan.")

βœ… End of Homework 1

Back to top