Search code examples
pythonfunctionreturncall

Call function and return a value


I've got the following code:

def checkUserId(userID):
    if userID < 1 or userID > 10:
        print(userID)
        print("You did not enter a valid ID number. Try again.")    
        userID = int(input("Enter your ID number."))
        print(userID)
        checkUserId(userID)
    else:
        return userID

userID = 0
while userID != "shutdown":
    userID = int(input("Enter your ID number."))
    checkUserId(userID)
    print(userID)

All I'm wanting to do is check if the userID is between 1 and 10. If it is, then we continue. But for some reason, when the function is called and does the check, the value of userID(now entered correctly) is not returned. Instead, the original invalid value, the one entered before the function call, is used. If the user enters '11', '11' will still remain the userID value after the function call. Just run it to see what I mean. Thanks for any assistance.


Solution

  • There were two UserID variable in your code and in case of value not between 1 to 10 you were not returning the UserID value, hence it was printing the old value in while loop.

    you can use below simplified code.

    def checkUserId(user_id):
        if user_id < 1 or user_id > 10:
            print(user_id)
            return "You did not enter a valid ID number. Try again."
        else:
            return user_id
    
    user_id = 0
    while True:
        user_id = input("Enter your ID number.")
        if user_id == 'shutdown':
            break
        ret_user_id = checkUserId(int(user_id))
        print(ret_user_id)