1

So I'm trying to write a code and here's a small snippet of it in which I'm getting a problem where the value of a remains 0.

a=0

def add(x,y):
    return x+y
    
def mains():
    if True:
        a=add(10,20)
        print(a)
mains()

Its working now.

Anirudh
  • 61
  • 6
  • 2
    You are not calling any of the functions. – Cow Feb 24 '22 at 09:41
  • 1
    As @user56700 said: You need to call your mains function and then this: Does this answer your question? [Using global variables in a function](https://stackoverflow.com/questions/423379/using-global-variables-in-a-function) – Ocaso Protal Feb 24 '22 at 09:43
  • Call the mains() function and if you wanna modify the value of "a" then you also need to write "global a" in the mains function. Otherwise it won't change the value of a – gajendragarg Feb 24 '22 at 09:43

3 Answers3

3

Morning,

Firsly, as a is outside of a function, you need to define within the function that you are using a global variable:

This would look like this:

def mains():
   global a #Lets the function know the variable is already defined outside the scope
   if True:
      a=add(10,20)

Secondly, I'm not sure how your function is set up but you actually need to call the function mains() for it to run that function.

This code works for me:

a=0

def add(x,y):
    return x+y
    
def mains():
   global a #Lets the function know the variable is already defined outside the scope
   if True:
      a=add(10,20)

mains()
print(a)
Joshua
  • 588
  • 1
  • 5
  • 19
1

Firstly you must call your function before it will do anything, secondly to alter a from within your function you need to use a as a global variable

a=0

def add(x,y):
    return x+y
    
def mains():
    global a
    if True:
        a=add(10,20)

mains()
print(a)
Patrick
  • 1,189
  • 5
  • 11
  • 19
1

mains() is a function, and must be called in order to execute. Moreover, you need to make sure that your function can find a. To do this, use the global keyword.

a=0

def add(x,y):
    return x+y
    
def mains():
    global a  # find a
    if True:
        a=add(10,20)

mains()  # run the function
print(a)

Read more: https://docs.python.org/3/faq/programming.html#what-are-the-rules-for-local-and-global-variables-in-python

eccentricOrange
  • 876
  • 5
  • 18