Python Forum

Full Version: UnboundLocalError: local variable 'Num' referenced
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
my question here why does my code  generate the UnboundLocalError: local variable 'Num' referenced
error

def nsmall(n,array):
    for i in range(1,n-1):
        Num = min(array)
        del array[array.index(Num)]
    return Num
    
If your function is called with n <3, the loop is not entered - and your Num remains un-initilaized

(PS Name Num is un-pythonic)
Because you're returning a value that only sometimes is defined. If that's what you want to return, you should have a default value for it, something like:

def nsmall(n,array):
    num = None
    for i in range(1,n-1):
        num = # etc
    return num