Python Forum
Is that code correct? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: Is that code correct? (/thread-33739.html)



Is that code correct? - Sameh - May-22-2021

Hi there,

This is my first participation. to answer ►How many miles are there in 10 kilometers?
Is this way correct:

miles_in_kilometer = 10 / 1.61
print('There are {} miles in 10 kilometers'.format (miles_in_kilometer))



RE: Is that code correct? - Yoriz - May-22-2021

It depends on what you mean by correct?
if you want the output to be
Output:
There are 6.211180124223602 miles in 10 kilometers
Then it is correct?
Note: your conversion amount 1.61 is quite rounded up, it would probably be better using 1.609344


RE: Is that code correct? - Sameh - May-22-2021

Thanks for your prompt reply,
I mean is it correct when I answer this question..

How many miles are there in 10 kilometers?

Is it approximately 6.1 miles in 10 kilometers? and this Python code is correct output..!


RE: Is that code correct? - Yoriz - May-22-2021

10 km to miles


RE: Is that code correct? - Sameh - May-22-2021

Thanks,
I am trying to understand all exercises in Think Python book ...

Thanks again..


RE: Is that code correct? - perfringo - May-22-2021

You probably want to control display of the result. I would go with yard precision:

>>> miles_in_kilometer = 10 / 1.61
>>> print('There are {:.3f} miles in 10 kilometers'.format(miles_in_kilometer))
There are 6.211 miles in 10 kilometers
Of course one can use expressions inside f-strings so it can be written also as:

>>> f'There are {10/1.61:.3f} miles in 10 kilometers'
'There are 6.211 miles in 10 kilometers'
PS - don't use space between format and opening parenthesis.


RE: Is that code correct? - Yoriz - May-22-2021

Without an example of what a correct output should look like, no one knows what correct is.
@perfringo is assuming you want 3 decimal places but that might not be correct.


RE: Is that code correct? - Sameh - May-22-2021

Thanks @perfringo,
It's a good way to display decimal with f-string.

Thank to you all