How to build a Fahrenheit to Celsius Converter in Python
In this post, we will learn how to use Python to build a fahrenheit to celsius converter.
Fahrenheit and celsius are two of the most popular ways to measure temperature. However, the conversion between the two is not straightforward.
The formula for converting fahrenheit to celsius is:
BASHcelsius = (fahrenheit - 32) * 5 / 9
To start, let's ask the user for the temperature in fahrenheit. To do this, we will use the input
function, then convert the input to a float so that we can perform arithmetic with it.
PYTHONfahrenheit = float(input("Enter the temperature in Fahrenheit: "))
Now that we have the temperature in fahrenheit, we can convert it to celsius. Let's create a function using the above formula, and call it fahrenheit_to_celsius
.
PYTHONdef fahrenheit_to_celsius(fahrenheit):
return (fahrenheit - 32) * 5 / 9
Call this function and store its return value in a variable called celsius
.
PYTHONcelsius = fahrenheit_to_celsius(fahrenheit)
Now that we have our celsius value, we can print it out to the user.
PYTHONprint(f"{fahrenheit} Fahrenheit is equal to {celsius} Celsius")
Here is the entire fahrenheit to celsius converter:
PYTHONdef fahrenheit_to_celsius(fahrenheit):
return (fahrenheit - 32) * 5 / 9
fahrenheit = float(input("Enter the temperature in Fahrenheit: "))
celsius = fahrenheit_to_celsius(fahrenheit)
print(f"{fahrenheit} Fahrenheit is equal to {celsius} Celsius")
Run this program to try it out for yourself. Here's an example output:
BASHEnter the temperature in Fahrenheit:
50
50.0 Fahrenheit is equal to 10.0 Celsius
- Getting Started with Express
- Create an RSS Reader in Node
- Git Tutorial: Learn how to use Version Control
- How to Serve Static Files with Nginx and Docker
- Getting Started with Deno
- How to deploy an Express app using Docker
- How to deploy a Node app using Docker
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Getting Started with Moment.js
- Learn how to build a Slack Bot using Node.js
- Getting Started with Vuex: Managing State in Vue
- Setting Up a Local Web Server using Node.js