Python Error: local variable 'last_card' referenced before assignment - python

The program keeps on telling me that 'last_card' is referenced before the assignment and it is. However, how can I by pass this error. If you look at the code, last_card is referenced in the first if statement. I want to use its value from the first "IF" statement and use it in the second. How can I do that?
if region == "showCardHistory":
temp = re.search(r'Card History for Slot (A|B|\d+)(.*)',line)
if temp:
last_card = temp.group(1)
temp = re.search(r'Secs since boot\s+:\s+(\d+)',line)
if temp:
card_slot_string = re.match(r'(A|B)',line)," CPM ",last_card,":"," IOM ",last_card

Python doesn't know for sure that the 1st if clause will be called. So, in order to be safe, it will assume at compile-time that last_card hasn't yet been declared. When you reference it in your 2nd if clause, the case may happen that the 1st if clause didn't evaluate True, and then it will have an UnassignedError.

Related

understanding python inner function .how does this works?

def prefix_factory(prefix):
def prefix_printer(text):
print(f"{prefix}: {text}")
return prefix_printer
Now lets execute the below line.
# First time we are executing this
debug = prefix_factory('DEBUG')
# Second time we are executing as
debug('Hello world')
First time we are executing this
1st execution or assignment of function to the variable debug is assigned the value "DEBUG". My understanding is this is how it has to be executed.
ideally inner function prefix_printer(text) - gets defined inside prefix_factory()
'return prefix_printer' should get an error, stating that text is not available or text is missing.
Second time we are executing as
debug('hello world ') - 2nd execution of the function reference.
The question for the second execution is, I am assuming 'hello world' should be considered as a value for the prefix. and text should be blank as we don't call prefix_printer in the return statement with any value. Hence it has to be '' empty string. I am coming from c, C++ background.
My question is, it's the same piece of code 1st-time prefix is assigned,
but during the 2nd execution debug('Hello world') it behaves differently. How is it possible, please clarify in detail how this works?
When debug = prefix_factory('DEBUG') is executed, variable debug is assigned the return value from calling function prefix_factory('DEBUG'). It is not assigned the value "DEBUG" as you said. And what is this return value?
Function prefix_factory returns prefix_printer, which is a function nested within prefix_factory. Moreover, prefix_printer references a variable, prefix, which is defined in the outer, enclosing function. When prefix_factory returns a nested function, prefix_printer, that references a variable defined in the nesting function, that returned function is known as a closure. Even though we have now returned from the call to printing_factory, the closure function prefix_printer, which has now been assigned to variable debug, still has a reference to the value of variable prefix as it existed at the time prefix_factory was called.
Subsequently, when you execute debug('Hello World'), because debug evaluates to our prefix_printer closure , this is equivalent to calling function prefix_printer('Hello World') with variable prefix initialized to 'DEBUG'.

Python variable declared in 'for' loop not seen outside of loop

I know there are quite a few "python scope questions" here but I am VERY rusty with python and I am really confused about a "UnboundLocalError" problem I keep getting. I have read that 'for' loops do not have a contained scope yet my code seems to be acting in that way... My code looks like this:
`
...
for b in blocks[:]:
if b.contains(CONSTANT_NUM):
r = b.split(CONSTANT_NUM+2)
if r: blocks.append(r)
Foo= struct.unpack('<H', b.data)[0]
Bar = Foo
...
print("Foo: 0x%x" % (Foo))
`
Whenever I run this, I get the error "UnboundLocalError: local variable 'Foo' referenced before assignment". When I instead try and print Bar I get the same error. Why is the assignment not being carried outside of the 'for' loop?
It could be very likely that your loop never went into the if statement and hence Foo was never initialized.
You need to initialize it before the loop just to make sure that if that conditional is never met, you have something to print.
In your case, if the 1st if condition is failing, then the compiler won't reach the Foo = ... statement. Which will result in the error you are getting now.
The error indicates that at the time of checking the variable foo you have not yet initialized.
you should initialize it before the loop.

How to stop Function reassigning Boolean value within loop

Im trying to learn Python via creating a basic language-learning app to test myself. In order to get it to test me with a different word each time I have tried to write a function that generates an intial key ONLY IF it is the first time it is run (after this i have another function which should generate a different key).
In order to do this I have tried to us a Boolean (isfirsttime) which I initially set to False within the main loop of the particular Tkinter window in which this part of the code runs (sorry if I'm not explaining this particulary well am admittedly a total begginer!).
Within my function I then check if this value is False and then - it is - i generate a key and pass out this plus the value TRUE.
Back in the main loop I then assign the value True to the variable isfirsttime.
I think that the problem is that in the main loop the isfirsttime is FIRST assigned to False (to get the function checkfirst to work the first time) but this means that every time it is run it resets the Boolean to False.
Could anybody explain to me how I can reassign the value of isfirst time to TRUE after the first time the code has run, in a way that will cause the checkfirst function to PASS everytime after that? (I know that my problem has something to do with scope but i cannot figure it out - and have tried functions within functions and endlessly reassigning variables so I'm obviously not getting something here!)
Many thanks!
isfirsttime == False
def checkfirst():
if isfirsttime==False:
for item in categories:
newkey=random.choice(list(tempdict))
print("key is" + newkey)
isfirsttime=not isfirsttime
print(str(isfirsttime) + "isfirsttime")
return newkey, True
else:
pass
genkey=checkfirst()[0]
isfirsttime=checkfirst()[1]
You can make the call like this:
genkey, isfirsttime = checkfirst()
However, you still need to do something about the second time that checkfirst() is called.
Also, reading the comments under your question you need to sort out the assignment to isfirsttime:
isfirsttime = False # assign isfirsttime to False
def checkfirst():
# stuff omitted

Django: "referenced before assignment" but only for some variables

I'm writing a small app in Django and I'm keeping the state saved in a few variables I declare out of the methods in views.py. Here is the important part of this file:
from app.playerlist import fullList
auc_unsold = fullList[:]
auc_teams = []
auc_in_progress = []
auc_current_turn = -1
print(auc_in_progress)
def auc_action(request):
data = json.loads(request.GET["data"])
# ...
elif data[0] == "start":
random.shuffle(auc_teams)
print(auc_unsold)
print(auc_in_progress)
auc_in_progress = [None, 0, None]
print(auc_in_progress)
The auc_unsold and auc_teams variables work fine; the auc_in_progress variable is not seen by this method, though, giving the error in the title. If I take out the print statement and let this code assign a value to it, the exception will be thrown somewhere else in the code as soon as I use that variable again.
I have tried making another variable and this new one seems to suffer from this problem as well.
What is happening?
Edit: I found a solution: if I write global auc_in_progress just before the print statements, then everything works fine. If I try writing that as I declare the variable above it doesn't work, though, for some reason.
I am unsatisfied with this, because I don't know why this happens and because I dislike using global like that, but eh. Someone has an explanation?
You should absolutely not be doing this, either your original code or your proposed solution with global.
Anything at module level will be shared across requests, not only for the current user but for all users for that process. So everyone will see the same auction, etc.
The reason for your error is because you assign to that variable within your function, which automatically makes it a local variable: see this question for more details. But the solution recommended there, which is the same as your workaround - ie use global - is not appropriate here; you should store the data somewhere specifically associated with the user, eg the session.

Python range() builtin function, erm... malfunctioning with Django

What, if anything, is wrong with this line of python code:
daterange = [begin + timedelta(n) for n in range((end - begin).days)]
Where begin and end are datetime.date objects with valid values.
I'm using this in a Django view to process some data, but everytime the view this is in gets called I get the following error with the aforementioned line highlighted:
UnboundLocalError at /url/of/error/creating/view/here/
local variable 'range' referenced before assignment
If I execute this line inside the interpreter it works fine, but somehow it doesn't fly inside a Django view. I don't understand why range is being interpreted as a variable name at all. Is there actually something wrong with this line, or is it something else in the code that's making Django complain?
Help!
There's nothing wrong with Django. You create a local variable range in the same scope (by assigning one). For instance range = None in the very last line of a function makes Python consider an occurrence of range in the first line of the same function a reference to that local variable. Since it doesn't have a value assigned at that point, you get an UnboundLocalError.

Categories

Resources