github_username = "YOUR_GITHUB_USERNAME"
print(github_username)Homework 1
Python Fundamentals
0) π§π» Setup
Question 0a
Create a variable named github_username (string) and print it.
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)
- Create a list named
seat_numberscontaining integers 2 through 9. - Append
10. - Remove
6. - 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:
- Print the second element.
- Write one line of code that tries to change the year to 2027.
- 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}- Add
"cookie": 1.50 - Update the price of
"coffee"to3.00 - 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 = 4Compute 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)
- Using only
+and*, build and print this exact string:
"Go Knights! Go Knights! Go Knights!"
You may start with:
chant = "Go Knights!"- 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"- Convert
pi_textto a float namedpi_value. - Convert
pi_valueto an integer namedpi_int. - Print
pi_text,pi_value,pi_intand 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
99to a string. - Convert
Falseto 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 = 83Print:
"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 = 120Print:
"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:
word[:]word[4:]word[:4]word[:-3]word[2:8]word[::3]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:
- the first 3 items
- every 2nd item starting from the beginning
- the last 2 items
- 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]- Compute the average temperature.
- 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 = 150Each 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:
- integers from 5 to 15
- multiples of 3 from 0 to 30
- 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"]- Remove only the first
"B"using.remove()and print the list. - Starting from the original list again, remove all
"B"values using list comprehension and print. - Starting from the original list again, delete the middle two elements using
delwith 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}- Add
"markers": 4using.update() - Change
"pens"to 12 using.update() - Delete
"erasers"usingdel
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 = 0Use 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:
Uses
enumerate()to print:1) pushups2) plank- β¦
Computes the average minutes.
For each exercise, print a line like:
"squats: 12 min (Above Avg)"or"plank: 5 min (Below Avg)"(Use f-strings.)
Create a dictionary
exercise_to_minutesusing dictionary comprehension.Use
try/exceptto attempt to printexercise_to_minutes["stretch"].- If missing, print
"stretch is not in the plan."
- If missing, print
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.")