7. Functions, Modules and Libraries#
Exercise 7.1.#
Write a function which can convert a given temperature in degrees Celcius into the equivalent in Fahrenheit. Use the following formula: F = 1.8 * C + 32.
Once the function is ready, test it with a number of values. 20 degrees Celcius ought to be converted into 68 degrees Fahrenheit, and 37 degrees Celcius should equal 98.6 degrees Fahrenheit.
def celcius_to_fahrenheit( celcius ):
fahrenheit = 1.8 * celcius + 32
return round( fahrenheit , 1 )
print(celcius_to_fahrenheit(20))
print(celcius_to_fahrenheit(37))
Exercise 7.2.#
Write a function which can test whether a given number is in between 10 and 20. The function should return True
if this is the case, and False
otherwise. The function should also return False
is equal to 10 or to 20.
def between_10_and_20(number):
if number>10 and number<20:
return True
else:
return False
print(between_10_and_20(8))
print(between_10_and_20(14))
print(between_10_and_20(29))
print(between_10_and_20(20))
Exercise 7.3.#
In a given university course, the final grade is determined by grade for essay and by the grade for a presentation. The presentation counts for 30% and the essay for 70%.
Write two functions:
calculate_mark
should calculate the final grade based on a set of partial grades according to the given formula. Grades must be rounded to integers. 5.4, for example, becomes 5 and 6.6 becomes 7.pass_or_fail
should determine whether a given grade is at a pass level (i.e. equal to or higher than 6). This function must return a string value, ‘Pass’ or ‘Fail’.
def calculate_mark( essay, presentation ):
partial1 = essay * 0.7
partial2 = presentation * 0.3
final = partial1 + partial2
return round(final)
def pass_or_fail(grade):
result = 'Fail'
if grade >= 6:
result = 'Pass'
return result
essay1 = 7.0
presentation1 = 8.5
final1 = calculate_mark(essay1, presentation1)
print( "final grade: {} ({})".format( final1 , pass_or_fail(final1) ) )
essay2 = 4.5
presentation2 = 5.5
final2 = calculate_mark(essay2, presentation2)
print( "final grade: {} ({})".format( final2 , pass_or_fail(final2) ) )
Exercise 7.4.#
Write a function which takes a Python list as a parameter. This list should contain numbers. The function should return the average value of the numbers in the list. Name the function calculate_average()
. in the definition of this function, add an optional parameter which specifies the number of digits that are returned after the digit. The default value must be 1.
To calculate the sum of all the numbers in a list, you can work with the sum()
function.
numbers = [6,67,8,33,24,11,34,6,23,4,19,6,9,12,134,45,23]
def calculate_average(numbers, nr_digits=1):
average = sum(numbers)/len(numbers)
return round(average, nr_digits)
print(calculate_average(numbers,4))
Exercise 7.5.#
Import the math library, as follows:
from math import *
This command simply imports all the available functions from the math library. Use the functions log10()
, pow()
, sqrt()
and cos()
to generate the following numbers:
The base-10 logarithm of 5.
3 raised to the power of 4
The square root of 144
The cosine of 60 radians.
from math import *
print( str( log10(20) ) )
print( str( pow( 3 , 4 ) ) )
print( str( sqrt( 144 ) ) )
print( str( cos( 60 ) ) )
Exercise 7.6.#
Following Pythagoras’ theorem (A2 + B2 = C2), calculate the length of the hypothenuse in a right trangle in which the other two sides have a length of 6 and 7. Make use of the math module.
from math import *
A = 6
B = 7
C2 = pow( 6 , 2 ) + pow( 7 , 2 )
C = sqrt( C2 )
print(C)
Exercise 7.7.#
The random
module can be used to make random numbers, or to select items from a list randomly.
Using the
randrange()
method, write code to create a dice rolling application. In other words, write code which can generate a random number in between 1 and 6.Secondly, work with the
choice()
method from random to select a random number from the list namedgame
.
from random import randrange, choice
game = ['rock','paper','scissors']
print(randrange(1,6))
print(choice(game))
5
paper
Exercise 7.8.#
Instead of saving dates simply as strings, you can also save them as datetime
objects. This can be done using the datetime
module. Saving dates as datetime
objects can be very helpful when you want to perform calculations on dates. For this exercise, calculate the number of days that have passed since January 1 2022. Follow the steps below.
datetime
is a module. Within this module, there is also a class nameddate
. Start by importing the datetime class from the datetime module.Define ‘January 1 2022’ as a
datetime
. You can do this using the constructor method ofdatetime
. This method demands three parameters: the year, the month and the date. These three numbers should all be integers. Assign the date to a variable namedolder_date
Find the current date. The
datetime
class indatetime
contains a method calledtoday()
that you can use for this purpose. Assign today’s date to a variable namednow
.Subtract
older_date
fromnow
. Append the propertydays
to the result to see only the number of days.
from datetime import date
older_date = date(2022,1,1)
now = date.today()
nr_days = (now-older_date)
print(nr_days.days)
1004