Local variable referenced before assignment global doesn't work - python

how can I make this function working? Is there a good subsitute for global??
position=0
score=0
eggY=300
eggX=0
def egglg():
while True:
global eggX
global eggY
if eggX<330:
eggX+=5
eggY+=0.8
elif eggX>=330:
eggY=eggY+2
if eggY>450:
terminate()
elif eggY<450 and eggY>350 and position ==1:
score+=1
return
#rest of my code, with chaning position to 1 when i press w
egglg()
somehow it returns 0

Since you want to write to the global variables eggX, eggY and score you've to declare all 3 variables global:
position=0
score=0
eggY=300
eggX=0
def egglg():
global eggX, eggY, score
# [...]
Note, the variable position is just read, so there is no necessity to declare it golabal.

Related

is there a solve with my python code ! return 1 only?

def check_answer (q, a, s ):
if q == a :
s += 1
print (f" your score is {s} ")
else :
s -= 1
print (f" your score is {s} ")
i know maybe my english not good but i need help with my problem
i made a quiz project ,
when user enter the right answer I want the program give him more 1 point in his score
but my code does not work good !!
my code
Two options
Use return value to update caller variable
Use global variable so function uses caller's variable s
Note: Option 1 is normally preferred with Option 2 only for simple code.
Issue with Option 2 is global variables enable functions to have hidden (non-obvious, surprising, hard to detect, hard to diagnose) side effects, leading to an increase in complexity--Source
Option 1--use return to update s
def check_answer (q, a, s ):
# a local s is initialized to the passed-in value
if q == a :
s += 1 # update local s in function check_answer
print (f" your score is {s} ")
else :
s -= 1 # update local s in function check_answer
print (f" your score is {s} ")
return s # returns the value of the local s to caller
# Usage (as mentioned by Barmar in comments)
# Initialization (set s to initial value)
s = 0
# ... some code
s = check_answer(q1, a1, s) # s is updated to new value
# ...some more code
s = check_answer(q1, a2, s) # s is udpated to new value
# ...and so on
Option 2: share s as a global variable
def check_answer (q, a):
global s # use s from global scope
if q == a :
s += 1 # updates global variable s
print (f" your score is {s} ")
else :
s -= 1 # updates global variable s
print (f" your score is {s} ")
# Usage
# initialize s (global scope variable i.e. outside function calls)
s = 0
# other code
# ...
check_answer (q1, a1) # global s is updated
# ...
# ...
check_answer(q2, a2) # global s is updated
# ...and so on
# ...

Error: UnboundLocalError: local variable 'attempts' referenced before assignment

I am attempting to make a simple guessing game for my class with graphics and I'm trying to make an attempt counter. This is the area where my code is going wrong.
def value():
guess = int(input("Enter your guess: "))
if guess > num:
attempts = attempts + 1
turtle.clearscreen()
interface()
tooHigh()
attempt = turtle.Turtle()
attempt.speed(0)
attempt.color("white")
attempt.penup()
attempt.hideturtle()
attempt.goto(-250 , 200)
attempt.write(guess, font=("Courier", 14, "bold"))
value()
elif guess < num:
attempts = attempts + 1
turtle.clearscreen()
interface()
tooLow()
attempt = turtle.Turtle()
attempt.speed(0)
attempt.color("white")
attempt.penup()
attempt.hideturtle()
attempt.goto(-250 , 200)
attempt.write(guess, font=("Courier", 14, "bold"))
value()
elif guess == num:
attempts = attempts + 1
turtle.clearscreen()
interface()
yes()
attempt = turtle.Turtle()
attempt.speed(0)
attempt.color("pink")
attempt.penup()
attempt.hideturtle()
attempt.goto(-250 , 200)
attempt.write(guess, font=("Courier", 14, "bold", "underline"))
print ("Correct!")
else:
print ("ERROR")
def startScreen():
begin = input("Start the game?: ")
if begin == 'yes':
value()
elif begin == 'instructions':
instructions()
startScreen()
elif begin == 'no':
sys.exit()
else:
print ("Unrecognised answer.")
startScreen()
attempts = 0
num = random.randint(1,1000)
interface()
startScreen()
The error I receive is:
Traceback (most recent call last):
File "D:\Desktop\Python Programs\Game.py", line 154, in <module>
`startScreen()`
File "D:\Desktop\Python Programs\Game.py", line 141, in startScreen
`value()`
File "D:\Desktop\Python Programs\Game.py", line 110, in value
`attempts = attempts + 1`
UnboundLocalError: local variable 'attempts' referenced before assignment
It doesn't seem possible to move attempts into the function as it constantly calls itself, resetting attempts each time.
I am unsure why this is occurring so any help would be greatly appreciated. Thanks!
The reason you are getting this error is because of something called variable scope. You have defined the variable attempts outside of the function value, so the function will not recognize any local variable by the name attempts unless you explicitly put the statement global attempts at the beginning of your function. This will tell the function that you want to use the variable attempts that you defined in your main program. That should look like this:
def value():
global attempts
#function code
Alternatively, you can allow your function value to take an argument, and pass the variable attempts into that. That would look something like this:
def value(attempts):
#function code
#you can use the variable attempts as needed, since you're passing it directly into the function
#call the function however you want
attempts = 0
value(attempts)
In the function, when you access a variable for assignment, it by-default is treated as a local variable. So, to make Python know that the variable that you want to modify is a global variable, you do the following:
def value():
global attempts
# rest of your code

Python Random Project

This is a random code which is similar to my own project code.
When i run it it says UnboundLocalError: local variable 'score' referenced before assignment. Can anyone fix it.
score = 0
def Random_Thing():
Random_Text = input("Random Text")
if Random_Text == "Hello":
score = score + 1
print(score)
def Random_Thing_2():
Random_Text_2 = input("Random Text 2")
if Random_Text_2 == "Hello2":
score = score + 1
print(score)
Random_Thing()
Random_Thing_2()
print(score)
When you define score = 0 at the top, it is in the global scope for the file. By default, functions have only read access to global variables. You cannot change them. Therefore print(score) would work inside a function. But score=score+1 would not.
If you want to change global variable(s) from inside a function, do global var1, var2... at the begining of the function. For your code, you need to do
def Random_Thing():
global score
#your code
def Random_Thing_2():
global score
#your code

Name 'variable' is not defined after implementing 'global variable' inside the function

I am currently working on my first program on python, however, when I've encountered a problem concerning the scope of definition of my variables. Here is the problematic sample of my code :
def listen(topLeft, bottomRight):
timeless = 0
# The key combination to check
COMBINATIONS = [
{keyboard.Key.shift, keyboard.KeyCode(char='b')}
]
# The currently active modifiers
current = set()
def execute():
global topLeft,bottomRight,timeless
print("Do Something")
if timeless == 0:
topLeft = mouse.position
timeless += 1
elif timeless == 1:
bottomRight = mouse.position
timeless += 1
elif timeless >= 2:
return False
def on_press(key):
global timeless
if any([key in COMBO for COMBO in COMBINATIONS]):
current.add(key)
if any(all(k in current for k in COMBO) for COMBO in COMBINATIONS):
execute()
def on_release(key):
if any([key in COMBO for COMBO in COMBINATIONS]):
current.remove(key)
with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
listener.join()
Basically, once the Listener calls on_press, execute is called. In order to pass the timeless variable, I use the global tag. However, once the program comes to executing the execute function, I receive the following error code : NameError: name 'timeless' is not defined.
Any help would be appreciated, as I have tried pretty much everything I could
Since timeless is actually a local variable in the function listen, it's not a global variable, and in fact your error comes from the fact that there is no global variable named timeless. What execute needs is to declare timeless (and probably topLeft and bottomRight as well) as nonlocal, so that it refers to the first binding in the stack of containing lexical scopes.
def listen(topLeft, bottomRight):
timeless = 0
# The key combination to check
COMBINATIONS = [
{keyboard.Key.shift, keyboard.KeyCode(char='b')}
]
# The currently active modifiers
current = set()
def execute():
# modify the local variables in listen
nonlocal topLeft,bottomRight,timeless
print("Do Something")
if timeless == 0:
topLeft = mouse.position
timeless += 1
elif timeless == 1:
bottomRight = mouse.position
timeless += 1
elif timeless >= 2:
return False
...
In a function defined at the global scope, global and nonlocal are identical, as the first containing scope is the global scope. In a nested function, global jumps straight to the global scope, while nonlocal walks up the nesting scopes one at a time.
You declare a global variable outside of any function. You can reference a global variable inside a function without using the keyword. You only need to use the keyword global when you are assigning a new value to the variable, sort of as a way of specifying that you want to assign the value to the global variable and not to a new local variable that shares the same name. See this for examples. For your example, first define your globals outside of any function, then use them in the functions, using the global keyword when you want to modify:
# Global variable definitions outside of any function.
timeless = 0
topLeft = 0
bottomRight = 0
# Define the function that uses the variables.
def execute():
print("Do Something")
global timeless
if timeless == 0:
global topLeft # modifying the global variable with this name!
topLeft = mouse.position
timeless += 1
elif timeless == 1:
global bottomRight # modifying the global variable!
bottomRight = mouse.position
timeless += 1
elif timeless >= 2:
return False
All of that said, it's probably best to avoid globals in general. You could define a class instead and use a member property for those things that need to be modified and referenced in multiple methods. For example, something like:
class Listener:
def __init__(self):
self.timeless = 0
self.top_left = 0
self.bottom_right = 0
def execute(self, mouse): # pass some mouse object in, otherwise what's "mouse"?
print('Do something')
if self.timeless == 0:
self.top_left = mouse.position
self.timeless += 1
elif self.timeless == 1:
...
timeless = 0
topLeft = 0
bottomRight = 0
current = set()
def listen(topLeft, bottomRight):
timeless = 0
# The key combination to check
COMBINATIONS = [
{keyboard.Key.shift, keyboard.KeyCode(char='b')}
]
# The currently active modifiers
current = set()
def execute():
print("Do Something")
if timeless == 0:
topLeft = mouse.position
timeless += 1
elif timeless == 1:
bottomRight = mouse.position
timeless += 1
elif timeless >= 2:
return False
def on_press(key):
if any([key in COMBO for COMBO in COMBINATIONS]):
current.add(key)
if any(all(k in current for k in COMBO) for COMBO in COMBINATIONS):
execute()
def on_release(key):
if any([key in COMBO for COMBO in COMBINATIONS]):
current.remove(key)

List returns value none within code

creates variable sin order for me to recall them later.
def initialise():
global num
global neg
global pos
global pos_list
global neg_list
global pos_sum
global neg_sum
pos_sum=0
neg_sum=0
num=1
neg=0
pos=0
pos_list=[]
neg_list=[]
print("type your numbers")
listing()
Allows the user to repeatedly list positive or negative numbers until they use '0'
def listing():
global num
global neg
global pos
global pos_list
global neg_list
global neg_sum
global pos_sum
num=1
try:
num=float(input())
float(num)
if num<0:
neg_list.append(num)
neg+=1
neg_sum+=num
listing()
elif num>0:
pos_list.append(num)
pos+=1
pos_sum+=um
listing()
else:
end()
except ValueError:
listing()
this ends the code and creates a simple table for the user to view.(I always make tables like this as I find it easier this way and I know there are table functions but I am at school and they do not have the necessary libraries
def end():
global pos_list
global neg_list
global neg_sum
global pos_sum
global neg
global pos
pos_list=pos_list.sort()
neg_list=neg_list.sort()
total_sum=pos_sum+neg_sum
print(" "*33,"Positive"," "*(50-len('positive')),"Negetive"," "*(50-len('negetive')))
i1=0
i2=0
if len(pos_list)>=len(neg_list):
count=len(pos_list)
elif len(pos_list)<len(neg_list):
count=len(neg_list)
else:
pass
for x in range(count):
print("number"," "*(50-len('number')-len(count)),pos_list[i1]," "*(50-len(pos_list[i1])),neg_list[i2]," "*(50-len(neg_list[i2])))
i1+=1
i2+=1
print("amount of numbers"," "*(50-len('amount of numbers')),pos," "*(50-len(pos)),neg," "*50-len(neg))
print("total"," "*(50-len('total')),pos_sum," "*(50-len(pos_sum)),neg_sum," "*(50-len(neg_sum)))
initialise()
the problem:
NameError: global name 'pos_list' is not defined
occurs here:
if len(pos_list)>=len(neg_list):
but I can see this happening 3-4 lines after as well.

Categories

Resources