pythonglobal-variablestext-based

Why is my global variable not working? (Python)


I am making a text-based game for school, and I want it to have a personalized name feature, but whenever I get past the function where the variable is defined, the other functions only use the original value, which is 0. Here's an example:

global name = 0 #this part is at the top of the page, not actually just above the segment
def naming();
 print("A long, long time ago, there was a person who was born very ordinary, but would live to become very extraordinary.\n")
  time.sleep(2)
  while True:
    name=input("Who are you? Give me your name.\n")
    choice = input(f'You said your name was {name}, correct?\n')
    if choice in Yes:
      prologue();
    else:
      return

def prologue():
  print(f'Very well, {name}. You were born with a strange gift that nobody could comprehend, at the time. You were born with the Favor of the Gods.')

This is the exact code segment I have, and when I hit "run", It works fine until def prologue(): I have ruled out the possibility that it is something else, because in the replicator window it says "undefined name 'name'"


Solution

  • This is a working example but isnt it better that you pass name to prologue function instead of using global variable? It is another subject but you have to avoid using global.

    import time
    
    name = 0 #this part is at the top of the page, not actually just above the segment
    def naming():
        global name
        print("A long, long time ago, there was a person who was born very ordinary, but would live to become very extraordinary.\n")
        time.sleep(2)
        while True:
            name=input("Who are you? Give me your name.\n")
            choice = input(f'You said your name was {name}, correct?\n')
            if choice == "Yes":
              prologue()
            else:
              return
    
    def prologue():
        global name
        print(f'Very well, {name}. You were born with a strange gift that nobody could comprehend, at the time. You were born with the Favor of the Gods.')
    
    
    if __name__ == '__main__':
        naming()