Search code examples
pythonfunctionreturn

return function not saving the value and later u call the variable it says variable not define


I'm writing a function in Python where I take user input and validate it. Later I'm saving it to a variable using return. But after calling the variable, it says variable not defined.

def user_input():
    
    position = 'wrong'
    position_range = range(1,10)
    within_range = False
    
    while position.isdigit == False or within_range == False:
        
        position=input('select the postion from (1-10): ')
        
        if position.isdigit()==False:
            print('hey! thats not a valid input')
            
        elif position.isdigit()==True:
            if int(position) in position_range:
                within_range=True
            else:
                print('hey! thats out of range')
                within_range=False
        
    return int(position)

user_input()

print(position)

Solution

  • The way return works is that you can do the following:

    variable = function()
    

    And whatever function() returns, will be assigned to the variable. You should do the following:

    position = user_input()
    print(position)
    

    By the way, I would recommend using a different name for position, as it is also used inside the function, but because that position was defined inside the function, it exists only in the function's scope, and is different from the position outside. As such, you should name them differently.