Let’s say you get an assignment to develop a temperature converter application (as you may have done already in a previous assignment). You may want to convert temperatures from one unit of measurement to multiple others. A basic script, called `kelvin_to_celsius.py`, could only be used to do that one task. But what if we wanted to extend this script, call it `temperature_converter.py`, and use it to also convert Kelvin to Fahrenheit (following the formula `F = (K − 273.15) * 9/5 + 32`)? And what if these two features should be able to run independently of each other?
For that we need to create functions in Python. Up until now, all the code you wrote would run in order when running your script. Functions are blocks of code in Python that are only run if they are explicitly called. What’s more, functions can have parameters (data to pass to a function, input) and can return data (output) as a result of that.
Functions are the perfect solution for this task. They will allow you to create two blocks of code that you can call separately: one function called `kelvin_to_celsius(temperature)` and another function called `kelvin_to_fahrenheit(temperature)`. Both of these functions have a parameter (or input data) called `temperature`. The code in the function should convert this temperature and the function should then return this result. Now, a user can call these functions separately, depending on which conversion they need!
Not only are functions a perfect solution for this assignment, they are an essential part of almost all Python programs. Functions help break scripts into smaller and modular blocks, allowing you to reuse code (programmers call this DRY: Don’t Repeat Yourself). Especially when your Python projects grow, functions will help to keep them manageable and organized.
For your new program, called `temperature_converter.py`, you will implement these two functions in Python and ask the user for input. You ask for the user input in an if `__name__ == "__main__":` block on the bottom of your script where you will check if the input is a number and then print the results (first Celsius, then Fahrenheit) of both functions.
-!- CODE language-bash -!-$ python3 temperature_converter.py
Temperature in Kelvin: 0
-273.15
-459.66999999999996
$ python3 temperature_converter.py
Temperature in Kelvin: 500
226.85000000000002
440.33000000000004
$ python3 temperature_converter.py
Temperature in Kelvin: word
Please input a digit.
CodeGrade is your virtual teaching assistant for your coding classroom. You teach, CodeGrade takes care of the rest.
With our 40+ built-in fully automatically graded Introduction to Python assignments for university-level courses, you can start teaching Python at your institution with confidence now. Or, scale your classroom with CodeGrade's tools.
Book a personal 30-minute demo now and we'll show you how to get started with CodeGrade in less than 1 hour!