Home > Software design >  Writing a function that returns true if an integer is between two numbers in Python
Writing a function that returns true if an integer is between two numbers in Python

Time:11-17

I have attempted to write a function that has a for loop that returns True if my input was between two numbers. this is what I wrote:

def func(x):
    x = list(range(0,1000))
    for n in x:
        if 90 <= n <= 110:
            return True
        else:
            return False

To my understanding x is between 0 to 10000 and the characters in x which are n, should return True if my input is between 90-110 and false otherwise.

However, this does not work.

I did further research and I found that the following function works which is:

def myfunc(n):
    return (90 <= n <= 110) 

This function will return true if n is between 90-110

Why is the function that has a for loop did not work ?

CodePudding user response:

When using return you get out of the function scope. for it achieve what you want to do you can use a list that contains the boolean values of each case and return that array.

CodePudding user response:

You can try using the range function:

def myfunc(n):
    lower_limit = 90
    upper_limit = 110
    
    number_range = range(lower_limit, upper_limit)
    return (n in number_range)

CodePudding user response:

The problem in your for is that you're returning False first time a number that's not in the range. And because you're creating a list of number from 0 to 1000, this means that first number will be 0.

Your script will check n=0 against 90<=n<=110. This is False so it will return False. Returnning a value will end the execution of that function, so the for loop is gonna be stopped at the first iteration returning False.

You can read here about return

  • Related