Samson_
Samson_

Reputation: 1

NameError: global name 'category' is not defined

I am making a Hangman Game and having trouble. Ok every time I go to edit this and save my edits I get a red mark saying I need more details not just code so this is my more details. Please do not delete it or I cannot edit my post. :)

My error is,

"NameError: global name 'category' is not defined"

#Hangman Game V1 by (My name)

import random
import time

play_again = 'Yes'

#Categorys

animals = ['alligator', 'barracuda', 'cougar', 'cheetah', 'dolphin',      'falcon', 'gorilla', 'penguin', 'salmon', 'wombat']

olympics = ['archery', 'badminton', 'cycling', 'rowing', 'fencing', 'gymnastics', 'sailing', 'tennis', 'swimming',
            'volleyball']

countries = ['china', 'america', 'mexico', 'russia', 'sweden', 'canada', 'spain', 'korea', 'japan', 'france']


def intro():
    print ''
    print 'Welcome to Hangman by (My name)!'
    print ''
    print ''


def pick_category():
    category = raw_input('First, choose a category by typing in it\'s name. Your options are: Animals, Olympics, & '\
                         'Countries!')
    print ''
    print 'You chose the category ' + category + '.'
    return category

def choose_word():
    print ''
    print 'Now I will pick the secret word from your category.'
    print ''
    print '...'
    time.sleep(1)

    if category == 'Animals':
        secret_word = random.choice(animals)

    if category == 'Olympics':
        secret_word = random.choice(olympics)

    if category == 'Countries':
        secret_word = random.choice(countries)

    print ''
    print 'Alright, I have chosen the word!'
    #for testing purposes
    print secret_word

while play_again: intro() pick_category() choose_word()

Upvotes: 0

Views: 1435

Answers (1)

Ilja Everilä
Ilja Everilä

Reputation: 52997

You probably meant for category to be an argument of choose_word(). At the moment pick_category() returns the value of the local variable category, which is then ignored. Instead define choose_word() as:

def choose_word(category):
    ...

and pass the returned category to it, for example like this:

while play_again: 
    intro()
    # Passes the returned category as the argument
    choose_word(pick_category())

Upvotes: 1

Related Questions