I need help with writing a program that asks the user to enter distance in kilometers and then converts distance to miles

Dani AI

Generated

A tiny plan to get unstuck: write the steps in plain English (as suggested), read a single value from the user, convert that string to a numeric type, do the multiplication, and print a nicely formatted result. was right to flag that input comes in as text — that means you should parse and validate it instead of assuming an integer.

Common pitfalls to avoid: use float if you want decimal kilometers (don’t force int unless you want whole numbers), catch ValueError on bad input, and reject negative distances if that makes sense for your app. ’s 1.6 is fine for a quick mental estimate, but prefer the precise conversion mentioned earlier when you do the math.

A compact, cross-version example that validates input, rejects negatives, and formats the output:

try:
    input = raw_input
except NameError:
    pass

KM_TO_MILES = 0.621371192

def km_to_miles(km):
    return km * KM_TO_MILES

def main():
    s = input("Distance in kilometers: ")
    try:
        km = float(s)
    except ValueError:
        print("Please enter a numeric value.")
        return
    if km < 0:
        print("Distance cannot be negative.")
        return
    miles = km_to_miles(km)
    print("{:.3f} km = {:.3f} miles".format(km, miles))

if __name__ == "__main__":
    main()

Quick extra tips: wrap conversion logic in a function (easy to unit-test), try inputs like 0, 0.5, and very large values while testing, and use a units library (e.g., pint) if you need many different unit conversions or higher-precision handling.

Recommended Answers

All 8 Replies

What have you got so far?

As far as asking the user for input use either raw_input or input depending on your version of Python. Then the conversion is simple math. Just google "1 kilometer to miles" and it will give you the conversion rate.

i'm just starting out with this problem so i really don't know where to start

Not much help to give you without solving it.
Look a little on this.

>>> km = raw_input('How many km? ')
How many km? 100
>>> km
'100'
>>> #As you see km is now a string
>>> type(km)
<type 'str'>
>>> #make intreger
>>> int(km)
100
>>> #100 * ??? what mystery number give miles?

For python 2.x use always raw_input(and convert to what you need)
Python 3.x has only input same as raw_input(it return a string too)

As little as I can remember 1 mile is about 1.6 km, so 1 km is 1/1.6 miles.

As little as I can remember 1 mile is about 1.6 km, so 1 km is 1/1.6 miles.

According to the Google:

1 kilometer = 0.621371192 miles

Whenever I start a script I usually write out in plain English what I want to do. It will keep you organized and you will never not know "where to start." Comment out the plain english, and script around it.

For example, here is the "skeleton" for a script to get the statistics of every major league baseball player:

#query MLB database
#parse results
#display results

Now, this script would obviously be tediously complicated and long, boring, etc... But, I know know where to start. I first need to query the MLB database. I may want to do a sub-skeleton here, because qerying a database has several different steps, so I might have to do some googling on querying a database using python. But, I know what I'm doing, and I've split my code into 3 parts. Yay me.

So let's see a skeleton for your script, and then we'll give you some tips. :)

Here are some more example skeletons:

Process a restaurant bill

#get all the items ordered
#get the total price
#add tax
#add gratuity if there are more than 6 people
#print the bill

rename all files in a directory

#get a list of all the files in the directory
#loop through the files, renaming them
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.