In this challenge we will write a set of functions to calculate how many Bytes there are in a given number of kilobytes, megabytes, gigabytes, terabytes or petabytes.
First let’s investigate the link between these storage units:
A Byte can be used to store an integer between 0 and 255, or a single character (using the ASCII code).
A text file is often measured in Kilobytes as it would contain a few thousand characters.
= 1024 x 1024 Bytes
A digital photograph or an mp3 would typically take up a few megabytes of disk space.
= 1024 x 1024 KB
= 1024 x 1024 x 1024 Bytes
A high quality movie (DVD) would take up a few gigabytes. An SD card or USB key would contain a few GB of data.
= 1024 x 1024 MB
= 1024 x 1024 x 1024 KB
= 1024 x 1024 x 1024 x 1024 Bytes
A hard drive can contain a few Terabytes of data.
= 1024 x 1024 GB
= 1024 x 1024 x 1024 MB
= 1024 x 1024 x 1024 x 1024 KB
= 1024 x 1024 x 1024 x 1024 x 1024 Bytes
Very large databases stored on web servers used by large websites (Google, Facebook, etc…) will contain a few Petabytes of data.
Subroutines?
By completing this challenge we will investigate how subroutines (functions/procedures) are used in Python to create sections of code that can be called/reused many times within a program. Subroutines mean that a section of code can be identified using a name (identifier). This enables us to add more instructions to the already existing functions used in Python such as print or input.
To create a new function in Python we have to declare it first using the keyword def in Python. Our first function will be called kilobytes_to_bytes() and will take one parameter: numberOfKilobytes: (integer value).
def kilobytes_to_bytes(numberOfKilobytes):
We will then add the code to calculate the number of bytes that this function should return:
def kilobytes_to_bytes(numberOfKilobytes): bytes = 1024 * numberOfKilobytes return bytes
Note how the code for the subroutine/function is indented to the right.
We will then be able to call our the kilobytes_to_bytes() function to perform any conversion. T
numberOfBytes = kilobytes_to_bytes(5)
Check the Python code below where we have implemented and used the kilobytes_to_bytes() function to convert a user input into bytes.
Your task consists of creating another set of functions as follows:
- megabytes_to_bytes()
- gigabytes_to_bytes()
- terabytes_to_bytes()
- petabytes_to_bytes()
Extension Task
Create a new Python program that will:
- Ask the user how old they are (age in years),
- Convert this number in days knowing that there are 365.25 days in a year,
- Output this number of days to the end-user.
Add more code to your program to calculate:
- How old is the user in days,
- How old is the user in hours,
- How old is the user in minutes,
- How old is the user in seconds.
Solution...
The solution for this challenge is available to full members!Find out how to become a member:
➤ Members' Area