Search code examples
pythonfunctionreturnuser-defined-functionsfractions

My return statement in a fraction-simplifying function in Python doesn't work


I have this function that simplifies a fraction.

  • Input: 2 numbers - a Numerator and a Denominator.

  • Output: 2 numbers - a Numerator and a Denominator (simplified).

When I call the function to simplify a = 12 and b = 36, and print them afterward, why are they still a = 12 and b = 36 and not a = 1 and b = 3?

This Python code:

def simp(n, d):

  # Find the smaller number
  limit = min(n,d)

  # For loop that repeatedly divides numerator and denominator by a common dividend
  for dividend in range(limit, 2, -1):
    if (n % limit == 0) and (d % limit == 0):
      n = n / limit
      d = d / limit
  
  # Return the simplified numbers
  return (n, d)

a = 12
b = 36
print(a, "/", b,)
print("should be simplified down to")
simp(12, 36)
print(a, "/", b)

Outputs:

12 / 36
should be simplified down to
12 / 36

I don't think it is because of the algorithm, because when I tried print(n, "/", d) within the function, it correctly outputs 1 / 3. So there is probably something wrong with the return statements, I just don't know what's wrong.


Solution

  • You call simp(12,36) which returns a tuple but you don't assign it to anything.

    all you need to do is where you call simp is put [a,b] = simp(12,36)

    Edit: Brackets are not needed, simply can be a, b = simp(12,36). Thanks @Barmar