Pranav Borse
Pranav Borse

Reputation: 63

How do I round the value my function outputs?

I'm writing a code which converts knots to km/h.

def to_kmh(knots):
  # Calculate the speed in km/h
  return 1.852 * knots
 
# Write the rest of your program here
knots = float(input('Speed (kn): '))
if to_kmh(knots) <60:
  print(f'{to_kmh(knots)} - Go faster!')
elif to_kmh(knots) <100:
  print(f'{to_kmh(knots)} - Nice one.')
elif to_kmh(knots) >=100:
  if to_kmh(knots) <120:
    print(f'{to_kmh(knots)} - Radical!')
if to_kmh(knots) >120: 
  print(f'{to_kmh(knots)} - Whoa! Slow down!')

I'm trying to round the output (km/h) to 1 decimal place. Example: When I type in '3 knots' on the program I get:

5.556 - Go faster!

Whereas I would like to get

5.6 - Go faster!

I've tried using

def to_kmh(knots):
  # Calculate the speed in km/h
  return 1.852 * knots
  round(to_kmh, 1)

in the function, but that outputs the same result (5.556).

Upvotes: 0

Views: 270

Answers (3)

luigibertaco
luigibertaco

Reputation: 1132

You should only round when displaying, and you can achieve it like this using :.1f on your f-string variables:

def to_kmh(knots):
    # Calculate the speed in km/h
    return 1.852 * knots
 
# Write the rest of your program here
knots = float(input('Speed (kn): '))
if to_kmh(knots) <60:
    print(f'{to_kmh(knots):.1f} - Go faster!')
elif to_kmh(knots) <100:
    print(f'{to_kmh(knots):.1f} - Nice one.')
elif to_kmh(knots) >=100:
    if to_kmh(knots) <120:
    print(f'{to_kmh(knots):.1f} - Radical!')
if to_kmh(knots) >120: 
    print(f'{to_kmh(knots):.1f} - Whoa! Slow down!')

Another option, to avoid the repetition, would be to make your to_kmh return the formatted string instead of a number.

Or, if you really want to round the number from the function (it is not guaranteed that the result will be what you want):

def to_kmh(knots):
  return round(1.852 * knots, 1)

Your mistake was that your tried to round after return.

Upvotes: 4

Barmar
Barmar

Reputation: 781200

Don't do the rounding when returning the value, do it when formatting the output.

kmh = to_kmh(knots)
if kmh <60:
    print(f'{kmh:.1f} - Go faster!')
elif kmh <100:
    print(f'{kmh:.1f} - Nice one.')
elif kmh <120:
      print(f'{kmh:.1f} - Radical!')
else:
    print(f'{kmh:.1f} - Whoa! Slow down!')

There's also no need to test >= 100, since that's ensured by the previous elif. And the final test should just be else: to get all higher values.

Upvotes: 1

Sup
Sup

Reputation: 331

You have to use the round() before the return statement. In a function, anything after the return statement is executed is not executed.

So change your code to

return round(1.852 * knots, 1)

it should work fine !!

Upvotes: 2

Related Questions