Python Forum
Why is this function returning none?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Why is this function returning none?
#1
def in1to10(n, outside_mode):
    if outside_mode != True:
        if n >= 1 and n <= 10:
            return True
    if outside_mode == True:
        if n <= 1 or n >= 10:
            return True
    else:
        return False

print(in1to10(2, True))
The code is supposed to meet the conditions:
Given a number n, return True if n is in the range 1..10, inclusive. Unless outside_mode is True, in which case return True if the number is less or equal to 1, or greater or equal to 10.
My code works for every case except when outside_mode=True and n is between 1 and 10, the functions returns none. Why is the function not returning False, shouldn't the else statement make the function always return false if the above two if statements are not met?
Reply
#2
It is passing this clause
Quote:
if n <= 1 or n >= 10:
2 is not less than or equal to 1, nor is 2 greater than or equal to 10, so it moves to the end of the function and returns None. Your else clause is pertaining to outside_mode being True which it is so it does not execute that. Control is flowing to the second if condition, then that nested if condition and fails, then it moves to line 10 and returns None because there is nothing else in the function. If you want the function to not be able to return None, then remove your else line, and dedent the return False back one indentation level. your two outer if condtions should also be if and elif. It is either one or the other, not both or neither.

PS: you should do this for boolean conditions:
def in1to10(n, outside_mode):
    if not outside_mode: #if outside_mode is False
        if n >= 1 and n <= 10:
            return True
    if outside_mode: #if outside_mode is True
        if n <= 1 or n >= 10:
            return True
    return False
print(in1to10(2, True))
Recommended Tutorials:
Reply
#3
Bitwise operators come in handy here as you are looking for an exclusive or:

def in1to10(n, outside_mode=False):
    return (1 <= n <= 10) ^ outside_mode
I am trying to help you, really, even if it doesn't always seem that way
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Can anyone spot why this function is returning an empty list? hhydration 2 1,868 Nov-18-2020, 06:16 AM
Last Post: deanhystad
  Function not returning correct value TsG009 4 4,155 Nov-24-2017, 09:07 PM
Last Post: sparkz_alot
  Function for returning absolute numbers Ernstblack 2 3,205 Oct-02-2017, 05:48 PM
Last Post: nilamo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020