Lab 2

Objectives

  • Write and test your own functions
  • Work with strings
  • Open and use multiple files in Thonny
  • Translate problem descriptions into code
  • Create and use a custom module

Part 0: Setup

Download the file lab2.zip by clicking the blue “Download Starter Code” button at the top of the lab; move the zip file to your cs145/labs directory, then double-click on the zip file to create a subfolder called lab2 inside your labs directory.

Part 1: Username generator

Open lab2_part1.py from within Thonny. Write a function that takes a name and forms a username from it.

def username_generator(name):
    """
    Generate a lowercase username from the first letter of
    first name followed by up to 7 characters of last name

    Parameters:
        name (str): full name, e.g. "Frida Kahlo"

    Returns:
        str: generated username

    Example:
        >>> username_generator("Mike Wazowski")
        'mwazowsk'
    """

Examples:

  • “Frida Kahlo” → fkahlo
  • “Denzel Washington” → dwashing
  • “Mike Wazowski” → mwazowsk

Hints:

  • Use .find(" ") to locate the space between the first and last name. (Eg, if s is "Grace Hopper" then s.find(" ") returns 5)
  • Use slicing to extract the last name. (Eg, if s is "Grace Hopper" then s[6:] returns “Hopper”)
  • Concatenate the first initial and the last name.
  • Convert to lowercase with .lower().
  • Slice to a maximum of 8 characters.
  • Test with several names until correct.

Part 2: Area computations

Here, you will build a small module for calculating areas. Open lab2_part2.py from within Thonny.

Tasks:

  1. Finish get_area_circle(length). Here, length refers to the radius of a circle. You will want to use math.pi.
  2. Add get_area_square(length). Here, length refers to the side length.
  3. Add get_area_triangle(length). Here, length refers to the side of an equilateral triangle.
  4. Test with several values, eg:
    • Circle with radius 1 → ≈ 3.14159
    • Square with side 2.5 → 6.25
    • Triangle with side 3 → ≈ 3.897

Part 3: Testing and Using a Module

Now, let’s use your modules from a third file. Open lab2_main.py from within Thonny. We have already added the import statements for you. Add calls to your functions defined in lab2_part1 and lab2_part2 from this third file. A couple models are provided for you. Check the following results:

  • Circle with radius 0.5 → ≈ 0.7854
  • Square with side 0.8 → 0.64
  • Triangle with side 0.75 → ≈ 0.2436

Submitting your work

When you are done, submit these three files to Gradescope:

  • lab2_part1.py
  • lab2_part2.py
  • lab2_main.py

Ensure that the upload succeeds and your submission passes all visible tests.