Temperature Conversion Application In Python

Last time we talked about using functions in Python, this time let us take it a step farther and create a module. Functions are great and you are going to use them everywhere, but what happens when you need to use a function in more than one place? What happens when a function needs to be utilized in different files within one application? In Python, we create modules, which are just your regular .py files. We can use functions (and objects) from other files by using an import statement. Every language has some form of an import statement. In C we use an include statement. The idea is that when you need, you can include code from another code file. For this post, lets assume a scenario. Imagine that you are an entry level programmer at a software company. You are assign to a team that is working on some large scale scientific application in Python. As the newbie on the team, you are giving the task to write functions that will be used for temperature conversation in multiple parts of the program. You are given the following function pseudocode and are requested to write the code for them:

  1. c2f(t) will take a float temperature in Celsius and return a float temperature in Fahrenheit
  2. c2k(t) will take a float temperature in Celsius and return a float temperature Kelvin
  3. f2c(t) will take a float temperature in Fahrenheit and return a float temperature Celsius
  4. f2k(t) will take a float temperature in Fahrenheit and return a float temperature Kelvin
  5. k2c(t) will take a float temperature in Kelvin and return a float temperature in Celsius
  6. k2f(t) will take a float temperature in Kelvin and return a float temperature in Fahrenheit

So these functions are pretty easy to write, they are all 1 line of code. Using some basic formulas from Wikipedia Conversion of units of temperature the code in Python for temperature conversion might look like this:


def c2f(t):
	return (t*9/5.0)+32

def c2k(t):
	return t+273.15

def f2c(t):
	return (t-32)*5.0/9

def f2k(t):
	return (t+459.67)*5.0/9

def k2c(t):
	return t-273.15

def k2f(t):
	return (t*9/5.0)-459.67

That was simple. Notice that we have included in every calculation an implicate conversion to float, so even if t is not a float, the result will return as a float. That might be useful if at some other part of the application some numeric calculation is required. Especially if the calculation requires higher level of accuracy. Within a couple of minutes you hand your boss (email him/her) a file named temperature.py and you think you are done. In most cases you might be done, but have you tested your code? Rushing code is never a good idea. Take the time to fully test you code and make sure it works the way you think it does. This example might be straight forward, but other examples might be more complicated. It is a good habit to always self test you code. Here is one way you can test the code:


def main():

	menu = “\nTemperature Convertor\n\n"+\
	 	"1. Celsius to Fahrenheit\n"+\
		"2. Celsius to Kelvin\n"+\
		"3. Fahrenheit to Celsius\n"+\
		"4. Fahrenheit to Kelvin\n"+\
		"5. Kelvin to Celsius\n"+\
    		"6. Kelvin to Fahrenheit\n"+\
		"7. Quit"

	user_input = 0
	while user_input != 7:
		print menu
		user_input = raw_input("Please enter a valid selection: ")

		try:
			user_input = int(user_input)
		except:
			print user_input + " is not a valid selection, please try again\n"

		if user_input == 1:
			t = get_user_input()
			print str(t) + " degree Celsius is " + str((c2f(t))) + " degree Fahrenheit"
		elif user_input == 2:
			t = get_user_input()
			print str(t) + " degree Celsius is " + str((c2k(t))) + " degree Kelvin"
		elif user_input == 3:
			t = get_user_input()
			print str(t) + " degree Fahrenheit is " + str((f2c(t))) + " degree Celsius"
		elif user_input == 4:
			t = get_user_input()
			print str(t) + " degree Fahrenheit is " + str((f2K(t))) + " degree Kelvin"
		elif user_input == 5:
			t = get_user_input()
			print str(t) + " degree Kelvin is " + str((k2c(t))) + " degree Celsius"
		elif user_input == 6:
			t = get_user_input()
			print str(t) + " degree Kelvin is " + str((k2f(t))) + " degree Fahrenheit"
		elif user_input == 7:
			quit()
		else:
			print str(user_input) + " is not a valid selection, please try again\n"

if __name__ == "__main__":
	main()

The output of the code might look like this: wpid-python_tempeature_converstion-2014-01-2-19-29.png Now this main() function is in a different file called converter.py. The file content has now functions that can convert anything. However, in the very top of the file there is one magical statement:


from temperature import *

There are different ways to include code from another .py file, but for now, we can use this one. All it is is a small indication for Python to know that if they need to open a temperature.py file as well as the converter.py file. The only requirement is that both files are in the same working directory, that is that they are in the same folder. When you examine the code you may notice that some code was added to account for invalid entries, such as if a user enters a character instead of a number. There is also a hidden function called get_user_input() that looks like this:


def get_user_input():

	user_input = 0
	while type(user_input) != type(1.0):
		user_input = raw_input("Enter degrees to convert: ")
		try:
			user_input = float(user_input)
		except:
			print user_input + " is not a valid entry"
	return user_input

This function makes sure the user enters a numeric value to convert. At this point you have all the tools necessary to tell you boss that you have tested you code and it works properly. You might also want to keep this as part of the code in case you want to use it in the future. I have uploaded the code in case you want to test it out for yourself, Temperature Conversation Application in Python.

If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.
  • Pingback: Captain DeadBones” Chronicles: Temperature Conversation Application in Python | The Black Velvet Room()

  • Brutus

    I thought * imports like `from temperature import *` are considered very bad coding practice?

    • CptDeadBones

      Thanks for the comment! You are correct. Using "from import ..." is very bad coding. One should always try to use "import" instead. However, one should learn different styles of coding as well. Everything is a tool, it is only a matter of how and when to use some "features". You will find that in most cases "import" will be sufficent. But every now and then you will get a crazy odd code that works better with "from import ...". I did mention about 2/3 of the way into the post that there are other ways to do this.
      Good Catch!

      • Julian

        I think you have misunderstood Brutus's objection.

        This line:

        from temperature import c2f

        is fine. It explicitly adds c2f to the namespace. Anyone looking at the code will know where c2f came from.

        However, the line:

        from temperature import *

        is generally deprecated (see PEP8). It "pollutes" your namespace by inserting an unknown set of identifiers than might override other identifiers already in your namespace, and that might change if the temperature module ever changes.

        • CptDeadBones

          That is another good point. I did not even think about that. I guess it would be valid code.