Python Program Convert Gallons To Litres Using Function

By | October 23, 2023

Python Program Convert Gallons To Litres – To convert gallons to liters in Python, you can use the following simple program. The conversion factor is 1 US gallon = 3.78541 liters.

Python Program Convert Gallons To Litres Using Function

Python Program Convert Gallons To Litres Using Function

This program defines a function gallons_to_liters that takes the number of gallons as input and returns the equivalent amount in liters. It then takes user input for the number of gallons, converts it to liters using the function, and displays the result.


# Function to convert gallons to liters
def gallons_to_liters(gallons):
    liters = gallons * 3.78541
    return liters

# Input from the user
gallons = float(input("Enter the number of gallons: "))

# Perform the conversion
liters = gallons_to_liters(gallons)

# Display the result
print(f"{gallons} gallons is equal to {liters} liters.")

Let me explain the Python program in more detail:

  1. We start by defining a function gallons_to_liters that takes the number of gallons as its parameter and returns the equivalent volume in liters. It does this by multiplying the number of gallons by the conversion factor, which is 3.78541. This factor represents the number of liters in one US gallon.
  2. We then prompt the user to input the number of gallons they want to convert to liters. The input function is used for this purpose. The input is accepted as a string, so we convert it to a floating-point number using float() so that we can perform mathematical operations with it.
  3. Next, we call the gallons_to_liters function, passing the user’s input as an argument. The result is stored in the variable liters.
  4. Finally, we display the result to the user using the print function. The program prints a message that includes the original number of gallons entered by the user and the equivalent amount in liters, which is calculated using the gallons_to_liters function.

For example, if the user enters 5 gallons, the program will calculate and print: “5.0 gallons is equal to 18.92705 liters.”

Here’s the formula to convert gallons to liters:

Liters = Gallons × 3.78541

Where:

  • Liters is the equivalent volume in liters.
  • Gallons is the volume in gallons you want to convert.
  • 3.78541 is the conversion factor, representing the number of liters in one US gallon.

You can use this formula in your Python program to perform the conversion

This is how the program works to convert gallons to liters in Python.

Loading

Leave a Reply

Your email address will not be published. Required fields are marked *