Why is my global variable not working? (Python)

258 views Asked by At

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'"

3

There are 3 answers

4
obayhan On BEST ANSWER

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()
5
chepner On

global is used inside a function to indicate that a name that would otherwise be treated as a local variable should be global instead.

def naming():
    global name

    ...

def prologue():
    print(f'Very well, {name}. ...')

As long as you don't call prologue before you call name, there is no need to initialize name in the global scope; the assignment inside naming is sufficient.


Also, you meant choice in ["Yes"] or, better yet,choice == "Yes"

1
Issac Abraham On

Remove global from name then it should work