w3resource

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


34. Sum with Special Rule

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

Pictorial Presentation:

Python Exercise: 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 named 'sum' that takes two parameters 'x' and 'y'
def sum(x, y):
    # Calculate the sum of 'x' and 'y' and assign it to the variable 'sum'
    sum = x + y
    
    # Check if the calculated sum falls within the range of 15 to 19 (inclusive)
    if sum in range(15, 20):
        return 20  # If the sum falls within the specified range, return 20
    else:
        return sum  # If the sum doesn't fall within the specified range, return the calculated sum

# Call the 'sum' function with different arguments and print the results
print(sum(10, 6))   # Call the function 'sum' with arguments 10 and 6, then print the result
print(sum(10, 2))   # Call the function 'sum' with arguments 10 and 2, then print the result
print(sum(10, 12))  # Call the function 'sum' with arguments 10 and 12, then print the result 

Sample Output:

20                                                                                                            
12                                                                                                            
22 

Flowchart :

Flowchart: Convert month name to number of days

For more Practice: Solve these Related Problems:

  • Write a Python program to add two integers, but return 20 if the sum falls between 15 and 20 inclusive.
  • Write a Python program to implement conditional logic that overrides the normal sum when it is within a specific range.
  • Write a Python program to use a function that sums two numbers and checks if the result is between 15 and 20, then returns 20.
  • Write a Python program to validate two integers, compute their sum, and apply a special rule for sums in a given interval.

Go to:


Previous: Write a Python program to convert month name to a number of days.
Next: Write a Python program to check a string represent an integer or not?

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.