2-13-2021
Today, we will be creating a Python program which can convert temperatures from Celsius to Fahrenheit and vice versa. This going to use all the fundamental ideas which we have learned about previously. Let's begin!
The first step of this program is getting some user input. We will need to ask two things of the user: what unit they would like to convert to, and the temperature they are converting. Here we will do that:
unit=input("What unit would you like to convert to?(C or F)\n")
value=input("Please enter the temperature you are converting\n")
This will now store those values for us into their appropriate variables. We will now use them in an if-else statement to perform the correct operation. Here is how we can do that:
if unit=="F":
result=((float(value)*9)/5)+32
print("Temperature in Fahrenheit is: "+result)
elif unit=="C":
result=((float(value)-32)*5)/9
print("Temperature in Celsius is: "+result)
else:
print("Invalid input")
Here, we are using an if else statement to perform the correct operation on the value variable. Something to notice is that we need to use float() around our value variable. This is because by default, values read in by input() are made strings. In order to perform mathematical operations on this number, we need to convert it to a decimal with float().
And that's our program. Here's the full code:
unit=input("What unit would you like to convert to?(C or F)\n")
value=input("Please enter the temperature you are converting\n")
if unit=="F":
result=((float(value)*9)/5)+32
print("Temperature in Fahrenheit is: "+result)
elif unit=="C":
result=((float(value)-32)*5)/9
print("Temperature in Celsius is: "+result)
else:
print("Invalid input")
Hopefully this little program gives you more ideas as to how you can use Python on your own! Creating any small project is key in learning programming, so try to make something! We will continue on with learning more complex topics which will lead to even more complex programs!