0
name = "Aayan"

def AI():
    print("Hi, {}. I hope you are doing well :)".format(name))
    ask = input("How can i help you, {} ? : ".format(name))
    if ask == "change name" or "rename":
        new_name = input("What should I call you ? : ")
        name = new_name
    else:
        exit()

AI()

It throws UnboundLocalError: local variable 'name' referenced before assignment. How can I update name after asking it from the user ?


AaYan Yasin
  • 566
  • 3
  • 15
  • 1
    You should return the value from the function with `return name` and call the function with `name = AI()` so you rebind `name` in the outer scope. Don't use `global`. Never use exit. To cite the documentation of [`exit`](https://docs.python.org/3/library/constants.html?highlight=exit#exit) (and `quit`): "They are useful for the interactive interpreter shell and should not be used in programs." – Matthias Jun 11 '21 at 12:45
  • Does this answer your question? [UnboundLocalError on local variable when reassigned after first use](https://stackoverflow.com/questions/370357/unboundlocalerror-on-local-variable-when-reassigned-after-first-use) – joanis Jun 11 '21 at 13:02

1 Answers1

0
name = "Aayan"

def AI():
    global name
    print("Hi, {}. I hope you are doing well :)".format(name))
    ask = input("How can i help you, {} ? : ".format(name))
    if ask == "change name" or "rename":
        new_name = input("What should I call you ? : ")
        name = new_name
        return name
    else:
        exit()


print(AI())

use global keyword inside function and call name

Rishabh Semwal
  • 328
  • 1
  • 3
  • 12