0

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)
Thierry Lathuille
  • 23,663
  • 10
  • 44
  • 50
infinityPK
  • 53
  • 5

3 Answers3

2

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.

Green05
  • 319
  • 1
  • 8
1

there is no position variable outside the function, so the code cannot recognize it. You must print(user_input()) at the end of your code to have the result you want, or more clearly you can assign the result of user_input() to a variable and print it

x=user_input()
print(x)
IoaTzimas
  • 10,538
  • 2
  • 13
  • 30
1

You cannot access the variable position outside of the function due to its limited scope. The scope of the variable is within the function user_input() and it can only be accessed within it. To access it outside you need to do something like:

position = user_input() 

print(position)
Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
Dhruv Awasthi
  • 149
  • 1
  • 4