Python Program to Convert Miles to Kilometers

Python Program to Convert Miles to Kilometers

Welcome to our guide on a Python program to convert miles to kilometers.

In this tutorial, we’ll explore how to write a simple Python script that takes a distance in miles as input and converts it to kilometers.

Throughout this tutorial, we will explain the code step by step, making it accessible for beginners to follow along.

Introduction

Python Program to Convert Miles to Kilometers

Converting miles to kilometers is a common task in many applications, especially in fields such as transportation, fitness tracking, and geography.

While the conversion formula itself is straightforward, automating the process with Python can save time and reduce errors.

Understanding the Conversion Formula

Before we dive into writing the Python program, let’s first understand the conversion formula between miles and kilometers:

1 mile = 1.60934 kilometers

This formula forms the basis of our Python program.

We’ll take user input in miles and use this formula to convert it to kilometers.

Python Program to Convert Miles to Kilometers

Let’s start by writing the Python script. We’ll take user input for miles, perform the conversion, and then display the result.

# Python Program to Convert Miles to Kilometers

# Function to convert miles to kilometers
def miles_to_kilometers(miles):
    # Conversion factor
    conversion_factor = 1.60934
    # Convert miles to kilometers
    kilometers = miles * conversion_factor
    return kilometers

# Main function
def main():
    # User input for miles
    miles = float(input("Enter distance in miles: "))
    # Convert miles to kilometers using the function
    kilometers = miles_to_kilometers(miles)
    # Display the result
    print(f"{miles} miles is equal to {kilometers} kilometers.")

# Call the main function
main()

In this script:

  • We define a function miles_to_kilometers(miles) that takes the number of miles as input and returns the equivalent distance in kilometers.
  • Inside the main() function, we take user input for miles using the input() function.
  • We then call the miles_to_kilometers() function with the user-input miles and store the result in the variable kilometers.
  • Finally, we display the result using print().

Testing the Python Program to Convert Miles to Kilometers

Let’s test our Python program with some example inputs:

Example 1:

Input

Enter distance in miles: 50

Output

50.0 miles is equal to 80.467 kilometers.

Example 2:

Input

Enter distance in miles: 100

Output

100.0 miles is equal to 160.934 kilometers.

Handling Errors

Error Handling in Python Program to Convert Miles to Kilometers

Our program currently assumes that the user will enter a valid numerical value for miles.

However, if the user enters a non-numeric value or leaves the input blank, the program will raise a ValueError exception.

We can handle this situation by adding error handling to our code.

# Main function
def main():
    try:
        # User input for miles
        miles = float(input("Enter distance in miles: "))
        # Convert miles to kilometers using the function
        kilometers = miles_to_kilometers(miles)
        # Display the result
        print(f"{miles} miles is equal to {kilometers} kilometers.")
    except ValueError:
        print("Invalid input. Please enter a valid number for miles.")

# Call the main function
main()

In this modified version of our main() function, we use a try-except block to catch any ValueError that may occur when converting the user input to a float.

If a ValueError occurs, we print a friendly error message prompting the user to enter a valid number.

Summing Up: Python Program to Convert Miles to Kilometers

In this tutorial, we’ve explored how to write a Python program to convert miles to kilometers.

We began by understanding the conversion formula and then proceeded to write the Python script step by step.

We’ve covered error handling to make our program more robust and user-friendly.

You can now easily convert distances from miles to kilometers using our simple Python script.

Feel free to experiment with the program, and don’t hesitate to leave a comment if you have any questions or suggestions for improvement!

Access our full programs library here.

Happy coding!


Discover more from Python Mania

Subscribe to get the latest posts sent to your email.

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

Related Articles:

Recent Articles:

0
Would love your thoughts, please comment.x
()
x

Discover more from Python Mania

Subscribe now to keep reading and get access to the full archive.

Continue reading