Lab 1: Functions Due: 09:00:00 AM on 2019-07-17

This assignment will walk you through the basics of using Thonny and writing your first functions in Python.

In general labs are organized into several sections:

  1. Background/Introduction: An explanation of the overall goal of the lab and any needed introduction to new features in Python, etc..
  2. Specifications: The specific functionality you are expected to implement including suggestions for creativity points.
  3. Guide: A narrative guide to completing the lab including suggestions, links to relevant documentation, etc..

This first lab will have more emphasis on the narrative guide.

Background

As we will discuss further in class, we incorporate comments, i.e. notes that are not executed, into our programs to communicate our thinking to future users or readers of our code. Python has two kinds of comments, inline comments (any part of the line after the #) and docstrings (text between sets of triple quotes, e.g. """). In this first lab we will use the former to document our functions, like shown in the example functions, and the latter to encapsulate text that should not be executed.

For reference, here are some simple example functions from lecture.

Specifications

You will be compiling a single Python file with multiple sections for this assignment. Please download and use the linked starter file. Right-click on the above link, select “Save as…”, and save the file as “lab1_functions.py” for this assignment. Then open the saved file with Thonny. Your future lab submissions will be expected to follow a similar format (most labs will not have a starter file). Note that the file name matters. The online submission system requires a specific filename.

At a minimum your submission should have:

Section 1: Interacting with Python

  1. Copy your Shell session (see guide) into the docstring comment in the starter file. The copied section should approximately be one page (and no more) and include the answer to the burger pricing problem in the guide section.

Section 2: We’ve got problems

  1. Fix the errors in the provided functions, noting in the comment above the function what you changed.

Section 3: Your first Python program

  1. Implement Python statements with and without enclosing print functions (see guide below).
  2. An implementation of the circle_area function.
  3. Implement Python statements that use your circle_area function.

Section 4: A semester abroad in Europe

Implement the following:

  1. A function named euros_to_dollars, that takes a single parameter, a price in euros represented as a floating point number, and returns the equivalent price in dollars. [1.5 points]
  2. A function named welcome that doesn’t take any parameters and prints out “welcome” in another language. [1.5 points]
  3. A function named kilometers_to_miles, that takes a single parameter, the number of kilometers, and returns the equivalent distance in miles. [1.5 points]
  4. A function named mpg_from_metric that takes two parameters: (1) the number of kilometers and (2) the number of liters. The function returns the miles per gallon (i.e., miles divided by gallons) by converting the kilometers and liters appropriately. [3 points]
  5. A function of your own that takes one or more parameters and does something interesting/useful. Be creative! [1.5 point]

Creativity Suggestions

It is OK to use Python features we haven’t yet discussed in class in your creativity features or elsewhere. There may be times in future labs when I want you to use a specific feature or data structure in a problem; if so, I will explicitly indicate so in the assignment.

Guide

Section 1: Interacting with Python

Start up Thonny as practiced in the prelab (you may need to find it in the Applications folder). Open the starter file you downloaded. Save the file with an appropriate name in a folder you have created for the class (and lab), making sure the file has a “.py” extension (the standard file extension for Python programs).

Try a few commands in the interactive shell in the bottom half of Thonny. Recall that >>> is the prompt, meaning Python is ready for a command; an indented line is a line continuation indicating that Python is waiting for you to finish the statement; and a line without anything in front of it is generally the response from the interpreter.

Try a few simple mathematical equations (e.g., 1 + 1, 2 ** 3, (100 // 20) + 45 * 7). Play around with the idea that Python ignores whitespace within expressions (and notice that Python makes for a pretty effective calculator).

22/7 is an approximation for the mathematical value π. Type in both 22/7 and 22//7 and note the difference.

Remember that we can use variables to store intermediary values. Assign 22/7 to a variable called pi (unicode Greek letters can be used in Python variable names but are awkward to type). Use your newly-created variable to calculate the area of a circle with radius 15. Note that in the shell you can use the up and down arrow keys to revisit commands you typed previously.

Now in your Shell session use Python to solve the following problem:

In-n-Out is a fast food hamburger chain in the western US (mostly California). In-n-Out has an extensive “secret menu” (my order is always a Double-Double animal style), that used to include the option to order burgers with an arbitrary number of patties and cheese slices, e.g. a 3×3 with 3 patties and 3 slices of cheese, a 4×4 with four of each and so on.

In 2004 when I lived in California, an In-n-Out hamburger (no cheese) was $1.50, a cheeseburger (one patty, one slice of cheese) was $1.75 and a Double-Double (two patties and two cheese slices) was $2.65. In-n-Out pricing is linear; the bun and fixings costs a fixed amount and each additional patty and slice of cheese also costs a fixed amount. Using Python and the information above compute the price in 2004 of the infamous 100×100 and a 100×50 (100 patties but only 50 cheese slices). Remember that a 100×100 still only has one bun and set of vegetable toppings. The log of your Python Shell should “show your work”, that is like the “hot dog” problem in lecture you should Python variables to compute various costs (e.g. for a slice of cheese) instead of figuring out the solution on paper and copying it into the Python shell. You may encounter decimal values that are close, but not exact, e.g. 0.449999999999999 instead of 0.45; that is OK (it is a result in limitations on how Python represents floating point numbers, and something we will learn about at the end of the semester).

When you’re ready to move on, copy and paste your shell session into the docstring comment in the starter file loaded in the Thonny editor. The total length of the copied section should be no more than 1 page. Recall that a docstring comment is between """, e.g.

"""
This is a docstring comment.
"""

Section 2: We’ve got problems

Fix any errors you observe in the Section 2 template, replacing the “???” in the comment with a few word description of your fix. You may find this Python debugging flowchart helpful. You can run the program by clicking the green circle with the white arrow to see the error that Python reports.

Section 3: Your first Python program

So far, we’ve mostly been interacting with the Python Shell (interpreter). This is good for some situations, but eventually you’re going to want to write longer programs that you can edit easily and persist when you quit Thonny. In this sections we will write Python statements in our Python program file and execute them. Note, that you won’t successfully be able to run your Python program until you fix the errors in Section 2 of the starter file.

Write a few Python statements into the appropriate section of the file, save it and then run your program.

Each line you enter in the file will be executed in the shell as if you typed it. For example, enter 22/7 in the file. You can run your file by clicking the green circle with the white arrow.

When you do so, you’ll notice that your program gets executed by the Python shell in the bottom panel. Most likely, though, your program won’t show anything in the shell window. Make sure you understand why your program displays what it does (or does not)!

Add some print statements in your program.

Recall that when you are running a program (rather than interacting with the shell) the intermediate results are not printed (like in the REPL). Instead, if you want values to be displayed you need to use the print function. You can print any expression, for example:

print(10)                       # Printing a number
print(22/7)                     # Printing the result of a more complex expression
pi = 22/7                       # Assign 22/7 to pi
print(pi)                       # Printing the value of a variable
print("Hello computer user")    # Printing a string

Add a few print statements to your program and run it again. You should now see some results printed out.

Write a function name circle_area that takes the radius as a parameter and returns the area of a circle with that radius.

Remember the basic structure for defining a function is (though not all functions will have return statements):

def function_name(parameters):
    statement1
    statement2
    ...
    return something

Recall that the way that Python can tell which expressions are part of the function body is based on the indenting.

Put in a print statement that prints out the area of a circle of radius 25 at the end of your program and then run your program. You should NOT have any print statements inside your circle_area function. Instead, you should call your function and print out the value returned.

Remember, we can print any expression:

print(circle_area(25))

This statement has multiple parts. The circle_area(25) part invokes or calls the function you just created, which, in turn, will execute the statements inside that function. When your function returns its result, that result will be passed as a parameter to the print function, which will cause the value to be printed in the shell/interpreter.

After running your program, play with the function in the interpreter.

After you’ve run your program, you can still interact with the interpreter (bottom right). For example, you can type:

>>> circle_area(12.4)
483.2457142857143

Section 4: A semester abroad in Europe

For the last part of this assignment, you will write some additional functions of your own (in the same file you have been working with all along).

Imagine you’re going on a semester abroad in Europe. To make the job of managing funds and considering traveling distances easier, you decide to write some functions to convert between currencies and units used in the United States to those used in European countries.

Write a function named euros_to_dollars, that takes a single parameter, a price in euros represented as a floating point number, and returns the equivalent price in dollars. Assume an exchange rate of 1€ is 1.16$. For example, after running your program you should be able to type:

>>> euros_to_dollars(13.25)
15.37

Make sure that you are using the return statement and are not printing the answer in your function. In particular, try running the following and make sure you get something printed at the same places (i.e., there should be no output until you manually call print in the interpreter window):

>>> dollars = euros_to_dollars(13.25)
>>> print(dollars)
15.37

Write a function named welcome that doesn’t take any parameters and prints out “welcome” in another language (i.e., doesn’t return a string). For example:

>>> welcome()
Willkommen

Remember that you can create functions with zero parameters. To call a function without any parameters, you still need to put the matching (though empty) parentheses at the end.

Write a function named kilometers_to_miles, that takes a single parameter, the number of kilometers, and returns the equivalent distance in miles. For example, after running your program you could type:

>>> kilometers_to_miles(100)
62.137

Write a function named mpg_from_metric that takes two parameters: (1) the number of kilometers and (2) the number of liters. The function returns the miles per gallon (i.e., miles divided by gallons) by converting the kilometers and liters appropriately. Remember, to have multiple parameters for functions, you separate them with commas in both the function definition and in the function invocation.

>>> mpg_from_metric(400, 30)
31.3619409576589

When you’re done

All your work should be in a single file (using the supplied starter file).

Update the comment at the very beginning of the file indicating the course and assignment number, your name, your section and a brief listing of your creativity features (so that the graders know what to look for).

Each function should have a short comment above it describing what it does. Also include other miscellaneous comments to make your thinking clear. While each function needs a comment, for this first lab you don’t need to create formal Docstring comments.

Submit your program via gradescope. Your program file must be named lab1_functions.py. You can submit multiple times, with only the most recent submission (before the due date) graded. Note that the tests performed by Gradescope are limited. Passing all of the visible tests does not guarantee that your submission correctly satisfies all of the requirements of the assignment.

Grading

Features Points
Section 1 3
Section 2 4
Section 3 4
Section 4 9
Comments and code style 3
Creativity points 2
Total 25