Python won't keep value

def function():
    x = 0
    def ask():
            x = input("Pick X: ")
    ask()
    print(x)
function()

It returns this:

>>> 
================= RESTART: C:/Users/benmo/Desktop/example.py =================
Pick X: 3
0
>>> 

Can anyone explain to me why it prints 0 and not 3?

Short version, because the scope of x inside ask is local to ask and does not get returned to the calling main function, which has its own variable named x.

You need to return the value.

def function():
    def ask():
            return input("Pick X: ")
    x = ask()
    print(x)
function()

Something like this should work.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.