[SOLVED] Coursera issue for me

Issue

Please help me, i doing an online course and i was asked this question

The fractional_part function divides the numerator by the denominator, and returns just the fractional part (a number between 0 and 1). Complete the body of the function so that it returns the right number.
Note: Since division by 0 produces an error, if the denominator is 0, the function should return 0 instead of attempting the division.

here is my code:

def fractional_part(numerator, denominator):
# Operate with numerator and denominator to 
# keep just the fractional part of the quotient
   if denominator == 0 or numerator == 0:
      print("0")
   else:
        fraction = numerator / denominator
        while fraction > 1:
           fraction1 = fraction - 1
   return fraction1

print(fractional_part(5, 5)) # Should be 0
print(fractional_part(5, 4)) # Should be 0.25
print(fractional_part(5, 3)) # Should be 0.66...
print(fractional_part(5, 2)) # Should be 0.5
print(fractional_part(5, 0)) # Should be 0
print(fractional_part(0, 5)) # Should be 0

This is my output:

UnboundLocalError: local variable ‘fraction1’ referenced before assignment

Solution

If you change fraction1 to fraction you will solve the problem that fraction1 is not defined. Then you need to add fraction = 0 after the first if to solve if denominator or numerator is 0

def fractional_part(numerator, denominator):
# Operate with numerator and denominator to 
# keep just the fractional part of the quotient
   if denominator == 0 or numerator == 0:
      fraction = 0 #to solve if denominator or numerator is 0
      print("0")
   else:
        fraction = numerator / denominator
        while fraction > 1:
           fraction = fraction - 1
   return fraction

Answered By – Sefan

Answer Checked By – Pedro (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *