Question
Lets say you get an assignment to develop a temperature converter application (as you may have done already in a previous assignment). You may want
Lets 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. Whats 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: Dont 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.
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started