Lab 2
Objectives
By the end of the lab, you will have:
- Practiced writing functions.
- Experimented with strings
- Opened multiple files in Thonny
- Converted a written description of a problem into a program
- Created your own module!
Part 0: Setup
To begin, download the file lab02.zip
by clicking the blue “Download Starter Files” button at the top of the lab, and extract the files from the zip file into a directory called lab02
inside your labs
directory.
Part 1: Username generator
Middlebury ITS has just hired you to write a function that will generate usernames for all incoming new students.
Start by opening the lab02_part1.py
file with Thonny.
In the location specified in the script, create a function called username_generator
with one parameter (a string) called name
We’ve given you a test string, stored in the variable name
, that you can start using ("Frida Kahlo"
). You will need to extract the first initial and the last name, concatenate them together, and make sure they are lowercase. As a twist, however, we are going to put a hard limit of 8 characters on the length of the username.
-> fkahlo
Frida Kahlo -> dwashing
Denzel Washington -Yo Ma -> yma
Yo-> hpotter
Harry Potter -> mwazowsk Mike Wazowski
In the following steps, we are going to practice progressive development. In other words, we will do a piece of the problem, check to see if we got it right, then do the next piece, etc., until we get done. You only need to turn in the final solution.
- Step zero: Start by writing a docstring that describes what your function does. The rest of the steps refer to the code inside the function.
- Step one: Create a new variable and assign it the location of the space separating the two names.
name.find(" ")
return?
The find()
function is used to locate sub-strings within a string. (Try it out in the interactive mode: create a string s = "name"
and then try the command type s.find("m")
see what comes back). Use this to find the location of the space.
- Step two: Create a new variable called
last_name
and store the last name of the person in it. Use a slice and the index you discovered in the last step.1 - Step three: Testing checkpoint Determine the last name. Click the run button with your name in the
name
variable. If you want to temporary check if thelast_name
variable contains your last name, you can add aprint(last_name)
statement in your function. That should show the value in the console when you run your code. This is a technique that is often used to debug code. Inserting temporary print statement to check values of variable. Just remember to remove them once your code is working as you want. If you see your last name printed, carry on. If there were extra characters (like spaces) fix your code until it works properly. Don’t worry about the fact that this is not what we eventually want to compute. The idea of progressive development is to set intermediary goals that are easier to achieve. - Step four: Create a new variable to hold the username called
username
. Assign it a string consisting of the first letter of the first name concatenated with the last name. - Step five: Convert the username to lowercase. You can use the
lower()
function to do this. In other words,username.lower()
. (As for.find()
, you can try this in the interactive window. Notice that using the.lower()
function does not change your original variable username so, once again, you might want to save the returned value to be able to use it!) - Step six: Testing checkpoint Run your script again. Is it creating lowercase usernames? If so, move to the next step.
- Step seven: Add a slice to the username to make sure that it is no longer than 8 characters long.
- Step eight: Return your usename, if you haven’t already
- Step nine: Test, test, test… and test some more! Try a bunch of names (we have given you some in the assignment). Make sure that some are short and some are long. Make sure that they are capitalized going in and lowercase coming out. For example, try “Mike Wazowski” and make sure you get “mwazowsk”. Finally, make sure that you are printing the returned values outside of the scope of the function!
Note: this is a long winded approach to this. Experienced programmers would compose together several of these steps into a single line. You are welcome to try this once it is working, but remember, even though we could condense this down to one line doesn’t mean we should. It won’t necessarily be any faster (it could even be slower) and it will probably be harder to read. Some terseness can make code easier to read, while a lot of it can make it very hard to read. Judging when that transition happens can be tricky.
Part 2: Writing and using a module
In class, we introduced you to the math
module, which had a bunch of mathematical functions (sqrt()
, pow()
, etc.).
Living in beautiful rural Vermont, you might be asked one day to write some functions that will help out the local farmers. We can write these functions into our own module and let the farmers use them by importing the module. Remember that to use a module/library in python, you need to import it by using the import
command (e.g. import math
).
Calculating the area of different field shapes
You are going to create a set of functions called get_field_area_shape(length)
, where shape can be one of circle
, square
, and triangle
(an equilateral triangle) (e.g., one function would be get_field_area_circle(length)
and so on). Each function calculates the area of fields of that particular shape. The parameter (length) is a number providing a length that will be used to calculate the area for the selected shape. In other words:
- When the shape is a ‘circle’, the length should be interpreted in the function as the radius of the circle.
- When the shape is a ‘square’, the length should be interpreted in the function as the length of each square side.
- When the shape is a ‘triangle’ (equilateral), the length should be interpreted in the function as the length of each triangle side.
The function get_field_area_circle(length)
is only partially written and the ones for the other shapes are missing. Your job is to finish the existing function, and write the missing ones!
We have given you some files to get started:
lab02_part2_farm.py
: This will be our farm module where we will write the functions for this lab.lab02_part2_main.py
: This will be the main script which will call the functions in the farm module.
Please follow these steps:
- Step 1: Open the files
lab02_part2_farm.py
andlab02_part2_main.py
in Thonny. These were downloaded as part of the.zip
file earlier. Note: You can have multiple files open in Thonny using multiple tabs (the same way you might have multiple tabs open in your browser). The first screenshot below is focused on thelab02_part2_main.py
tab whereas the second is focused on thelab02_part2_farm.py
tab. Yours should be similar.
- Step 2: Try running the main script, and note the value that you get. Troubleshoot the problem and modify the function in your module so that, when you calculate the area of the circle, you get the correct value. (For a radius of 0.5 should be close to 0.7854). Hint: feel free to import other modules in your farm module. Can you think of a module where you could get the value of pi?
- Step 3: In the farm module, write the
get_field_area_square
function, with one parameter,length
. - Step 4: In the main script add a line that calls the area calculation for a square with a side length of 0.8, and one to print it (just like for the circle). The result for this side should be 0.64. If your result is incorrect, go back to your
get_field_area_square
function and debug! - Step 5: Repeat steps 3 and 4 for the case of a triangle. It is equilateral so you can actually find the area using just the length of the side (look it up!). For an equilateral triangle with side length 0.75, that the area is close to 0.2436.
Congratulations! You have just written your first module!
Finishing Up
You should be turning in three files:
lab02_part1.py
(containing your username generator function)lab02_part2_farm.py
(containing the get_field_area_shape functions) andlab02_part2_main.py
(containing all the commands you use to call your farm module).
One you are done, submit all three files to gradescope and ensure that you have passed all of the tests.
Footnotes
Note: the implementation that we are going through is not very inclusive. It doesn’t allow for example for double first names or double last names. This is because we have not yet learned some of the programming structures that will allow us to easily do that! Once we have discussed conditionals, we encourage you to come back to this exercise and modify your code so that it will work also if somebody has a double last name (in which case you might want to just use the first of the two in your function).↩︎