Rose
Rose

Reputation: 127

Why is the variable not updated? Function problem

Trying to use functions for the first time! But I'm having a problem with the variables. Why is it not updated?

def errorcheck(var):
        while (var != "y" and var != "n"):
                var = input("\nError. Input Y or n only. Enter again:\n-> ").lower() #gives user a choice on what directory
        return var

def getdirectory():
    print("\nCurrent directory is: " + os.getcwd()) #print current directory
    choice2 = input("\nRename files in current directory? Y or n:\n-> ").lower() #gives user a choice on what directory
    errorcheck(choice2)
    print("Choice 2 is now:" + choice2)

I'm expecting choice 2's value will change after errorcheck but choice 2 is still the same value as what was inputted before the errorcheck.

Rename files in current directory? Y or n:
-> hello

Error. Input Y or n only. Enter again:
-> n
Choice 2 is now: hello

What's wrong with this?

Upvotes: 1

Views: 30

Answers (1)

ObsoleteAwareProduce
ObsoleteAwareProduce

Reputation: 756

When the errorcheck function returns a value, you're not using it. Change the second function to:

def getdirectory():
    print("Choice 2 is now:" + errorcheck(choice2))
    choice2 = input("\nRename files in current directory? Y or n:\n-> ").lower()
    choice2 = errorcheck(choice2) #Update choice2
    print("Choice 2 is now:" + choice2)

Functions can't change the values of variables outside of them. In some other languages, you can do this with pointers, but Python cannot use these. To do that, you have to return the value, then update the variable with the return value.

Upvotes: 1

Related Questions