Defining a variable in a function python

Question:

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?

Asked By: Jemster456

||

Answers:

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.

Answered By: S.B

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)
Answered By: UNK30WN
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.