Newbie needs some help!

Hey everyone ! I’m in my first week at Codecademy and I love it so far! In between lessons I like experimenting with things I’ve learned and coupled with some help from googling things I finally got together a kilometre to mile conversion which also saves the output to a text file (I’m sure this is very simple for most but it’s a big step for me!).

My issue is, how can I change the following code where the output of miles (mi) gets rounded to 2 decimal places? I’ve tried using round() in so so many different ways and places with no luck …

while True:

km = float(input('Kilometers value: '))
factor = 0.62137119

mi = km * factor
print('%0.2f kilometers is equal to %0.2f miles' %(km, mi))


output = str(mi)
file = open('km_mile.txt','a')
file.write(str(km) + ' kilometers is equal to ' + output + ' miles' + '.\n')
file.close()

if km == 0:
	break

I would love to know how to use round() in this case to only affect the output in the text file !
Thank you in advance to anyone who can help!

The exact string fromatting (including trailing decimal places) can be imposed with formatting specifiers. I think the docs are a rough place to start for this one and if it’s Python2 this guide reads quite nicely (from a cursory glance)-
https://pyformat.info/

Edit (again): As per the answer below you need to change what’s being passed in file.write-

3 Likes

Hey there @oof001 :grinning: Welcome to the forums!!

There are a couple ways you could do this, and you already used one of them!
You could do the same thing you did in line 5:

However as you said you would like to use the round function.

The round function can take in one or two parameters, the number or variable to be rounded, and the number of decimal points you want rounded to.
In this case you would probably use both parameters:

n = 67.83439
print(round(n, 2) #prints 67.83
3 Likes

wow so I just changed

file.write(str(km) + ’ kilometers is equal to ’ + output + ’ miles’ + ‘.\n’)

to

file.write(’%0.0f kilometers is equal to %0.2f miles’ %(km, mi) + ‘.\n’)

and what do you know when I opened the .txt file it worked like a charm! It was right in front of me and I spent so long looking for a solution… much appreciated !!

and I’ll definitely look through https://pyformat.info/ since I have lots to learn

thanks again fellas !

1 Like