Pygame beginner programs, screen undefined - python

AMOUNT = 1
x = 175
y = 175
def main():
screen = pygame.display.set_mode((600,600))
screen.fill( (251,251,251) )
BoxAmountCalc(humaninput)
DrawBoxCalc()
pygame.display.flip()
while True:
for event in pygame.event.get():
if event.type == QUIT:
return
def BoxAmountCalc(x):
x = (2**humaninput) * (2**humaninput)
size = 600/x
return size
def DrawBoxCalc():
while True:
pygame.draw.rect(screen,(0,0,0), (x,y,size,size))
AMOUNT += 1
x = x + size
x = y + size
pygame.display.flip()
if AMOUNT > humaninput:
break
I've left out a few parts of the code, some of the variable definitions, but when I try to run this code it gives me an error saying that "screen" is not defined.
Is this because I need it to be defined as a parameter for the function and then pass it into the function, or am I missing something completely here?
Thank you for looking, I'm sorry for a very beginner question.

Is this because I need it to be defined as a parameter for the
function and then pass it into the function.
Yes. Once a function finishes executing, the variables created therein are destroyed. Here is an example:
def go():
x = 10
go()
print(x)
--output:--
Traceback (most recent call last):
File "1.py", line 5, in <module>
print(x)
NameError: name 'x' is not defined
Same thing here:
def go():
x = 10
def stay():
print(x)
go()
stay()
--output:--
File "1.py", line 9, in <module>
stay()
File "1.py", line 6, in stay
print(x)
NameError: name 'x' is not defined
But:
x = 10
def go():
print(x)
go()
--output:--
10
And better:
def go(z):
print(z)
x = 10
go(x)
--output:--
10
Try to keep your functions self contained, which means they should accept some input and produce some output without using variables outside the function.
In your code, you can do:
DrawBoxCalc(screen) and def DrawBoxCalc(screen):
but you also have an issue with humaninput. I would try to define DrawBoxCalc as DrawBoxCalc(humaninput, screen), and call it with both args. That means you will have to define main as main(humaninput).
Also, function names should start with a lower case letter, and python uses what is called snake_case for lower case names, so draw_box_calc, and class names should start with a capital letter and they can use camel case: class MyBox.

Related

Unsure on how to call this function within another function - Python

really sorry if someone has asked this before, i just couldn't find what i was looking for, I'm new to coding and aren't sure why i cant get 'matrice2x2mult' function to be called within 'runcalc'. However i suspect it is to do with me calling the function 'runcalc' at the bottom. Any help will be greatly appreciated. Once again sorry.
-I get the error message:
Traceback (most recent call last):
File "FILE_PATH", line 42, in <module>
query.runcalc(q)
File "FILE_PATH", line 19, in runcalc
matrice2x2mult()
NameError: name 'matrice2x2mult' is not defined
import time
class calculator():
def __init__(self, method):
self.method = method
def matrice2x2mult():
print("Matrix 1:")
a = input("a:")
b = input("b:")
c = input("c:")
d = input("d:")
print(f"({a} {b})\n({c} {d})")
def runcalc(self, method):
if self.method == "1":
print("yes")
matrice2x2mult()
elif self.method == "2":
pass
print ("welcome to matrice Calculator: \nEnter 'HELP' for help menu")
time.sleep(1)
q = input(r"What method is required:")
q = str(q)
help1 = False
while help1 == False:
if r"HELP" in str(q):
print("------help-menu------")
print("ENTER '1' FOR 2X2 MATRIX MULTIPLICATION")
print("ENTER '2' FOR A INVERSE OF A 2X2 MATRIX")
time.sleep(1)
q = str(input(r"What method is required:"))
break
else:
break
pass
query = calculator(q)
query.runcalc(q)```
[1]: https://i.stack.imgur.com/s6jud.png
Since matrice2x2mult is defined within calculator, and you're trying to access it via runcalc which is also defined within the same class, you need to use self.matrice2x2mult to access the function. The only way that using just matrice2x2mult would work is either if it was defined in global scope rather than just in that class, or if you did something like matrice2x2mult = self.matrice2x2mult which would be weird and not recommended.

Problem with accessing variable from function in another file

I need to get a variable declared in a function in another file.
Requirement is that I can't call the variable from setvar() function.
set.py:
def setvar():
global x
x = 100
def getvar():
return x
if __name__ == '__main__':
setvar()
getvar()
get.py:
import set
y = set.getvar()
print(y)
Error:
NameError: name 'x' is not defined
Why is x not defined? When I print it in getvar, x is defined.
How can I change it to get it work?
Why is x not defined?
The reason is because of your line:
if __name__ == '__main__':
As you know, that line means to only run the code within the if statement if the program is being run directly, rather than being imported into another program. As you are only importing the set.py program into the get.py program, the setvar() function never got called, hence the x variable never got defined.
Requirement is that I can't call the variable from setvar function.
That's not a problem! All you'll need to do is call the setvar() function outside of the if __name__ == '__main__': block once, and the problem would be fixed:
set.py:
def setvar():
global x
x = 100
def getvar():
return x
setvar()
if __name__ == '__main__':
getvar()
get.py:
import set
y = set.getvar()
print(y)
Output:
100

Getting a "Key Error: var_cheeze_value11"

I'm making a program that makes variables with a base name and variables like their id and series.
I use vars()[str(name+id+serie)] to make them and make it a button using the tkinter module.
When I launch it, it works until it tries to .get() the value from it, saying
keyError (variable name)
I tried to change how it's named, making it int() or moving the .get() here and there but nothing works.
# -*- coding: utf-8 -*
from tkinter import *
import math
import random
fenetre = Tk()
fenetre.geometry("1000x1000")
kanvas=Canvas(fenetre, width=500, height=500, bg="white")
id = 0
serie = 1
idcounter=0
while 1:
print("serie =",serie)
def cheezegrater():
global serie,id,idcounter
vars()[str("var_cheeze_sum"+str(serie))]=0
for o in range(1,val+1):
print("var11 =",var_cheeze_value11.get())
vars()[str("var_cheeze_sum"+str(serie))] += vars()[str("var_cheeze_value"+str(id-val+o)+str(serie))].get()
kanvas.pack()
fenetre.mainloop()
vars()[str("nombre_de_formes"+str(serie))] =int(float(input("combien?")))
val = vars()[str("nombre_de_formes"+str(serie))]
for o in range(1,val+1):
id+=1
vars()[str("var_cheeze_value"+str(id)+str(serie))] = Entry(kanvas, width=10)
o+=1
vars()[str("var_cheeze_value"+str(id)+str(serie))].pack
kanvas.pack()
fenetre.mainloop()
Traceback (most recent call last):
File "C:\Users\Utilisateur\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 1705, in __call__
return self.func(*args)
File "C:/Users/Utilisateur/.PyCharmEdu2019.1/config/scratches/scratch_1.py", line 38, in cheezegrater
vars()[str("var_cheeze_sum"+str(serie))] += vars()[str("var_cheeze_value"+str(id-val+o)+str(serie))].get()
KeyError: 'var_cheeze_value11'
You're inside a function and therefore outside of the same namespace where vars() doesn't contain those variables. Have a look at this example:
x = 1
print('Outside', x, 'x' in vars())
def f():
global x
print('Inside', x, 'x' in vars())
f()
It prints:
Outside 1 True
Inside 1 False
As you can see, even though we have global x and can print its value, it's not a key in vars() inside the function.
Also: Why are global variables evil?
Why did you choose to use vars() in the first place? Maybe you could just use a separate dict object instead? There's a lot of information in this question Python: Using vars() to assign a string to a variable
An improved version of the example from above might look like this:
data = {}
key = 'x'
data[key] = 1
print('Outside', data['x'], 'x' in data)
def f(data):
print('Inside', data['x'], 'x' in data)
f(data)
Of course, instead of 'x', you can use your own keys like str("var_cheeze_sum"+str(serie)).

Local variable not declared - cannot be fixed with any current stack solutions

I understand this is a question asked several times on here, but even after viewing and attempting to use all solutions on this site none fix my problem. Here is my code:
def trackMouse():
global x, y
x = 0
y = 0
x_max = 1000
y_max = 1000
keyboardEvent = evdev.InputDevice('/dev/input/event0')
mouseEvent = evdev.InputDevice('/dev/input/event1')
async def print_events(device):
async for event in device.async_read_loop():
if event.type == ecodes.EV_REL:
if event.code == ecodes.REL_X:
print("REL_X")
x += 1
if event.code == ecodes.REL_Y:
print("REL_Y")
y += 1
if event.type == ecodes.EV_KEY:
c = categorize(event)
if c.keystate == c.key_down:
print(c.keycode)
for device in keyboardEvent, mouseEvent:
asyncio.ensure_future(print_events(device))
loop = asyncio.get_event_loop()
loop.run_forever()
the error i get when running this loop is:
Task exception was never retrieved
future: .print_events() done, defined at etho.py:113> exception=UnboundLocalError("local variable 'a' referenced before assignment",)>
Traceback (most recent call last):
File "/usr/lib/python3.5/asyncio/tasks.py", line 239, in _step
result = coro.send(None)
File "etho.py", line 124, in print_events
if x += 1:
UnboundLocalError: local variable 'x' referenced before assignment
no matter where i assign the variable or declare it it will throw an error when i try to use it in an if statement or add to it, but not when i just set it equal to a number. I think it has something to do with the weird loop it is in.
print_events is treating x and y as local to itself, since they're modified inside the function and are not declared global inside the function. Since you want to modify them, you need to add declare them global inside print_events:
async def print_events(device):
global x, y
async for event in device.async_read_loop():
...
Note that passing them as arguments won't work since you want to modify them within the function and access the modified values outside the function.

python oop import - NameError confusion

I wrote some code that was meant to try to approach a target string by selecting randomly from a list of chars, but I have some problem that I do not quite understand.
import random
class MonkiesGo:
__chars = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
def __init__(self, targetString):
__targetString = targetString.lower()
__targetList = list(targetString)
__attemptList = []
__unmatchedIndexes = [ x for x in range(0, (len(targetString)-1)) ]
def attemptToSolve(self):
if len(__unmatchedIndexes) == 0:
__attemptString = ''.join(__attemptList)
return __attemptString, __targetString
else:
for index in __unmatchedIndexes:
__attemptList[index] = randomChar()
def updateSolutionProgress(self):
for indexCheck in __unmatchedIndexes:
if __targetList[index] == __attemptList[index]:
__indexToClear = __unmatchedIndexes.index(index)
del __unmatchedIndexes[indextToClear]
def __randomChar(self):
return __chars[ random.randint(0,26) ]
when I import it into a python shell in my terminal, make an object as follows:
from monkies import MonkiesGo
mk = MonkiesGo("hello")
mk.attemptToSolve()
I get the error:
Traceback (most recent call last):
File "", line 1, in
File "path/to/the/file/monkies.py", line 15, in attemptToSolve
if len(__unmatched 0: NameError: name '_MonkiesGo__unmatched' is not defined
What is causing this, and why is there an underscore before MonkiesGo?
THanks in advance.
Updated to:
import random
class MonkiesGo:
def __init__(self, targetString):
self.targetString = targetString.lower()
self.targetList = list(targetString)
self.attemptList = []
self.unmatchedIndexes = [ x for x in range(0, (len(targetString)-1)) ]
self.chars = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
def attemptToSolve(self):
if len(self.unmatchedIndexes) == 0:
self.attemptString = ''.join(self.attemptList)
return self.attemptString, self.targetString
else:
for index in self.unmatchedIndexes:
self.attemptList[index] = randomChar()
def updateSolutionProgress(self):
for indexCheck in self.unmatchedIndexes:
if self.targetList[index] == self.attemptList[index]:
indexToClear = self.unmatchedIndexes.index(index)
del self.unmatchedIndexes[indextToClear]
def randomChar(self):
return self.chars[ random.randint(0,26) ]
Now I get a name error regarding randomChar..?
You are not creating any instance variables. In the function __init__, variables such as __targetString are local and are defined only within the function. When you call the function attemptToSolve, the variable __unmatchedIndices is also local and therefore undefined. The double underscore does not automatically make an instance variable; perhaps that's your confusion.
Instead of __targetString = whatever, you should use self.__targetString = whatever, or better yet drop the underscores and use just self.targetString. That creates a member variable. Access it in member functions using the same self.targetString syntax. Check out the tutorial that comes with Python.

Categories