0

I have this code:

secret_word = "secretword"
guess = ""

def askForGuess():
    guess = input("Introduce the secret word :")
    print(guess,secret_word)
    

while guess != secret_word:
    askForGuess()
    

 
print("You've won!")

If I call askForGuess() inside the while statement it will never print 'You've won!' not even if I introduce the secret word correctly. However, if I just simply paste askForGuess() code inside of the while statement it works. Does anyone know why?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
midt23 Fr
  • 3
  • 1
  • 1
    You have two _different_ variables named `guess`. One is global, and one is a local variable inside the function. Changing the local one has no effect on the global one. If you want to use the global variable inside the function, put `global guess` at the top of the function so it knows to use the global one. – John Gordon Dec 28 '20 at 22:37

3 Answers3

2

As abe said, it is because there are two variables called guess in the two scopes.

Since the use of globals is not considered good code, my implementation of this would be:

secret_word = "secretword"
guess = ""

def askForGuess():
    guess = input("Introduce the secret word :")
    print(guess,secret_word)
    return guess

while guess != secret_word:
    guess = askForGuess()
    

 
print("You've won!")
Lyndon Gingerich
  • 604
  • 7
  • 17
ereldebel
  • 165
  • 11
1

Assigning some value to guess in the scope of your function askForGuess() doesn't change the value of the global variable guess, that's why you never get out of the loop.

abe
  • 957
  • 5
  • 10
0

What basically happens here is that the guess inside the loop is a new variable and not the one that the while loop checks. This is due to the fact that the guess variable in line 2 has not be declared as global. The following code should work

secret_word = "secretword"
global guess
guess = ""


def askForGuess():
    global guess
    guess = input("Introduce the secret word :")
    print(guess, secret_word)


while guess != secret_word:
    askForGuess()

print("You've won!")

Hope the above helps, well done for the well explained question.

RafD
  • 65
  • 1
  • 8