Coursera issue for me
Solution 1:
You have to define fraction1
in your code.
You are only creating fraction1
variable inside the while
loop and that while
loop only runs when fraction > 1
.
What if fraction <= 1
? You don't have any variable called fraction1
created anywhere in your code.
And at the end your function returns fraction1
which isn't defined.
Also you must decrease fraction
by 1 inside the loop else the loop goes on indefinitely.
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:
return 0
else:
fraction = numerator / denominator
fraction1 = 0
while fraction > 1:
fraction1 = fraction - 1
fraction -= 1
return fraction1
Solution 2:
to solve this you will need to remove the Floor division
so we use this Python Arithmetic Operator //
def fractional_part(numerator, denominator):
if denominator == 0 or numerator == 0:
return 0
else:
fraction = ((numerator / denominator)-(numerator // denominator))
return fraction
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
Output
0.0
0.25
0.6666666666666667
0.5
0
0