w3resource

Python: Get the difference between a given number and 17, if the number is greater than 17 return double the absolute difference

Python Basic: Exercise-16 with Solution

Write a Python program to calculate the difference between a given number and 17. If the number is greater than 17, return twice the absolute difference.

Python if-else syntax:

if condition :
indentedStatementBlockForTrueCondition
else:
indentedStatementBlockForFalseCondition

These statement blocks can have any number of statements, and can include about any kind of statement.

Pictorial Presentation:

Get the difference between a given number and 17, if the number is greater than 17 return double the absolute difference

Sample Solution:

Python Code:

# Define a function named "difference" that takes an integer parameter "n"
def difference(n):
    # Check if n is less than or equal to 17
    if n <= 17:
        # If n is less than or equal to 17, return the absolute difference between 17 and n
        return 17 - n
    else:
        # If n is greater than 17, return the absolute difference between n and 17 multiplied by 2
        return (n - 17) * 2

# Call the "difference" function with the argument 22 and print the result
print(difference(22))

# Call the "difference" function with the argument 14 and print the result
print(difference(14))

Sample Output:

10                                                                                                            
3

Explanation:

The said script defines a function called 'difference' that takes input(n) as an argument. Using an if-else statement the function checks whether the input value of n is less than or equal to 17. If the input value of n is less than or equal to 17, the function will return the difference of 17 - n. If the input value of n is greater than 17, the function will return double the difference of n - 17.

Now the script calls the function twice with the input values of 22 and 14, respectively.

In the first case the input is greater than 17, so the function returns (22-17)*2 = 10. Therefore, the script will print 10.

In the second case the input value is less than or equal to 17, so the function returns 17-14 = 3. Therefore, the script will print 3.

Flowchart:

Flowchart: Get the difference between a given number and 17, if the number is greater than 17 return double the absolute difference.

Python Code Editor:

 

Previous: Write a Python program to get the volume of a sphere with radius 6.
Next: Write a Python program to test whether a number is within 100 of 1000 or 2000.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-exercises/python-basic-exercise-16.php