Home > Enterprise >  how to return int. if int. is in range 10-19?
how to return int. if int. is in range 10-19?

Time:02-08

Here is my code so far. I want to return all sums, but if sum is in range of 10-19, return 20. Thank you! -Learning student

def main():
    find_sum(3, 4)
    find_sum(9, 4)
    find_sum(9, 1)
    find_sum(10, 11)


def find_sum(num1, num2):
    sum = num1   num2
    if 10 <= sum <= 19:
        print(20)
    print(sum)

main()

CodePudding user response:

[NOTE] this answer was added before OP edited the question to include an if statement in the find_sum method

you can check if a number is less than another value with

if a_number < some_other_big_number

you can check if a number is greater than another number with

if a_number > some_other_small_number

you can check if a number is between 2 numbers with

if some_other_small_number < a_number and a_number < some_other_big_number

which python convieniently lets you rewrite as

if some_other_small_number < a_number < some_other_big_number

using this knowledge you should be able to accomplish your task without problems

any if statement can also have a coresponding else that allows you to take an action if(and only if) the original condition is not met

 if is_between_10_and_19(value):
    do_something(20)
 else:
    do_something(value)

CodePudding user response:

You can simply use an if - else statement using the range function to determine the range of integers.

def main():
    find_sum(3, 4)
    find_sum(9, 4)
    find_sum(9, 1)
    find_sum(10, 11)


 def find_sum(num1, num2):
        sum = num1   num2
        if sum in range(10,20): # [10:20):
                print("20")
        else:
                print(sum)

CodePudding user response:

You can use an if else statement and the range keyword to see if "sum" is in 10 - 19

def main():
    find_sum(3, 4)
    find_sum(9, 4)
    find_sum(9, 1)
    find_sum(10, 11)


 def find_sum(num1, num2):
        sum = num1   num2
        if sum not in range(10, 20) # I included 19 too
            print(sum)
        else:
            print("20") # Prints 20 if the sum is with 10 and 19 (19 included)
  •  Tags:  
  • Related