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:
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 including and after a #
) 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, what inputs the expect and what outputs they produce.
For reference, here are some simple example functions from lecture.
Start up Thonny as practiced in the prelab (you may need to find it in the Applications folder). Download the linked starter file into a directory you have created for the course. 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 and update the comment at the top with your name and section.
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 (many 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 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. 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 editor 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
Args:
parameters: Describe the function arguments
Returns:
Describe the return value (if the function returns a value)
"""
statement1
statement2
...
return something
Recall that the way that Python can tell what is part of the function is based on the indenting.
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 also as a float
. Assume that 1€ is worth $1.21.
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)
42.35
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(35)
>>> print(dollars)
42.35
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 (like shown above).
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 would be “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.358472666666668
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. If you are not sure if you are returning values, try assigning the function call expression to an variable like shown above. There should be no output until you manually call print in the interpreter window
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//
floor (integer) division**
exponentiation()
parentheses for groupingStart with this code as a model, and complete it with similar statements for the numbers 1 through 9.
def four_fours():
"""
Express the values 0..9 using exactly four 4s.
Allowed operators are +, -, *, //, %, **, and parentheses.
Returns:
None
"""
print(4+4-4-4, "is 4+4-4-4") # 0
# FILL THIS IN with similar expressions for 1 through 9
In the above code, the mathematical expression 4+4-4-4
gets evaluated to the integer 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 integer value 0 through 9 on its own line, along with the expression that produced the value; 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 ...
Your output must match the formatting above exactly, i.e. a space on either side of “is” and no spaces in the expression.
Write a function convert_from_seconds
, which takes in a nonnegative integer number of seconds seconds
and reports the number of days, hours, minutes, and remaining seconds in seconds
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(seconds):
"""
Print number of days, hours, minutes, and seconds in a given number of seconds.
Args:
seconds: non-negative integer representing number of seconds
Returns:
None
"""
days = seconds // (24 * 60 * 60) # Number of days
leftover_seconds = seconds % (24 * 60 * 60) # The leftover seconds
# FILL THIS IN to compute hours and minutes
print(days, "days")
# FILL THIS IN to print number of hours, minutes, seconds like shown above
Your submitted file for this assignment must be named “lab1_functions.py”. At a minimum your submission should have:
Implement the following functions as described in the Guide section:
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 as a float
.welcome
that doesn’t take any parameters and returns
“welcome” as a string in another language.kilometers_to_miles
, that takes a single parameter, the
number of kilometers, and returns the equivalent distance in miles as a float
.celsius_to_fahrenheit
that takes a single parameter, the
temperature in Celsius and returns the equivalent temperature in Fahrenheit as a float
.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) as a float
by converting the kilometers and
liters appropriately.Implement the following functions as described in the Guide section:
four_fours
that takes no parameters, and prints out the integer values 0 through 9 using four 4s and the operators +, -, *, //, %, **, and parentheses. Each line should show both the integer value and the corresponding mathematical expression using a print statement such as print(4+4-4-4, "is 4+4-4-4")
.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.mpg_from_metric
function is to utilize the
other functions you write that do some of the work for you i.e. DRY it up. To
calculate the mpg, write an additional function liters_to_gallons
and then
use this function and your kilometers_to_miles
function to implement the
mpg_from_metric
function [0.5-1 point].dollars_to_euros
function that converts dollars using your
euros_to_dollars
function instead of explicitly incorporating the exchange
rate [0.5-1 point].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.
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 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. Check out this guide to submitting programming assignments to Gradescope.
Features | Points |
---|---|
Section 1 | 10 |
Section 2 | 10 |
Code design and style | 5 |
Creativity points | 2 |
Total | 27 |
The return
in return print(...)
does nothing and will only confuse someone reading your code.
A common problem is failing a test with a result just outside the error
tolerance specified in the test (e.g. for mpg_from_metric
). Generally the
temperature conversion has an error tolerance of 0.1 and the distance/volume
functions have a tolerance of 0.01. If you find yourself with this kind of
failure, try making your conversion factors more precise. Don’t leave those
tests as failing because the results seem “close enough”. Your program should
pass all of the tests.
Fortunately you shouldn’t need to sign up for Gradescope as I pre-populated the course roster (although you will need to create a password, etc. the first time you login). Apparently many of the Gradescope e-mails seem to be ending up in the junk mail folder, so check there first. Alternately you can choose the “Forgot my password” link on the login page to resend the e-mail to set your password (and log in the first time).