Varun Shetty
Varun Shetty

Reputation: 419

Error converting miles to kilometers

I'm trying to learn python and am attempting to create a simple formula that converts miles to kilometers and returns some text with the conversion.

Here's what I have:

def mile(x):
    z = x * 1.609344
    print "%.2f" % z

x = float(raw_input("How many miles are you traveling? "))  

z = mile(x)

print "That's about % kilometers." % z

Can someone explain why this doesn't work? I could definitely set up the mile function to print a sentence with the conversion, but I didn't want to do that.

Upvotes: 2

Views: 2917

Answers (3)

Levon
Levon

Reputation: 143122

As way of an explanation:

You need to return the value of your computation/conversion from the function so that the result can be assigned to variable z. You can then print it out.

Before, you were printing the value inside your function, and not returning anything, which resulted in z getting assigned None which is why your print at the bottom didn't work.

In general it's best to do your work/computations inside the function and then return a value that you can decide how to use.

@wim shows the correct code for the function. If you now do

z = mile(x)
print "That's about %.2f kilometers." % z

you'll get the result you were expecting. (note the correct formatting as pointed out by @Aaron Dufour, you'll get 2 numbers past behind the decimal point when you print your result) Incidentally, your first print statement was correct, only the 2nd one was missing the complete formatting directive.

Upvotes: 1

Aaron Dufour
Aaron Dufour

Reputation: 17535

You have a couple of problems. The first is that your function does not return a value. When the line z = mile(x) is run, the mile(x) part will be replaced by whatever is returned by mile. The code you want is:

def mile(x):
    z = x * 1.609344
    return z

Note that it is irrelevant what variable you assign this to; it doesn't have to match the variable that is being returned. For example, both y = mile(x) and z = mile(x) will assign to the given variable properly.

Second, your string formatting won't work. This is that part that looks like "That's about % kilometers." % z. The string formatting replaces %<identifier> with the given variable, where <identifier> tells what type the variable is (and possibly some info about how to display it). You will need the identifier f or, like in the earlier print statement, .2f, giving "That's about %.2f kilometers." % z

Upvotes: 1

wim
wim

Reputation: 363243

Your function needs to return the result.

def mile(x):
    z = x * 1.609344
    return z

Upvotes: 10

Related Questions