pythonstringfunctionreturn

Returning strings and floats in python functions


I need to make a function that returns a sentence with variables in it. But how do I exclude all the special string characters that I don't need? (e.g. ( or , or ')

ef area_of_triangle( bottom, height ):
    area = 0.5 * bottom * height
    return 'The area of a triangle with a bottom of', bottom, 'and a height of', height, 'is', area, '.'

this is my code for now but, the output always includes brackets, commas and apostrophes.

So when i do: print(area_of_triangle(2, 1))

the output is: ('The area of a triangle with a bottom of', 2.0, 'and a height of', 1.0, 'is', 1.0, '.')

instead of: The area of a triangle with a bottom of 2.0 and a height of 1.0 is 1.0.

How do i fix this?


Solution

  • The problem is that you're trying to use return the same way that you use print().

    When you call print(), you can pass any number of arguments separated by commas, and they will be printed as one long string.

    But that behavior is unique to print(). Other parts of Python don't work that way.

    When you do something like this:

    money = 5
    return 'I have ', money, ' dollars.'
    

    It does NOT return the single string 'I have 5 dollars'. Instead, it returns this tuple:

    ('I have', 5, 'dollars.')
    

    And then, when you print that result, that's exactly what you get.

    If you want to return a single string, you have to do a bit of work to stitch the parts together. The easiest way to do that is with an f-string:

    return f'I have {money} dollars.'
    

    The letter f at the beginning tells python that this is an f-string, which means it will replace the text {money} with the value of that variable name.