Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 Python 3 Global Variable Help
#1
Hi, I'm just learning python and I'm still an absolute beginner, but I've decided to try my hand at a choose your own adventure game.
My goal is to to create a new global variable within a function in order to call it while outside of that function.
I've tried a few things but I'm stuck. I introduce the global variable on line 101. My check is the last line of the code.

The game is working fine as of so far, but any information on getting started for my code that is commented out would also be appreciated



def playagain():
    answer = input('Play again? Y or N')
    if answer == "Y":
        print('Goodluck!')
        levelone()
    else:
        print('Goodbye!')


def get_user_input():
    """Prompts the user for its choice and return it."""
    user_input = input('Choose: ').lower().strip()
    return user_input
def replay():
    user_input = input('Play again Yes/No: ').lower().strip()

    if user_input == 'yes':
        print('_' * 100)
        levelone()
    elif user_input == 'no':
        print('thanks for playing!')
        print("That's all for now")
       
        

# class item():
#     def __init__(self, name, description,value)

# class weapon():
# def health():
# class armour():
# class player():
# class inventory():
# def combat():
# class gold():



def levelone():
    waiting_for_input = True
    print('Welcome to your adventure.')
    print('Are you ready? yes/no')
    print('1 for yes')
    print('2 for no')

    while waiting_for_input:
        user_input = get_user_input()
        if user_input == '1':
            print('_'*100)
            print('Alright, Lets Begin')
            break
        elif user_input == '2': 
            print('_'*100)
            print('Maybe later')
            waiting_for_input = False
            break
    while waiting_for_input:
        print('_'*100)
        print('You awaken to find youself in a dimly lit cavern, beside you lies a sword and a shield ')
        print('do you want to pick them up')
        print('1 for yes')
        print('2 for no')
        break
    while waiting_for_input:
        user_input = get_user_input()

        if user_input == '1':
            print('_'*100)
            print('You stand up, dust yourself off while trying to ignore your throbbing head, grab the weapons on the ground,')
            print('look around and see a door ajar.')
            break
        elif user_input == '2':
            print('_'*100)
            print('You stand up, dust yourself off while trying to ignore your throbbing head, ')
            print('look around and see a door ajar.')
            break
    while waiting_for_input:
        print('What shall you do?')
        print('1: Go through the door')
        print('2: Search the room')
        break
    while waiting_for_input:
        user_input = get_user_input()

        if user_input == '1':
            print('_'*20)
            print('As you open the door you see 5 people standing around a long table filled with maps')
            print('in the center of the table stands a tall, burly man, he notices you enter the room and the men fall silent')
            print("Looking up from the maps, he looks and you and says, ' Glad to see you are finally awake, what's your name?")
            your_name = input('your name: ')
            character_name = "Hello, {}, welcome to the Gryphon's den, do you remember anything before you got here?".format(your_name)
            print(character_name)
            break
        elif user_input == '2':
            print('_'*20)
            print('You search the room and find nothing of but some cobwebs and dirt.')
            print('You decide to go through the door and meet your fate.')
            print('As you open the door you see 5 people standing around a long table filled with maps')
            print('in the center of the table stands a tall, burly man. He notices you enter the room and the men fall silent')
            print("Looking up from the maps, he looks and you and says, ' Glad to see you are finally awake, what's your name?")
            global name
            name = input('your name: ')
            line = "Hello, {}, welcome to the Gryphon's den, do you remember from anything before you got here?".format(name)
            print(line)
            break
        



# Start Game

levelone()


replay()


print(name)
Error:
Traceback (most recent call last): File "c:/Users/Tridium/Documents/python/Adventure.py", line 118, in <module> print(name) NameError: name 'name' is not defined
Quote
#2
If you would do it this way
# Start Game
name = '' 
levelone()
print(name)
it would work BUT THIS VERY BAD CODE STYLE! DON`T DO IT THIS WAY! NEVER USE GLOBAL!

Define your functions to get parameters/arguments and RETURN variables that your other code need.
If you would change your last lines in your function levelone()
            # global name # or DELETE this line
            name = input('your name: ')
            line = "Hello, {}, welcome to the Gryphon's den, do you remember from anything before you got here?".format(name)
            print(line)
            return name
and would then call this function like
name = levelone()
print(name)
this would provide you with the name the user inputted.

BUT, and now it´s your turn: What is the value of name if your function is exited before the user inputs his name and how can you solve that?

BTW: the amount of BREAKs in your code is not pythonic. Rethink this also.
Quote
#3
ThomasL,

Thank you for your reply, I added the argument return line to the final line of function levelone(), and when I call it I still receive the error that name is undefined, I was able to solve this error on my own by moving global name to line 90 and fixing some issues where i forgot to rename some variables. While I realize this may be bad code ethics, i'm hoping it may be acceptable because name is something I want to stay constant throughout the game.

global name
name = input('your name: ')
character_name = "Hello, {}, welcome to the Gryphon's den, do you remember anything before you got here?".format(name)
print(character_name)
break
Quote
#4
I would choose a better layout.
Example
def get_user_input(allowed=[], message='Choose: '):
    while True:
        user_input = input(message).lower().strip()

        if user_input in allowed:
            return user_input
        elif user_input in ['quit', 'exit']:
            print("Bye for now\n")
            exit()
        else:
            print('Try again')

def levelone_begin():
    print('Welcome to your adventure.')
    print('Are you ready? yes/no')
    print('1 for yes')
    print('2 for no')
    user_input = get_user_input(['1', '2'])

    if user_input == '1':
        print('_' * 100)
        print('Alright, Lets begin')
        return levelone_awake
    elif user_input == '2':
        print('_' * 100)
        print('Maybe later\n')
        exit()

def levelone_awake():
    print('_'*100)
    print('You awaken to find youself in a dimly lit cavern, beside you lies a sword and a shield ')
    print('do you want to pick them up')
    print('1 for yes')
    print('2 for no')
    user_input = get_user_input(['1', '2'])

    if user_input == '1':
        print('_'*100)
        print('You stand up, dust yourself off while trying to ignore your throbbing head, grab the weapons on the ground,')
        print('look around and see a door ajar.')
    elif user_input == '2':
        print('clooock')
        return levelone_awake

def main():
    while True:
        question = levelone_begin
        while question:
            question = question()

        user_input = get_user_input(['y', 'n', 'yes', 'no'], 'Play Again? Y or N: ')
        if user_input == 'N':
            print ('Goodbye!')
            exit()

        print('Goodluck!\n')

main()
99 percent of computer problems exists between chair and keyboard.
hobby-programmer.com
Quote
#5
(Jul-28-2019, 07:49 AM)Tridium Wrote: I added the argument return line to the final line of function levelone(), and when I call it I still receive the error that name is undefined

Did you call your function levelone() like this after adding "return name"?
name = levelone()
print(name)
Quote
#6
(Jul-28-2019, 06:48 PM)ThomasL Wrote:
(Jul-28-2019, 07:49 AM)Tridium Wrote: I added the argument return line to the final line of function levelone(), and when I call it I still receive the error that name is undefined
Did you call your function levelone() like this after adding "return name"?
name = levelone() print(name)

I did not, but I was able to solve this by realizing I was using this in the '2' input instead of the '1' input and in my tests i was inputing '1'

And to answer your question, I'm not sure I understand. From what I believe, they would not be able to break out of that loop before answering that question, unless they close the program, since all options currently bottleneck into that situation. ButI was not calling
name = levelone()
print(name)
, but now that i know this, i will probably rework my code to include that.

Also, I'm reworking the code to be more 'Pythonic', but I'm a complete beginner trying to use no guides and only google things when i need more information and I'm learning everything as I go since as of 2 days ago, I had never before done any coding.

All of my work is completely original, and I'm proud of that and i'm thankful for your help.
Yoriz likes this post
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  Using Time to Update a Global Variable and Label in TkInter cameron121901 5 514 Apr-22-2019, 05:08 PM
Last Post: SheeppOSU

Forum Jump:


Users browsing this thread: 1 Guest(s)