w3resource

Python: Sum of two given integers. However, if the sum is between 15 to 20 it will return 20

Python Basic: Exercise-34 with Solution

Write a Python program to sum two given integers. However, if the sum is between 15 and 20 it will return 20.

Pictorial Presentation:

Sum of two given integers. However, if the sum is between 15 to 20 it will return 20

Sample Solution:

Python Code:

# Define a function 'sum' that takes two integer inputs: x and y.
def sum(x, y):
    # Calculate the sum of x and y and store it in the 'sum' variable.
    sum = x + y
    # Check if the calculated sum is within the range [15, 20) (inclusive on 15, exclusive on 20).
    if sum in range(15, 20):
        # If the sum is within the range, return 20.
        return 20
    else:
        # If the sum is outside the range, return the calculated sum.
        return sum

# Test the 'sum' function with different sets of input values and print the results.
print(sum(10, 6))
print(sum(10, 2))
print(sum(10, 12))

Sample Output:

20                                                                                                            
12                                                                                                            
22 

Explanation:

The said code defines a function "sum(x, y)" that takes two integers as arguments and returns their sum.

It first calculates the sum of the two integers and assigns it to the variable "sum".

Then it checks whether the value of "sum" is in the range of 15 to 20 (inclusive) using the in-built Python function "range()".

If the value of "sum" is in the range of 15 to 20, the function returns 20 otherwise, it returns the value of "sum".

At the end, the function is called three times with different inputs and prints the sum of the inputs.

Flowchart:

Flowchart: Sum of two given integers. However, if the sum is between 15 to 20 it will return 20.

Python Code Editor:

 

Previous: Write a Python program to sum of three given integers. However, if two values are equal sum will be zero.
Next: Write a Python program which will return true if the two given integer values are equal or their sum or difference is 5.

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://198.211.115.131/python-exercises/python-basic-exercise-34.php