A car’s miles-per-gallon (MPG) can be calculated with the following formula: MPG = Miles driven / Gallons of gas used Write a Python program that asks the user for the number of miles driven and the gallons of gas used. It should calculate the car’s MPG and display the result with a nice message.
The Correct Answer and Explanation is :
Here’s a Python program that calculates a car’s miles-per-gallon (MPG) based on user input for miles driven and gallons of gas used. After the code, I’ll provide a detailed explanation of how it works.
# Function to calculate MPG
def calculate_mpg(miles, gallons):
if gallons == 0: # Check to avoid division by zero
return "Gallons used cannot be zero."
return miles / gallons
# Main program
def main():
print("Welcome to the MPG Calculator!")
try:
# Get user input for miles driven and gallons of gas used
miles_driven = float(input("Enter the number of miles driven: "))
gallons_used = float(input("Enter the gallons of gas used: "))
# Calculate MPG
mpg = calculate_mpg(miles_driven, gallons_used)
if isinstance(mpg, str): # Check if there was an error message
print(mpg)
else:
# Display the result
print(f"The car's MPG is: {mpg:.2f} miles per gallon.")
except ValueError:
print("Please enter valid numerical values.")
# Run the program
if __name__ == "__main__":
main()
Explanation
- Function Definition: The program starts by defining a function named
calculate_mpgthat takes two parameters:milesandgallons. This function performs the MPG calculation by dividing miles driven by gallons used. It also includes a check to prevent division by zero, returning a relevant message if gallons is zero. - Main Program Flow: The
mainfunction begins by welcoming the user. It then prompts the user to input the miles driven and gallons used. The inputs are converted to floats to allow for decimal values (e.g., 25.5 miles or 3.2 gallons). - Error Handling: A try-except block is used to handle potential errors when converting user input to float. If the input isn’t a valid number, an error message is displayed.
- MPG Calculation: After obtaining the inputs, the program calls the
calculate_mpgfunction and stores the result. If the result is a string (indicating an error), it prints the error message. Otherwise, it formats the MPG result to two decimal places for clarity and displays it in a user-friendly message. - Execution: Finally, the program checks if it’s being run as the main module and executes the
mainfunction, allowing for interaction with the user.
This program effectively demonstrates the basic principles of user input handling, mathematical calculations, and function definitions in Python.