Python Forum
UnboundLocalError: local variable 'Num' referenced
Thread Rating:
  • 2 Vote(s) - 3 Average
  • 1
  • 2
  • 3
  • 4
  • 5
UnboundLocalError: local variable 'Num' referenced
#1
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
    
Reply
#2
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)
Test everything in a Python shell (iPython, Azure Notebook, etc.)
  • Someone gave you an advice you liked? Test it - maybe the advice was actually bad.
  • Someone gave you an advice you think is bad? Test it before arguing - maybe it was good.
  • You posted a claim that something you did not test works? Be prepared to eat your hat.
Reply
#3
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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  It's saying my global variable is a local variable Radical 5 1,099 Oct-02-2023, 12:57 AM
Last Post: deanhystad
  local varible referenced before assignment SC4R 6 1,465 Jan-10-2023, 10:58 PM
Last Post: snippsat
  How does UnboundLocalError work? deanhystad 3 1,633 Feb-25-2022, 01:21 AM
Last Post: bowlofred
  UnboundLocalError: local variable 'wmi' referenced before assignment ilknurg 2 1,859 Feb-10-2022, 07:36 PM
Last Post: deanhystad
  Referenced before assignment finndude 3 3,223 Mar-02-2021, 08:11 PM
Last Post: finndude
  exec + subprocess = UnboundLocalError paul18fr 6 3,445 Feb-04-2021, 06:27 AM
Last Post: Gribouillis
  ReferenceError: weakly-referenced object no longer exists MrBitPythoner 17 11,268 Dec-14-2020, 07:34 PM
Last Post: buran
  UnboundLocalError: local variable 'figure_perso' referenced before assignment mederic39 2 2,230 Jun-11-2020, 12:45 PM
Last Post: Yoriz
  UnBoundLocalError Seaninho 3 2,625 May-31-2020, 07:22 AM
Last Post: azajali43
  local variable 'marks' referenced before assignment Calli 3 2,277 May-25-2020, 03:15 PM
Last Post: Calli

Forum Jump:

User Panel Messages

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