# NOTE: In Python, exponentiation is ** (not ^)
result = (2**5) / (7 * (4 - 2**3))Classwork 2
Python Fundamentals
Question 1. Python Operations and Basic Data Structures
(a) Arithmetic with Powers and Parentheses
Using Python operations only, calculate below: \[\frac{2^5}{7 \cdot (4 - 2^3)}\]
- -1.1428571428571428 (which is exactly -8/7)
(b) Adding Mixed Types by Converting Strings
Given:
data = [10, 2.5, "3"]Using Python only, calculate 10 + 2.5 + 3
total = data[0] + data[1] + float(data[2])(c) Computing a Weighted Exam Score with max()
Given:
exam_score = {"Midterm": 78, "Final": 92}Compute the Total Exam Score:
\[ \begin{align} \text{(Total Exam Score)} = \max\{ &0.50\times \text{(Midterm)} + 0.50\times \text{(Final)},\\ &0.33\times \text{(Midterm)} + 0.67\times \text{(Final)} \} \end{align} \]
simple_avg = 0.50 * exam_score["Midterm"] + 0.50 * exam_score["Final"]
weighted_avg = 0.33 * exam_score["Midterm"] + 0.67 * exam_score["Final"]
total_exam_score = max(simple_avg, weighted_avg)Question 2. Boolean Expressions and Logic
For each expression below, what is the value of the expression? Explain thoroughly.
(a) Comparing Different Data Types (int vs str)
20 == '20'False- Why?
- 20 is an integer, but β20β is a string.
- Different types are not equal.
(b) Logical Operators with Comparisons (or)
x = 4.0
y = .5
x < y or 3*y < xTrue- Why?
x < yβ 4.0 < 0.5 βFalse3*y < xβ 1.5 < 4.0 βTrueFalse or TrueβTrue
Question 3. Conditional Statements (if / elif / else)
(a) Tracing an if-Chain (Membership and Thresholds)
What will the following code print? (Answer without running it.)
status = "Gold"
cart_total = 92.5
free_shipping_levels = ["Gold", "Platinum"]
if status in free_shipping_levels:
shipping = 0
msg = f"Status: {status} β Free shipping! Total = ${cart_total}"
elif cart_total >= 100:
shipping = 0
msg = f"Spend threshold met β Free shipping! Total = ${cart_total}"
else:
shipping = 7.99
msg = f"Status: {status}, Total = ${cart_total} β Shipping = ${shipping}"
print(msg)What will it print?
statusis"Gold""Gold"in["Gold", "Platinum"]is True, so the first if-branch runs.
So it prints:
Status: Gold β Free shipping! Total = $92.5
(b) Fill-in-the-Blanks: Writing an if-elif-else Chain
- Fill in the blanks:
- If
nameis"Geneseo"andscore >= 90β print"Geneseo high score" - Else if
score >= 90β print"High score" - Else β print
"Try again"
- If
name = "Geneseo"
score = 88
# Fill in the blanks
if ______________________________:
print("Geneseo high score")
elif ____________________________:
print("High score")
else:
print("Try again")name = "Geneseo"
score = 88
if name == "Geneseo" and score >= 90:
print("Geneseo high score")
elif score >= 90:
print("High score")
else:
print("Try again")Question 4. List Slicing and String Slicing
(a) Predicting Output from List Slices
What will the following code print? (Do not run itβreason it out.)
nums = [10, 20, 30, 40, 50, 60, 70]
print(nums[2:6])
print(nums[:4])
print(nums[::2])
print(nums[-4:-1])[30, 40, 50, 60]
[10, 20, 30, 40]
[10, 30, 50, 70]
[40, 50, 60]
(b) Extracting Numbers from Strings with Slicing
fare = "$10.00"
tip = "2.00$"
tax = "$ 0.80"Write a Python code that uses slicing and the print() function to print out the following message:
fare_num = float(fare[1:]) # "10.00"
tip_num = float(tip[:-1]) # "2.00"
tax_num = float(tax[2:]) # "0.80"
total = fare_num + tip_num + tax_num
print(f"The total trip cost is: ${total:.2f}")Question 5. Finding the Maximum Value in a List
list_variable = [100, 144, 169, 1000, 8]Write a Python code that uses print() and max() functions to print out the largest value in the list, list_variable, as follows:
list_variable = [100, 144, 169, 1000, 8]
largest = max(list_variable)
print(f"The largest value in the list is: {largest}")Question 6. Looping Through a List (while vs for)
vals = [3, 2, 1, 0](a) while loop
Use a while loop to print each value of the list [3, 2, 1, 0], one at a time.
vals = [3, 2, 1, 0]
counter = 0
while counter < len(vals):
print(vals[counter])
counter += 1(b) for loop
Use a for loop to print each value of the list [3, 2, 1, 0], one at a time.
vals = [3, 2, 1, 0]
for val in vals:
print(val)Question 7. Loop Control with Comparisons and Early Exit
Start with guess_me = 7 and number = 1.
guess_me = 7
number = 1(a) while loop
Write a while loop that keeps running until you break:
- If
number < guess_me, print"too low"and then incrementnumberby 1. - If
number == guess_me, print"found it!"and then break. - If
number > guess_me, print"oops"and then break.
guess_me = 7
number = 1
while True:
if number < guess_me:
print("too low")
number += 1
elif number == guess_me:
print("found it!")
break
else:
print("oops")
break(b) for loop
Write the same logic using a for loop that tries values from 1 to 10:
- If the current value is less than
guess_me, print"too low". - If it equals
guess_me, print"found it!"and thenbreak. - If it is greater than
guess_me, print"oops"and thenbreak.
guess_me = 7
number = 1
for num in range(1,11):
if num < guess_me:
print("too low")
elif num == guess_me:
print("found it!")
break
else:
print("oops")
breakQuestion 8. Comprehensions & Modifying Collections
(a) List & Dictionary Comprehensions
Given a list of three dictionaries:
lst_students = [
{"name": "Ava", "major": "DANL", "score": 91},
{"name": "Ben", "major": "ECON", "score": 84},
{"name": "Cara", "major": "DANL", "score": 76},
]- Use a list comprehension to create
danl_names, the names of students whose major is"DANL".
- Use a dictionary comprehension to create
danl_scoresmapping name β score for only"DANL"students.
# (a) Comprehensions
# list comprehension
danl_names = [d["name"] for d in lst_students if d["major"] == "DANL"]
# dict comprehension
danl_scores = {d["name"]: d["score"] for d in lst_students if d["major"] == "DANL"}(b) Modifying Lists & Dictionaries
- Modify
numsusing.append()to add99.
nums = [2, 5, 2, 8]- Modify
gradesusing.update()to (i) add"Cara": 76and (ii) change"Ben"to90.
grades = {"Ava": 91, "Ben": 84}# (b) Modifying lists & dictionaries
nums.append(99)
grades.update({"Cara": 76, "Ben": 90})Question 9. Error Handling with tryβexcept
You are given a variable value that stores a string:
value = "$320"Write a Python program that does the following:
- Attempt to convert value into a floating-point number using
float(). - If the conversion is successful, print:
You entered:
- If the conversion fails (for example, because the string is not a valid number), print:
Thatβs not a valid number!
Your program must use a tryβexcept block to handle the potential error gracefully.
Question 10. Imports and Library Setup (pandas + selenium)
(a) Importing a Library with an Alias
Import the pandas library as pd.
import pandas as pd(b) Installing an External Library
Install the selenium library.
!pip install selenium(c) Importing from a Submodule
From selenium, import the function webdriver.
from selenium import webdriverDiscussion
Welcome to our Classwork 2 Discussion Board! π
This space is designed for you to engage with your classmates about the material covered in Classwork 2.
Whether you are looking to delve deeper into the content, share insights, or have questions about the content, this is the perfect place for you.
If you have any specific questions for Byeong-Hak (@bcdanl) regarding the Classwork 2 materials or need clarification on any points, donβt hesitate to ask here.
All comments will be stored here.
Letβs collaborate and learn from each other!