Search code examples
pythonfunctionnumbersfractions

Function to express an integer as its reciprocal in fraction form


I am writing a small function that turns a integer into its reciprocal in its fraction form. This is how I've defined my function so far:

    def reciprocal (number):
      return "1/",number

This sort of works but the problem is that it doesn't print the answer on the screen as I'd like to because say i did print reciprocal(3) it would show ('1/', 3) on the screen instead of 1/3. I have tried all sorts of combinations of speech marks and brackets in the code but the answer has still got extra brackets and back-ticks around it. I am using python 2.7.10, is there any way to get rid of these? Or is there any other simple way to express an integer as its reciprocal in fraction form that would get rid of them? Thank you


Solution

  • Yes. Because what this line is actually doing is returning a tuple:

    return "1/",number
    

    If you simply print:

    type(reciprocal(3))
    

    You will see the result will be tuple.

    In order to keep the functionality of:

    print(reciprocal(3))
    

    You would want to do something like this instead:

    return "1/{}".format(number)
    

    Now, the above will actually return you a string instead of a tuple. The above is using the string format method, which you can read about here. Ultimately what you are doing is creating a string that will look like 1/x, where x will be number. The way to denote the x is by using the curly braces which is then used a placeholder that will set whatever you passed to format. Read more in the documentation to understand how it works.

    To help expand it, what it actually looks like when separated is this:

    s = "1/"
    

    Now, you want to be able to set your argument number. The string object supports several methods, one of which, is format. So you can actually simply call it: s.format(). However, that won't simply work the way you want it. So, per the documentation, in order to use this format method, you need to set in your string where exactly you want to set your argument that you want to place in your string. This is done by using the placeholder characters {} to indicate this. So:

    s = "1/"
    

    Will now be

    s = "1/{}".format(number)
    

    We set our {} as the placeholder of where we want number to be, and we assigned what will be in that placeholder by passing number to format.

    You can further see how now you have a string if you in fact print the type of the result:

    print(type(reciprocal(3)))
    

    You will see it is now a str type.

    As a note in Python, you can create a tuple with comma separated values:

    >>> d = 1, 2
    >>> type(d)
    <class 'tuple'>
    

    This is exactly why your function returns the tuple, because of the fact you are returning two values simply separated by a comma.