Lab

5.3.2. Lab#

  • Use this lab to practice the chapter’s coding skills in runnable Python code.

  • Sign in from the account menu before you start working on the lab.

  • Launch Live Code (the rocket) to write and run code in the coding cells.

  • Multiple submissions are allowed. The highest score is kept.

### Question 1: Safe conversion with try/except
# Write safe_float(s) that:
# 1. Tries to convert the string s to a float with float(s).
# 2. Returns the float if conversion succeeds.
# 3. If s cannot be converted, catches the ValueError, prints a message
#    built with an f-string that puts s inside single quotes, as in
#    f"Cannot convert '{s}' to float", and returns None.
# Call safe_float("3.14") and safe_float("abc"), printing each result.
# Print exactly these three lines:
# 3.14
# Cannot convert 'abc' to float
# None
### Your code starts here.



### Your code ends here.

Hide code cell source

### Solution
def safe_float(s):
    try:
        return float(s)
    except ValueError:
        print(f"Cannot convert '{s}' to float")
        return None

print(safe_float("3.14"))
print(safe_float("abc"))
3.14
Cannot convert 'abc' to float
None
### Question 2: Validating input with raise
# Write validate_rectangle(width, height) that uses if statements and
# raise ValueError(...) to reject bad input:
# 1. If width or height is not positive, raise ValueError with the
#    message "Width and height must be positive".
# 2. If width or height is greater than 100, raise ValueError with the
#    message "Width and height must be at most 100".
# Call validate_rectangle(10, 20) and print a confirmation line. Then catch
# the failures from validate_rectangle(-5, 20) and
# validate_rectangle(10, 500) with except ValueError as e, printing
# f"ValueError: {e}" for each.
# Print exactly these three lines:
# (10, 20) is a valid rectangle
# ValueError: Width and height must be positive
# ValueError: Width and height must be at most 100
### Your code starts here.



### Your code ends here.

Hide code cell source

### Solution
def validate_rectangle(width, height):
    if width <= 0 or height <= 0:
        raise ValueError("Width and height must be positive")
    if width > 100 or height > 100:
        raise ValueError("Width and height must be at most 100")

validate_rectangle(10, 20)
print("(10, 20) is a valid rectangle")

try:
    validate_rectangle(-5, 20)
except ValueError as e:
    print(f"ValueError: {e}")

try:
    validate_rectangle(10, 500)
except ValueError as e:
    print(f"ValueError: {e}")
(10, 20) is a valid rectangle
ValueError: Width and height must be positive
ValueError: Width and height must be at most 100
### Question 3: Multiple exception types
# Write safe_percentage(score, total) that:
# 1. Returns score / total * 100.
# 2. Catches ZeroDivisionError (total is 0): prints a message, returns None.
# 3. Catches TypeError (score or total is not a number): prints a message,
#    returns None.
# Print exactly these five lines:
# 75.0
# Error: total cannot be zero
# None
# Error: score and total must be numbers
# None
### Your code starts here.



### Your code ends here.

Hide code cell source

### Solution
def safe_percentage(score, total):
    try:
        return score / total * 100
    except ZeroDivisionError:
        print("Error: total cannot be zero")
        return None
    except TypeError:
        print("Error: score and total must be numbers")
        return None

print(safe_percentage(45, 60))
print(safe_percentage(45, 0))
print(safe_percentage(45, "sixty"))
75.0
Error: total cannot be zero
None
Error: score and total must be numbers
None
### Question 4: try/except/else/finally together
# Write safe_lookup(record, field) that:
# 1. Tries value = record[field].
# 2. Catches KeyError: prints a message naming the missing field, sets
#    value to None.
# 3. Uses else to print "Field found." only when the lookup succeeds.
# 4. Uses finally to always print "Lookup attempt finished."
# 5. Returns value.
# Call safe_lookup(student_record, "grade") and
# safe_lookup(student_record, "email"), printing each result.
# Print exactly these six lines:
# Field found.
# Lookup attempt finished.
# A
# Field 'email' not found
# Lookup attempt finished.
# None
student_record = {"name": "Priya", "grade": "A"}
### Your code starts here.



### Your code ends here.

Hide code cell source

### Solution
def safe_lookup(record, field):
    try:
        value = record[field]
    except KeyError:
        print(f"Field '{field}' not found")
        value = None
    else:
        print("Field found.")
    finally:
        print("Lookup attempt finished.")
    return value

student_record = {"name": "Priya", "grade": "A"}

print(safe_lookup(student_record, "grade"))
print(safe_lookup(student_record, "email"))
Field found.
Lookup attempt finished.
A
Field 'email' not found
Lookup attempt finished.
None
### Question 5: Raising exceptions by condition
# Write check_password_strength(password) that:
# 1. Raises TypeError with a descriptive message that includes
#    type(password).__name__ if password is not a string.
# 2. Raises ValueError with a descriptive message if password has fewer
#    than 8 characters.
# 3. Otherwise returns True.
# Call check_password_strength("longenough") and print the result.
# Then catch failures from check_password_strength("short") and
# check_password_strength(12345678), printing each caught message.
# Print exactly these three lines:
# True
# ValueError: Password must be at least 8 characters
# TypeError: Password must be a string, got int
### Your code starts here.



### Your code ends here.

Hide code cell source

### Solution
def check_password_strength(password):
    if not isinstance(password, str):
        raise TypeError(f"Password must be a string, got {type(password).__name__}")
    if len(password) < 8:
        raise ValueError("Password must be at least 8 characters")
    return True

print(check_password_strength("longenough"))

try:
    check_password_strength("short")
except ValueError as e:
    print(f"ValueError: {e}")

try:
    check_password_strength(12345678)
except TypeError as e:
    print(f"TypeError: {e}")
True
ValueError: Password must be at least 8 characters
TypeError: Password must be a string, got int