[Tutor] stuck
Mats Wichmann
mats at wichmann.us
Mon Apr 8 09:36:23 EDT 2024
On 4/7/24 19:06, Robert Towne wrote:
> Im unable to figure out what I am doing wrong
>
> def convert_distance(miles):
> km = miles * 1.6
> result = "{:.1f} miles equals {:.1f} km".format(miles,km)
> return result
>
>
> print(convert_distance(12)) # Should be: 12 miles equals 19.2 km
> print(convert_distance(5.5)) # Should be: 5.5 miles equals 8.8 km
> print(convert_distance(11)) # Should be: 11 miles equals 17.6 km
Your code should work - if you indent it properly. We can't always tell
here whether this is your mistake or some mail system trying to be
clever about what it thinks your writing should look like. Indentation
is part of Python syntax. It's ignored in many other programming
languages, but used anyway as an aid to readability. In Python a
statement ending in a colon is followed by a statement block (one line
or more) that must be indented to tell the interpreter which lines are
part of the block. For the block that forms the function definition it's
the lines up to the ending "return", so your function needs to look like
this:
def convert_distance(miles):
km = miles * 1.6
result = "{:.1f} miles equals {:.1f} km".format(miles,km)
return result
And yes, as Klaus says, many people prefer the "f-string" syntax - short
for formatted string literals - largely because it puts the interpolated
variables right there with their formatting instructions and you don't
have to keep looking to the right to match up variables with
placeholders in the string. But the format() method of strings is still
a valid part of the language.
More information about the Tutor
mailing list