0

I was wondering if declaring a variable inside a function, then use it with an object would make it a global variable

def re():
    re.termine = False
    re.rect_circle_switch = True
    re.case1_disponible = True
    re.case2_disponible = True
    re.case3_disponible = True
    re.case4_disponible = True
    re.case5_disponible = True
    re.case6_disponible = True
    re.case7_disponible = True
    re.case8_disponible = True
    re.case9_disponible = True

if rect.rec_1.collidepoint(pos) and re.case1_disponible==True:
                if re.rect_circle_switch == True :
                    pygame.draw.line(fenetre,noir,(50,50),(150,150),10)
                    pygame.draw.line(fenetre,noir,(142, 56),(51, 145),10)
                    
                    re.rect_circle_switch = False

I assume that it will still be local after using it, but i don't really understand how scoping works in python

mark
  • 1
  • This post might help you. https://stackoverflow.com/questions/423379/using-global-variables-in-a-function/423596 – arulmr Oct 30 '20 at 03:23
  • 1
    If you are referring to `re`, you are not declaring it, there is in fact no declaration in Python, only assignations, it is a global variable. I am unsure what your question is beyond that. – Olivier Melançon Oct 30 '20 at 03:24
  • `re` is a global variable because the function definition `def re(): ...` *creates assigns the function object to the variable `re`*. The function then creates *attributes* on itself using the global name `re`. You *could* re-assign the global name re, and it would try to create attributes on whatever object you assign to that name. This code doesn't make a lot of sense. The code below your function in the global scope would actually throw attribute errors, because you've never actually called the function. – juanpa.arrivillaga Oct 30 '20 at 03:31

1 Answers1

0

In general variable declaration, variables inside function are local and others are global. But you can declare global variables inside function too, using global var_name before declaring it. Like:

def globalVarFunc():
  # declare global variable x
  global x
  x = 10
  # local variable y
  y = 20
Wasif
  • 14,755
  • 3
  • 14
  • 34