Lab 1: Functions Due: 11:59 PM on 2020-02-18

FAQ

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. Guide: A narrative guide to completing the lab including suggestions, links to relevant documentation, etc.
  3. Specifications: The specific functionality you are expected to implement including suggestions for creativity points.

Background

This lab gives you practice with defining functions, assigning to variables, returning values from functions, and printing.

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, which are comments between pairs of triple-quotes """, e.g.,

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

We use docstrings to document our functions – what they do and what input and output they have.

For reference, here are some simple example functions.

Guide

Warm-up

Start up Thonny as practiced in the prelab (you may need to find it in the Applications folder). From within the Thonny app, open the starter file you downloaded. (Reminder of how to save the starter file)

Right-click on this link for the starter file, select “Save as…”, and save the file as “lab1_functions.py” in a folder you have created for the class. Then open the saved file with Thonny.

You will be compiling a single Python file with multiple function definitions for this assignment. 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.

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 expressions (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. Play around with assigning values to variables. For example, you could assign 22/7 to a variable, e.g., pi = 22/7, and then use your newly-created variable to calculate the area of a circle with radius 10. Note that in the shell you can use the up and down arrow keys to revisit commands you typed previously.

So far, we’ve mostly been interacting with the Python Shell (interpreter). This is useful for doing short computations and trying out Python expressions. But usually we write and save programs, which allows us to write code that we can edit, re-run over time, and save. We write and edit our code in the edit window above the shell.

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

def function_name(parameters):
    """
    Docstring explaining the function, its input and output
    """
    statement1
    statement2
    ...
    return something

Recall that the way that Python can tell what is part of the function is based on the indenting.

Section 1: Functions that return a value

Imagine you’re going on a semester abroad in Europe. To enhance your travels, 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€ = $1.10.

Run your program by clicking the green circle with the white arrow. Note that nothing appears to happen, because we have only defined a function, we haven’t yet called it.

After you’ve run your program, you can interact with the interpreter/shell. For example, you can call your function and see the value returned:

>>> euros_to_dollars(35)
38.5

Write a function named welcome that doesn’t take any parameters and returns a translation of “welcome” in another language. 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. [Note that for help, an appropriate Google query would seek the necessary information but not Python code. E.g., you could search “1 kilometer in miles”.] After running your program an example interaction could be:

>>> kilometers_to_miles(500)
310.6855

Write a function named celsius_to_fahrenheit that takes a single parameter, the temperature in Celsius and returns the equivalent temperature in Fahrenheit. [Note that for help, an appropriate Google query would be something like “celsius to fahrenheit formula” or “formula to go from celsius to fahrenheit”.] After running your program an example interaction could be:

>>> celsius_to_fahrenheit(22)
71.6

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. Here is an example call (your answer should be close to this but may not be exactly the same):

>>> mpg_from_metric(400, 30)
31.358523133333335

You should not have any print statements inside any of the above functions. Rather, these functions return values that can be printed when the function is called. For example, 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(35)
>>> print(dollars)
38.5

Section 2: Functions that print

When you are running a program (rather than interacting with the shell) the intermediate results are not printed. Instead, if you want values to be displayed from the running program, you need to use the print function. You can print any expression; for example, these are all valid lines of code you could have in a program:

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, world!")          # Printing a string

Consider the program statement

print(kilometers_to_miles(500))

This statement has multiple parts. The kilometers_to_miles(500) part invokes or calls a 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.

Write a function four_fours that expresses the values 0 through 9 using four 4s and the operators

+ addition
- subtraction
* multiplication
// integer division
** exponentiation
( ) parentheses for grouping

You can start with this code as a model, and complete it with similar statements for the numbers 1 through 9.

def four_fours():
    """
    Prints an arithmetic expression for each value 0..9 using exactly
    four 4s and the operators +, -, *, //, %, **, and parentheses
    """
    print(4+4-4-4, "is 4+4-4-4")  # 0

In the above code, the mathematical expression 4+4-4-4 gets evaluated to 0 and the value 0 is printed. But the string “is 4+4-4-4” is printed as is since it is enclosed in quotes. Your output should show each value 0 through 9 on its own line, i.e., using the above code as a starting point the output will start like the following:

>>> four_fours()
0 is 4+4-4-4
1 is ...

Write a function convert_from_seconds, that takes in a nonnegative integer number of seconds s and reports the number of days, hours, minutes, and remaining seconds in s seconds. There is no limit on the number of days, but you should be sure that 0 <= hours < 24, 0 <= minutes < 60, and 0 <= seconds < 60.

For instance,

>>> convert_from_seconds(3787)
0 days
1 hours
3 minutes
7 seconds

>>> convert_from_seconds(610)
0 days
0 hours
10 minutes
10 seconds

>>> convert_from_seconds(100000)
1 days
3 hours
46 minutes
40 seconds

You can start with this code as a model, and complete it with statements to compute and print the hours, minutes, and seconds.

def convert_from_seconds(s):
    """
    Input: non-negative integer representing number of seconds
    Prints: number of days, hours, minutes and seconds
    """
    days = s // (24*60*60)  # Number of days
    s = s % (24*60*60)      # The leftover
    # from remaining seconds, compute hours, minutes, seconds

    # report results
    print(days, "days")

Specifications

Your submitted file for this assignment must be named “lab1_functions.py”

At a minimum your submission should have:

Section 1: Functions that return values

Implement the following functions as described in the Guide section:

  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. [2 points]
  2. A function named welcome that doesn’t take any parameters and returns a translation of “welcome” in another language. [1 point]
  3. A function named kilometers_to_miles, that takes a single parameter, the number of kilometers, and returns the equivalent distance in miles. [2 points]
  4. A function named celsius_to_fahrenheit that takes a single parameter, the temperature in Celsius and returns the equivalent temperature in Fahrenheit. [2 points]
  5. 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]

Section 2: Functions that print

Implement the following functions as described in the Guide section:

  1. A function named four_fours that takes no parameters, and prints out the integer values 0 through 9 using four 4s and the operators +, -, *, //, %, **, and parentheses. [5 points]
  2. A function named convert_from_seconds that takes a single parameter, a number of seconds, and prints the number of days, hours, minutes, and seconds that make up that number of seconds. [5 points]

Creativity Suggestions

When you’re done

Update the comment at the very beginning of the file indicating 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 docstring describing what it does. Also include other miscellaneous comments to make your thinking clear.

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 10
Section 2 10
Comments and code style 3
Creativity points 2
Total 25

FAQ Excerpts

Example Lab FAQ

An example FAQ entry for Lab 1. I will often post answers to frequently asked questions from office hours. Check in here if you have a question, there might be an answer already available! For example, in past years I have observed confusion between print and return.