75.9k views
2 votes
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.

User Dennis
by
5.3k points

1 Answer

4 votes

Answer:

Here is the fractional_part() function:

def fractional_part(numerator, denominator):

if denominator != 0:

return (numerator % denominator)/denominator

else:

return 0

Step-by-step explanation:

I will explain the code line by line.

The first statement it the definition of function fractional_part() which takes two parameters i.e. numerator and denominator to return the fractional part of the division.

Next is an if statement which checks if the value of denominator is 0. If this is true then the function returns 0. If this condition evaluates to false which means that the value of denominator is not 0 then return (numerator % denominator)/denominator is executed. Now lets see how this statement works with the help of an example.

Lets say the value of numerator is 5 and denominator is 4. (numerator % denominator)/denominator will first compute the modulus of these two values. 5 % 4 is 1 because when 5 is divided by 4 , then the remainder is 1. Now this result is divided by denominator to get the fractional part. When 1 is divided by 4 the answer is 0.25. So this is how we get the fractional part which is 0.25.

The program with output is attached.

The fractional_part function divides the numerator by the denominator, and returns-example-1
User Hcknl
by
5.1k points