Lisa Ka
Lisa Ka

Reputation: 13

Python: Using a variable inside a function (but the variable should be users input)

I am trying to write a little hangman programme and I have to use this function in it (it is explicitly said in the assignment). It should check whether the guessed letter is in the word and if so, return a word consisting of *'s and guessed letter on the right position. Yet I don`t understand how can I use the "letter" variable if it is the one the user types in (his guess), so it is practically assigned outside the function. I am stuck a bit and I would be grateful if someone would say how to do it.

def print_guessed():
    global secret_word
    global letters_guessed
    word = []
    for i in range (0, len(secret_word)):
        if letter == secret_word[i]: word.append(letter)
        else: word.append('-')
    word_str = ''.join(word)
    return word_str

Upvotes: 0

Views: 134

Answers (3)

Ryan Haining
Ryan Haining

Reputation: 36802

EDIT if you're allowed to freely change the function, then just do

def print_guessed(letter):
    global letters_guessed
    letters_guessed.append(letter)
    return ''.join(c if c in letters_guessed else '-'
                   for c in secret_word)

OTHERWISE: this is quite a tricky problem given a function that doesn't even come close to doing the right thing, but I think I've figured it out!

secret_word = "answer"
letters_guessed = []
letter = ''

def fix_print_guessed(func):
    def wrapper(guess):
        global letters_guessed
        global letter
        letter = guess
        letters_guessed.append(letter)
        return func()
    return wrapper


@fix_print_guessed
def print_guessed():
    global secret_word
    global letters_guessed
    word = []
    for i in range (0, len(secret_word)):
        if letter == secret_word[i]: word.append(letter)
        else: word.append('-')
    word_str = ''.join(word)
    return word_str

found = len(secret_word) * '-'
while '-' in found:
    guess = raw_input('enter a letter: ')
    res = print_guessed(guess)
    found = ''.join(c1 if c1 != '-' else c2 
                    for c1, c2 in zip(found, res))
    print found

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 599610

Actually, though I agree with the commenters that this is terribly unPythonic code, you don't actually need to modify the function to make it work. letter is not assigned to within the function, which means that there's no need to declare it as global there: as long as it's defined in the outer scope, it will be accessible within.

Upvotes: 1

Aswin Murugesh
Aswin Murugesh

Reputation: 11070

I f you can make change to the function, then modify an argument to it, which is the variable-letter.

def print_guessed(letter):
    #do_stuff

And supply the letter guessed in the call statement

print_guessed(letter)

Upvotes: 2

Related Questions