144k views
0 votes
"difference" function

Write a function named "difference" that receives 2 parameters - "num1" (an int) and "num2" (an int). It should return the difference between the two numbers as an absolute value (i.e. no negative numbers, simply the difference between the two numbers regardless of order). It should not matter whether num1 is larger or smaller than num2.
e.g. difference(5, 8) should return 3, and difference(8, 5) should also return 3.
This function can be made trivial by using Python's built in "abs()" function - the task will be more worthwhile if you don't use this function

1 Answer

3 votes

Answer:

def difference(num1, num2):

if num1 > num2:

return num1 - num2

else:

return num2 - num1

Step-by-step explanation:

Here's a Python function that calculates the absolute difference between two numbers without using the built-in abs() function:

def difference(num1, num2):

if num1 > num2:

return num1 - num2

else:

return num2 - num1

This function checks which number is larger, and then subtracts the smaller number from the larger number to get the absolute difference. Note that if the two numbers are equal, the function will return 0.

User John Peralta
by
7.2k points