Exercise 2 - Short failing examples - SOLVED
Contents
Exercise 2 - Short failing examples - SOLVED#
Here we give a series of short functions that are failing for a variety of reasons. Please look over each of these in turn, and try to identify and fix the problem.
Exercise 2A - Nothing being printed??#
In this code we have written a function to take two inputs a and b and compute (a + b) / (a - b + 0.01)**2. However, when we try to use it nothing is printed. Please fix this!
def some_expression(a, b):
output = (a + b)/(a - b + 0.01)**2
return output
my_fav_a = 6
my_least_fav_b = 3
print(some_expression(my_fav_a, my_least_fav_b))
0.9933665191333431
Exercise 2B - TypeError??#
We have written a function to concatenate two strings. We then provide two strings, but the code says TypeError. Please make it add my strings together!!
def string_contatenator(string1, string2):
output = string1 + string2
return output
string1 = "I think I'm ok"
string2 = "I feel trapped"
print(string_contatenator(string1, string2))
I think I'm okI feel trapped
Exercise 2C - Assignment and logical equality#
Here is a function for determining whether you have a good amount of flour, sugar and eggs to make a cake. Except it doesn’t work. Please fix it!
def baking_cake(amount_flour, sugar_spoons, num_eggs):
if amount_flour == 5:
return f"Are you sure that you want to use {amount_flout} kg of flour to bake a cake?"
elif amount_flour < 0.25 and sugar_spoons == 20:
return f"This is going to be very sugary"
else:
return f"This looks good for making a cake, but maybe check with Mary Berry."
amount_flour = 4
sugar_spoons = 5
num_eggs = 2
print(baking_cake(amount_flour, sugar_spoons, num_eggs))
This looks good for making a cake, but maybe check with Mary Berry.
Exercise 2D - N factorial always equals 1??#
We wish to calculate a factorial of \(n\), in maths we often denote this as \(n!\) it is defined as $\( n! = 1 \cdot 2 \cdot 3 \cdot 4 \cdot \cdots \cdot n\)$
We have written a code to do this …. except whatever we give it as input it always returns 1. Please fix my code!
def my_func(n):
total = 1.0
for k in range(1, n+1):
total *= k
return total
print(my_func(3), my_func(5), my_func(7))
6.0 120.0 5040.0
Exercise 2E - List is not callable??#
We have a function that takes a list and returns the last 2 elements as a new list. Except it fails with the strange error seen below. Please fix!
def last_but_one_and_last(my_list):
if len(my_list)>=2:
output = [my_list[-2], my_list[-1]]
return output
my_list = [1, 2, 3, 4]
print(last_but_one_and_last(my_list))
[3, 4]
Exercise 2F - Function just gives the wrong output??#
After being upset that none of my 5 short code snippets above worked, I tried to reassure myself by coding something quick. A function that takes one input and returns the number squared. However, the function just seems to return random numbers? HEEEELLLPPP!!!!
def my_fonc(my_fav_n):
return my_fav_a**2
print(my_fonc(2))
36