zRage4
zRage4

Reputation: 39

Why am I getting the output as None?

I've been trying to check whether the numbers in a list of numbers are between -1,000,000 to 1,000,000.

This is how I approached the problem, I first initialized 'check' = True and an array of integers named A. I then loop through the array to check whether each number is in the range or not. 'check' is set to True if it is and False if it isn't. I then return the check value at the end of the loop. I proceed to call the function and I am trying to use the check value from the function to determine whether to sort the loop or print "Out of range!" I am not really sure what I'm missing.

check = True
A = [10, 3, 600000000, 3, 2]

def solution(A):
    
    for num in A:
        if(-1000000 <= num <= 1000000):            
            check = True
                
        else:                
            check = False
            break
    return check

solution(A)

if(check == True):
    print(A.sort())
else:
    print("Out of range!")

Upvotes: -1

Views: 110

Answers (3)

Zack Henkusens
Zack Henkusens

Reputation: 160

Your sort syntax was incorrect and returned none as pointed out in the comments. Also you were using a global variable which defeats the purpose of using functions (modularity). Code below is more efficient and readable.

#Check if number 'A' is within range
A = [10, 3, 600000000, 3, 2]

def solution(A):    
    for num in A:
        if(num > 1000000 or num < -1000000):        
            return False
    return True

if(solution(A) == True):
    print(sorted(A)) # Fixed sort syntax
else:
    print("Out of range!")

Output:

enter image description here

Alternative input [10,3,3,-3]:

enter image description here

Upvotes: 0

Aniket Tiratkar
Aniket Tiratkar

Reputation: 858

A.sort() sorts the contents of A, but it's return value is None.

>>> A = [5, 3, 6, 4]
>>> return_value = A.sort()
>>> print(A)
[3, 4, 5, 6]
>>> print(return_value)
None

If you need to print sorted list A, then you should use

print(sorted(A))

instead of

print(A.sort())

Upvotes: 1

Alvi15
Alvi15

Reputation: 335

Variable that is defined in a block is available in that block only. It is not accessible outside the block.

def solution(A):
    
    for num in A:
        if(-1000000 <= num <= 1000000):            
            check = True
                
        else:                
            check = False
            break
    return check

So your check value here is not accessible outside of Solution function. Since your function already returns check. Simply

check = solution(A)

To save your check outside the function.

And about printing, according to comment by @python_learner

print(A.sort())

A.sort() does an in place sort, it returns None, use print(sorted(A)) or do A.sort() then do print(A)

Upvotes: 1

Related Questions