Answers: Functions#
Provided here are answers to the practice questions at the end of “Functions”.
Function Execution#
Function Execution Q1#
tempA = convert_temp(95)
tempB = convert_temp(17, 'C')
Function Execution Q2#
comp_a = compare_to_threshold(250)
comp_b = compare_to_threshold(42, 42)
comp_c = compare_to_threshold(value=3, threshold=7)
User-Designed Functions#
UDFs Q1#
# there are multiple approaches to string concatenation
def provide_info(name, year, school='UCSD'):
output = "Hi! I'm " + name + '. I am a ' + year + ' at ' + school + '.'
return output
UDFs Q2#
# there are multiple approaches that work
def change_username(username):
if len(username) > 4 and username.isalnum() and 'cogs' not in username:
return False
else:
return True
UDFs Q3#
def exclaim(str_a, str_b):
result = str_a + ' ' + str_b + '!'
return result
exclaim('Happy', 'Friday')
UDFs Q4#
def return_bigger(num1, num2):
if num1 > num2:
return num1
elif num2 > num1:
return num2
elif num2 == num1:
return num1
UDFs Q5#
# wording of the returned messages may vary
def buy_or_save(round_1, round_2):
if round_1 == 'W' and round_2 == 'W':
return 'The team should save!'
elif round_1 == 'L' and round_2 == 'L':
return 'The team should buy!'
else:
return 'The team should half-buy!'
UDFs Q6#
def matcha(color, texture):
if color == "vibrant green" and texture == "fine":
return "This is ceremonial-grade matcha!" # wording may vary
elif color == "dull green" and texture == "fine":
return "This is high-grade matcha!" # wording may vary
else:
return "This is low-grade matcha!" # wording may vary
UDFs Q7#
# note: the type check must come first;
# otherwise comparing a string to 0 would raise a TypeError
def phone_time(screen_time):
if type(screen_time) == str or screen_time < 0:
return 'Invalid input' # message may vary
elif screen_time < 3:
return 'Good job keeping your screen time low!' # message may vary
elif screen_time >= 4:
return 'Time to take a break from your phone!' # message may vary
UDFs Q8#
def tip_calculator(bill, service='good'):
if service == 'great':
tip = bill * 20 / 100
elif service == 'good':
tip = bill * 15 / 100
else:
tip = bill * 10 / 100
return tip
UDFs Q9#
def weekend_check(day):
if day == 'Saturday' or day == 'Sunday':
return True
else:
return False
Debugging#
Debugging Q1#
def growth_rate(this_year, last_year):
return ((this_year - last_year)/last_year) * 100
Debugging Q2#
# three fixes were needed: a colon at the end of the def statement,
# the indentation of the kelvin line,
# and parentheses around (temp_f - 32) so the subtraction happens first
def fahrenheit_to_kelvin(temp_f):
temp_c = (temp_f - 32) * 5/9
kelvin = temp_c + 273.15
return kelvin
Debugging Q3#
def safe_convert(value):
try:
output = int(value)
except (ValueError, TypeError):
output = None
return output