Examples
- Hello World Program in Python (How to Print Hello World in Python?)
- Python Program to Add Two Numbers (Sum/Addition Program)
- How to Generate Random Number in Python? (Program)
- Leap Year Program in Python (Check Leap Year or Not in Python)
- Python Program to Check Number is Positive, Negative, or Zero
- Even Odd Program in Python (How to Check Number is Even or Odd?)
- Python Program to Find Largest of 3 Numbers (Greatest of Three Numbers in Python)
- Prime Number Program in Python (Check Prime or Not)
- Python Program to Find Square Root of a Number (Examples)
- Python Factorial Program (How to Find Factorial of a Number in Python?)
- Python Program to Find Prime Numbers in Range
- Python Program to Find Area of Triangle (Different Ways With Examples)
- How to Solve Quadratic Equation in Python? (Program Examples)
- How to Swap Two Numbers in Python? (Program Examples to Swap Variables)
- Python Program to Convert Kilometers to Miles (km to mi) and Vice Versa
- Python Program to Convert Celsius To Fahrenheit (and Fahrenheit to Celsius)
- Program to Check Armstrong Numbers in Python (Code Examples)
- Program for Armstrong Number Between Two Intervals in Python
- Program to Print Multiplication Table in Python (Code Examples)
- Python Program for Fibonacci Series (Print Fibonacci Sequence in Python)
- Program for Sum of n Natural Numbers in Python (Code Examples)
- Program to Print Powers of 2 in Python (Code Examples)
- Python Program to Find Numbers Divisible by Another Number
- Convert Decimal to Binary, Octal and Hexadecimal in Python (Program with Example)
- How to Convert Decimal to Binary in Python? Program with Examples
- How to Convert Decimal to Octal in Python? Program with Examples
- How to Convert Decimal to Hexadecimal in Python? Program and Examples
- How to Convert Binary to Decimal in Python? Program With Examples
- How to Convert Hexadecimal to Octal in Python? Program With Examples
- Program to Find LCM of Two Numbers in Python (Calculate LCM in Python)
- GCD of Two Numbers in Python (Program to Find HCF or GCD)
- GCD of Three Numbers in Python (HCF Program for n Numbers)
- Simple Calculator Program in Python (Basic Calculator Code)
- Find Factors of a Number in Python (Programs and Examples)
- Program to Find Prime Factors of a Number in Python
- How to Find ASCII Value in Python? ASCII Value of Character
Python Program to Convert Celsius To Fahrenheit (and Fahrenheit to Celsius)
In this post, we will learn the temperature conversion in Python. Whether you're a weather enthusiast, a science student, or an aspiring data analyst, the ability to seamlessly convert Celsius and Fahrenheit in Python is a valuable skill that can enhance your understanding of temperature scales and broaden your data analysis capabilities.
Understanding temperature conversions is not only essential for scientific and meteorological applications, but it also finds relevance in numerous real-life scenarios.
Whether you're planning a vacation abroad, analyzing climate data, working with temperature sensors, or even adjusting cooking temperatures, the ability to seamlessly switch between Celsius and Fahrenheit allows you to communicate and interpret temperature information with ease and precision.
So, we will explore various ways to write a Python program to convert Celcius to Fahrenheit and vice versa. Moreover, we will take a hands-on approach, presenting clear explanations and providing concise code examples.
So, let’s get started and understand centigrade to fahrenheit conversion in Python.
Python Program to Convert Celsius to Fahrenheit
Code
# Temperature conversion program in python
# Function to convert Celsius to Fahrenheit
def celsius_to_fahrenheit(celsius):
fahrenheit = (celsius * 9/5) + 32
return fahrenheit
# Input temperature in Celsius
celsius = float(input("Enter temperature in Celsius: "))
# Convert Celsius to Fahrenheit
fahrenheit = celsius_to_fahrenheit(celsius)
# Display the result
print("Temperature in Fahrenheit:", fahrenheit)
Output
Enter temperature in Celsius: 20
Temperature in Fahrenheit: 68.0
Explanation
-
We define a function called celsius_to_fahrenheit that takes one parameter celsius. This function is responsible for converting Celsius to Fahrenheit.
-
Inside the function, we use the formula (celsius * 9/5) + 32 to perform the conversion. The result is stored in the variable fahrenheit, which is then returned by the function.
-
We prompt the user to enter the temperature in Celsius using the input() function. The entered value is then converted to a floating-point number using float() and stored in the variable celsius.
-
We call the celsius_to_fahrenheit function, passing the value of celsius as an argument. This will calculate the equivalent temperature in Fahrenheit and return it.
-
The returned Fahrenheit temperature is assigned to the variable fahrenheit.
Finally, we use the print() function to show the converted temperature with the message "Temperature in Fahrenheit:" followed by the value of fahrenheit.
Convert Fahrenheit to Celsius in Python
Code
# Program for Fahrenheit to Celsius Conversion in Python
def fahrenheit_to_celsius(fahrenheit):
celsius = (fahrenheit - 32) * 5/9
return celsius
# Example usage
fahrenheit = 100
# Convert Fahrenheit to Celsius using the function
celsius = fahrenheit_to_celsius(fahrenheit)
# Print the converted temperature in Celsius
print(f"{fahrenheit} degrees Fahrenheit is equal to {celsius} degrees Celsius.")
Output
100 degrees Fahrenheit is equal to 37.77777777777778 degrees Celsius.
Explanation
-
In this program, we define a function fahrenheit_to_celsius that takes a temperature in Fahrenheit as input and returns the equivalent temperature in Celsius using the conversion formula (Fahrenheit - 32) * 5/9.
-
To use the function, we call it with the desired temperature in Fahrenheit and assign the result to the variable celsius. The function performs the conversion and returns the result.
-
In the example, we demonstrate how to convert 100 degrees Fahrenheit to Celsius by calling the fahrenheit_to_celsius function and passing the Fahrenheit temperature as an argument. The function calculates the equivalent Celsius temperature and assigns it to the variable celsius.
-
By running this program, it will convert the temperature and display the result.
Celsius Fahrenheit Conversion in Python Using class
Code
# Temperature converter Celsius to Fahrenheit
class TemperatureConverter:
@staticmethod
def celsius_to_fahrenheit(celsius):
return (celsius * 9/5) + 32
@staticmethod
def fahrenheit_to_celsius(fahrenheit):
return (fahrenheit - 32) * 5/9
# Example usage
celsius = 30
fahrenheit = 86
# Convert Celsius to Fahrenheit using the class method
converted_fahrenheit = TemperatureConverter.celsius_to_fahrenheit(celsius)
print(f"{celsius} degrees Celsius is equal to {converted_fahrenheit} degrees Fahrenheit.")
# Convert Fahrenheit to Celsius using the class method
converted_celsius = TemperatureConverter.fahrenheit_to_celsius(fahrenheit)
print(f"{fahrenheit} degrees Fahrenheit is equal to {converted_celsius} degrees Celsius.")
Output
30 degrees Celsius is equal to 86.0 degrees Fahrenheit.
86 degrees Fahrenheit is equal to 30.0 degrees Celsius.
Explanation
-
In this program, we define a TemperatureConverter class with two static methods: celsius_to_fahrenheit and fahrenheit_to_celsius. The celsius_to_fahrenheit method takes a temperature in Celsius as input and returns the equivalent temperature in Fahrenheit using the conversion formula.
-
Similarly, the fahrenheit_to_celsius method takes a temperature in Fahrenheit as input and returns the equivalent temperature in Celsius.
-
To use the class methods, we can directly call them using the class name followed by the method name, without needing to create an instance of the class.
-
In the example, we show how to convert temperatures by calling the class methods with sample values. We convert 30 degrees Celsius to Fahrenheit and 86 degrees Fahrenheit to Celsius using the respective class methods.
-
By running this program, it will convert the temperatures and display the results.
Using a class for temperature conversion encapsulates the conversion logic and provides a reusable and organized approach to handle temperature conversions in Python.
Celsius to Fahrenheit in Python Using Exception Handling
Code
def celsius_to_fahrenheit(celsius):
try:
fahrenheit = (celsius * 9/5) + 32
return fahrenheit
except TypeError:
raise ValueError("Invalid input! Please provide a valid temperature in Celsius.")
# Example usage
celsius = input("Enter the temperature in Celsius: ")
try:
celsius = float(celsius)
fahrenheit = celsius_to_fahrenheit(celsius)
print(f"{celsius} degrees Celsius is equal to {fahrenheit} degrees Fahrenheit.")
except ValueError as e:
print(str(e))
Output
Enter the temperature in Celsius: 20
20.0 degrees Celsius is equal to 68.0 degrees Fahrenheit.
Explanation
-
We define a function celsius_to_fahrenheit that takes a temperature in Celsius as input and returns the equivalent temperature in Fahrenheit using the conversion formula (Celsius * 9/5) + 32.
-
Within the function, we use a try-except block to handle a potential TypeError that may occur if the input is not a valid number. If a TypeError occurs, we raise a ValueError with a custom error message indicating that the input is invalid.
-
In the example, we first take the temperature in Celsius as input from the user. We then attempt to convert the input to a float using float(celsius). If the conversion is successful, we proceed with the temperature conversion by calling the celsius_to_fahrenheit function and printing the result. If a ValueError occurs during the conversion or if the input is not a valid number, we catch the exception and print the error message.
-
By running this program, it will handle invalid input gracefully and display the converted temperature if the input is valid.
Using exception handling allows us to handle potential errors and provide meaningful error messages, ensuring that the program gracefully handles invalid input scenarios.
Practice More Python Programs:
- Hello World Program in Python
- Python Program to Add Two Numbers
- Generate Random Number in Python
- Leap Year Program in Python
- Even Odd Program in Python
- Python Program to Find Largest of 3 Numbers
- Prime Number Program in Python
- Python Program to Find Square Root of a Number
- Python Factorial Program
- Python Program to Find Area of Triangle
- Solve Quadratic Equation in Python
- Swap Two Numbers in Python
- Python Program to Convert Kilometers to Miles
- Check Armstrong Numbers in Python
- Print Multiplication Table in Python
- Python Program for Fibonacci Series
- Convert Decimal to Binary, Octal and Hexadecimal in Python
- Find LCM of Two Numbers in Python
- GCD of Two Numbers in Python
- Simple Calculator Program in Python
- Python Matrix Addition Program
- Transpose of Matrix in Python
- Python Matrix Multiplication
- Python Calendar Program