Homework 1
Objectives
- Define functions with parameters and a return value
- Distinguish between functions that return a value and functions that print
- Read and interpret docstrings that describe a function’s parameters and return value
- Translate a word problem into an arithmetic expression
Background
In this assignment you’ll write your first functions in Python: six short functions, split into two groups. The four functions in Part 1 each compute and return a value – you can test them from the Shell just by calling them, since Python automatically shows you the value a function returns. The two functions in Part 2 print their results directly instead.
Don’t mix the two styles. In particular, don’t write return print(...): print itself doesn’t return anything useful, so return print(...) returns None instead of the value you actually computed. If you then tried x = euros_to_dollars(10), x would end up set to None instead of a price.
Part 0: Setup
Click “Download Starter Code” above to open the starter folder; download hw1.py and save it in your cs145/homework directory. Open it from Thonny and add your code in the places specified by the comments. Be sure to delete all comments such as “# YOUR CODE HERE” or “# TODO …” before you turn in your work.
Part 1: Functions that return a value
Each of these functions should compute a result and return it – don’t add a print statement inside any of them.
1. euros_to_dollars
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.16 (the current rate as of when this assignment was written – exchange rates move, so don’t be surprised if a live conversion elsewhere gives you a slightly different number).
def euros_to_dollars(price):
"""
Convert a price in euros to the equivalent price in dollars.
Parameters:
price (float): a price in euros
Returns:
float: the equivalent price in dollars
Example:
>>> euros_to_dollars(30)
34.8
"""2. kilometers_to_miles
Write a function named kilometers_to_miles that takes a single parameter, the number of kilometers, and returns the equivalent distance in miles. (For help, an appropriate Google query would seek the necessary conversion factor, not Python code – e.g., “1 kilometer in miles”.)
def kilometers_to_miles(km):
"""
Convert a distance in kilometers to the equivalent distance in miles.
Parameters:
km (float): a distance in kilometers
Returns:
float: the equivalent distance in miles
Example:
>>> kilometers_to_miles(500)
310.6855
"""3. celsius_to_fahrenheit
Write a function named celsius_to_fahrenheit that takes a single parameter, the temperature in Celsius, and returns the equivalent temperature in Fahrenheit. (For help, an appropriate Google query would be something like “celsius to fahrenheit formula”.)
def celsius_to_fahrenheit(celsius):
"""
Convert a temperature in Celsius to the equivalent temperature in
Fahrenheit.
Parameters:
celsius (float): a temperature in degrees Celsius
Returns:
float: the equivalent temperature in degrees Fahrenheit
Example:
>>> celsius_to_fahrenheit(22)
71.6
"""4. mpg_from_metric
Write a function named mpg_from_metric that takes two parameters – (1) a distance in kilometers and (2) an amount of fuel in liters – and returns the miles per gallon (miles divided by gallons), converting the kilometers and liters appropriately.
def mpg_from_metric(km, liters):
"""
Compute miles per gallon from a distance in kilometers and an amount
of fuel in liters.
Parameters:
km (float): a distance in kilometers
liters (float): an amount of fuel in liters
Returns:
float: the equivalent fuel efficiency in miles per gallon
Example:
>>> mpg_from_metric(400, 30)
31.3619409576589
"""Part 2: Functions that print
Each of these functions should print its result directly – they don’t return anything (notice both docstrings below say Returns: None).
5. four_fours
Write a function four_fours that prints the values 0 through 9, each expressed using exactly four 4s, along with the expression that produced it. Allowed operators are +, -, *, //, %, **, and parentheses.
The starter file already has the first line done for you as a model – complete it with similar statements for 1 through 9:
def four_fours():
"""
Print the values 0 through 9, each expressed using exactly four 4s,
along with the expression that produced it.
Allowed operators are +, -, *, //, %, **, and parentheses.
Parameters: None
Returns:
None
Example:
>>> four_fours()
0 is 4+4-4-4
1 is ...
...
"""
print(4 + 4 - 4 - 4, "is 4+4-4-4") # 0
# YOUR CODE HERE -- add similar print statements for 1 through 96. convert_from_seconds
Write a function convert_from_seconds that takes a single parameter, a non-negative integer number of seconds, and prints the number of days, hours, minutes, and remaining seconds it contains, so that 0 <= hours < 24, 0 <= minutes < 60, and 0 <= seconds < 60.
The starter file already computes days for you as a model – complete it with similar statements for hours, minutes, and seconds:
def convert_from_seconds(seconds):
"""
Print the number of days, hours, minutes, and remaining seconds in a
given number of seconds.
0 <= hours < 24, 0 <= minutes < 60, and 0 <= seconds < 60.
Parameters:
seconds (int): a non-negative number of seconds
Returns:
None
Example:
>>> convert_from_seconds(3787)
0 days
1 hours
3 minutes
7 seconds
"""
days = seconds // (24 * 60 * 60) # Number of days
seconds = seconds % (24 * 60 * 60) # The leftover seconds
# YOUR CODE HERE -- compute hours, minutes, and remaining seconds
print(days, "days")
# YOUR CODE HERE -- print hours, minutes, and secondsSpecification
At a minimum your submission should have:
- A function named
euros_to_dollarswith one parameter, a price in euros, that returns the equivalent price in dollars. - A function named
kilometers_to_mileswith one parameter, a distance in kilometers, that returns the equivalent distance in miles. - A function named
celsius_to_fahrenheitwith one parameter, a temperature in Celsius, that returns the equivalent temperature in Fahrenheit. - A function named
mpg_from_metricwith two parameters, a distance in kilometers and an amount of fuel in liters, that returns the equivalent fuel efficiency in miles per gallon. - A function named
four_fourswith no parameters that prints the values 0 through 9, each expressed using exactly four 4s and the allowed operators, along with the expression that produced it. - A function named
convert_from_secondswith one parameter, a non-negative number of seconds, that prints the equivalent number of days, hours, minutes, and remaining seconds.
Style and Design
- You must add your code to the provided starter file.
- At the top of your file, include a comment with your name (
Author:) and a note on what resources you used (included in starter file). - Docstrings are already provided for every function in the starter file for this assignment – you don’t need to write your own, but do read each one carefully, since it describes exactly what your function should do.
- Follow the Guidelines for Code Quality.
Submitting your work
When you are done, submit hw1.py to Gradescope.
Ensure that the upload succeeds and your submission passes all visible tests. Passing all of the visible tests does not guarantee that your submission correctly satisfies all of the requirements of the assignment. The automatic testing has some trade-offs: you’ll get immediate feedback, but because the process is automated it can be brittle. For the numeric functions in Part 1, answers are checked with a small tolerance for rounding, so you don’t need to match every decimal place exactly – but a result that’s clearly off won’t pass just because it seems “close enough.” We encourage you to submit early and often so you have time to resolve any issues.