﻿ Python: Sum of two given integers. However, if the sum is between 15 to 20 it will return 20 - 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:

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:

Python Code Editor:

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿