UnboundLocalError: local variable 'count' referenced before assignment - python

Throwing error at "count+=1". I tried making it a global etc. and it still gave an issue. It's more of a joke than anything, but I'd like to know why it isn't working.
import math
def delT():
#inputs
#float inputs
#do math
#print results
global count
count=0
def getAndValidateNext():
#print menu
getNext=input("select something")
acceptNext=["things","that","work"]
while getNext not in acceptNext:
count+=1
print("Not a listed option.")
if count==5:
print("get good.")
return
return(getAndVadlidateNext())
if getNext in nextRestart:
print()
return(delT())
if getNext in nextExit:
return
getAndVadlidateNext()
delT()

You need to move your global keyword down into your function.
count=0
def getAndValidateInput():
global count
#print menu
#So on and so forth
Now you should be able to access your count variable. It has to do with scoping in Python. You have to declare a variable is global in each function that you want to use it in, not just where it is define.

I ran into the same issue once, it turned out to have to do with the scope and having a function definition within another function definition. What worked was writing separate functions that would create and modify a global variable. Like this for example:
def setcount(x):
global count
count = x
def upcount():
global count
count += 1

global count should be inside the getAndValidateInput() function.

Related

How to reuse a variable

I have the variable total in a function. Say that I'd like to use that variable in an if statement in another function. I can use the return keyword and return that variable from my first function but how would I use that variable in an if statement that would be outside that function or even in a different function?
You could re-declare the variable with the value from the function. I don't have a lot of information, but I think this is what you mean.
def some_function():
total=10
return total
total=some_function()
print(total)
return the value from your first function, and then a call to that function will evaluate to that value. You can assign the value to a variable, or pass it directly to another function. In either case, the value doesn't need to be assigned to the same variable name in different scopes.
def func_a():
total = 42
return total
def func_b(the_answer):
if the_answer == 42:
print("That's the answer to the ultimate question!")
func_b(func_a())

How can I get a function in Python 3 to return a value that I can use in another function?

I need to design a game of snakes and ladders in python and for part of it, I need to be able to roll a dice and get a random value. For this, I have imported random and then written the function below. However, obviously, I then need to be able to use the dice value in other functions of the game. How do I get it so that the value python returns is retained and able to be used in another function.
Below is the function I have written for rolling the dice. However, when I then run this function and then afterwards try print(dice_value), the program tells me that dice_value has not be defined.
Anybody able to help??
import random
def roll_dice():
dice_value = random.randint(1,6)
print("Its a..." + str(dice_value))
return dice_value
The variable dice_value exists only inside your function roll_dice(). It is a local variable.
You need to call your function with:
my_variable = roll_dice()
Now the result of your function is stored in the variable my_variable, and you can print it.
You have to save the return value somewhere and then use it or pass it to another function.
For example:
>>> import random
>>> def roll_dice():
... dice_value = random.randint(1,6)
... print("[in roll_dice] Its a..." + str(dice_value))
... return dice_value
...
>>> obtained_dice = roll_dice()
[in roll_dice] Its a...1
>>> print("[outside roll_dice] Its a..." + str(obtained_dice))
[outside roll_dice] Its a...1
variable dice_value is a local variable inside the function space so you have to return and save it in another variable to continue using it
You can store the return value of your function roll_dice() in a variable that will in return store the value of the return variable (dice_value).
random_dice_value = roll_dice()
Note: You need to call the function after you have implemented it since Python is an interpreter language. It will execute the file line by line.
The problem is that you're trying to call the variable dice_value outside of its scope. If you still go on with your one liner print statement, you can do so by calling the function (that's returning the dice_value variable) as in:
print(roll_dice())

How to change a variable and keep the change from a function inside a function

#a test to see how to call and modify a variable by a function inside a function!
test_variable = "Hello __1__ !!, I'm good, How about you!!"
#function 1 to save to variable
def test_function_1():
global test_variable
hello = test_variable
return hello
#function 2 to use the variable through function 1
def test_function_2(test):
global test_variable
word = raw_input("Hi, Enter your word\n")
print
test = test.replace("__1__", word)
return test
#See how the function work!
print test_function_2(test_function_1())
#See if the variable changed by the function or not!
print test_variable
I can't keep the change to the variable. I try global in every function and it didn't work.
Remember in python, strings are immutable. So you can't change them. (I am guessing by 'I can't keep the change to a variable', you were expecting the global test_variable to change as well.
You are essentially assigning names. This talk is a good place to start to understand some core python concepts:
https://www.youtube.com/watch?v=_AEJHKGk9ns

Python: Referencing global variables inside a function

I came across this problem of not being able reference golbal variables from inside of a function. It always throws an error saying "local variable 'variable_name ' referenced before assignment".
I wrote a simple code which will throw the same error in trying to return a array of product of two numbers.
table=[]
counter = 0
def multiplier(num):
if counter >9:
print (table)
else:
table.append(num*counter)
counter +=1
multiplier(num)
multiplier (5)
What am I doing wrong here? My original code requires the function to be called again and again for that I want to use a counter to keep track of how many times it is being called. This means I cannot initialize the counter inside of the function because once the function is called and because the counter is initialized inside the function, it will be reset.
Use global keyword at the first line in your function block.
Like:
def multiplier(num):
global counter
...
You have to declare
global counter
in your function to access the global variable instead of creating a local variable of the same name. The nicer solution would be to define a class, though.
Make counter a parameter of the function with a default value of zero. When you recurse, add one to the count.
table=[]
def multiplier(num, counter = 0):
if counter >9:
print (table)
else:
table.append(num*counter)
multiplier(num, counter+1)
multiplier(5)
Here is your function refactored to return a value instead of printing it.
table=[]
def multiplier(num, counter = 0):
if counter >9:
return table
else:
table.append(num*counter)
return multiplier(num, counter+1)
print(multiplier(5))
You can use global keyword to use the global variable. Following points to keep in mind:
Use global keyword only when you are changing the global variable value.
You can use global variable if only reading just by using the variable name (global variable definition not required here).
Example:
var = 10
def change_var():
global var
var = 2
return var
def read_var():
print "Variable is:",var
Hope this helps.

Order of execution in Python methods [duplicate]

This question already has answers here:
Assigning to variable from parent function: "Local variable referenced before assignment" [duplicate]
(5 answers)
Closed 9 years ago.
I've tried looking at a few different examples, but I'm not really sure why this isn't working. Say I've some code like this:
def loadVariable():
global count
count = 0
def loadDictionary():
location = 'some location'
global myDict
myDict = pickle.load(open(location, 'rb'))
def main():
loadVariable()
loadDictionary()
for item in myDict:
if item.startswith("rt"):
count += 1
item = item[3:]
if __name__ == '__main__':
main()
To my eyes, the if statement is executed which starts the main() method. Then, the variable which is global is loaded, the dictionary is loaded and the for loop is executed.
However, when I run the code I am told that the local variable count is referenced before its assignment. Why is that happening?
Edit (Explaining some of the things I've written in comments):
This doesn't work (although I think that's because global is used wrong here):
global count
def loadVariables()
count = 0
def main():
loadVariables()
rest of code etc
This doesn't work either:
def loadVariables()
count = 0
def main():
global count
loadVariables()
rest of code etc
The only way thus far I've gotten it to work is using the link provided above, which is to treat the count as a list, like so:
def loadVariables():
global count
count = [0]
def main():
loadVariables():
rest of code etc
count[0] += 1
global means that within the function containing the global declaration, the name in the global declaration refers to a global variable. It does not mean "this thing is a global variable; treat it as global everywhere." In main, the names count and myDict refer to local variables, because main does not declare that it wants to use the globals.
The issue is that you're not declaring count as a global variable in the main function, so when the compiler sees that you're (eventually) assigning to it, it assumes that it's a local variable. Since it's value is read before it's assigned, you get an exception.
So, the most basic fix is just to add global count at the top of main(), but I think avoiding globals would be a better option. Why not have loadVariable and loadDictionary return their results, rather than assigning them to globals? If in main() you did count = loadVariable(), count would be a local variable, and you'd have no problems later trying to reassign it.
Here's a simple example of how global works
global_var = 0
def updater():
global global_var
global_var += 1
def stuff(x):
updater()
return global_var + x
if __name__ == '__main__':
stuff(2) # returns 3

Categories

Resources