0

I have a function which has an if statement and asks for user input.

def my_function():
    answer = input(";")
    if condition 1
        a = 1
    else
        a = 0

I then want to run the function like so ''' my_funnction() ''' Then I want to extract the value of a based on the outcome of the function. When I try to do this it says the variable is undefined. When I define the variable, a, outside the function then its value doesn't change. How can I have the value of my variable be extracted from the function?

quamrana
  • 37,849
  • 12
  • 53
  • 71
Jemster456
  • 21
  • 1
  • 4
    Return it from the function. A variable is local, by definition. Or put your function inside a class and declare the variable as an instance attribute of the class. – Óscar López Oct 08 '22 at 10:32
  • You define the variable `a` and give it a value, but like all variables defined inside functions you throw it away (along with its value) once the function terminates. You can return values from functions using `return`, but the names of variables remain inaccessible. – quamrana Oct 08 '22 at 10:36
  • Do you want to return the input value or only return `a` based on input was true or false? – Arifa Chan Oct 08 '22 at 10:39

2 Answers2

1

Nobody has access to function's local namespace. a is only accessible during the execution of the my_function.

You should return the value from the function and then do whatever you want with it later:

def my_function():
    answer = input(";")
    if condition 1
        a = 1
    else:
        a = 0
    return a

a = my_function()

Another solution which I don't recommend is using global keyword:

def my_function():
    global a
    if True:
        a = 1
    else:
        a = 0

my_function()
print(a)

By saying so, you make changes in global namespace. That's why you can access it later. (You don't have to define it in global namespace first)

However with a simple search you can find hundreds of articles like this about why using global variables is not recommended and why functions should be isolated.

S.B
  • 13,077
  • 10
  • 22
  • 49
0

Here is the easiest way.

def my_function():
    answer = input(";")

    if condition 1
        my_function.a = 1 #just add the function name to the variable
    else
        my_function.a = 0 #here also

Then

print(my_function.a)
UNK30WN
  • 74
  • 7