Python Forum

Full Version: Simple Question for Most - Help Explain Please
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello. I am taking a basic class and running their code. (This is my first time posting on this forum). My question is: Why do I need to use the first line "number_guess="0"" when running this code? The results are the same when I don't use it?

#number_guess="0"
secret_number="5"

while True:
    number_guess = input("guess  the number 1 to 5: ")
    if number_guess == secret_number:
        print("Yes." , number_guess, " is correct!\n")
        break
    else:
        print(number_guess, " is incorrect")
you are right - as the code is at the moment you don't need it
In this particular case there is no difference, you don't need that first line with number_guess.
Thank you both for answering. Is there a short answer as to when I might need to use the number_guess-"0" line?
If you would not be assigning a value to that variable in each iteration, you would need it defined outside loop - same as you already do with secret_number variable.

Originally posted, but is incorrect, as pointed out by buran:
Thank you for the reply. I understand and am grateful for the response.
(Jan-27-2018, 04:13 PM)j.crater Wrote: [ -> ]Since after the loop finishes, variable is out of scope and thus rest of the code cannot access it.
the loop does not create/represent its own namespace/scope - variable number_guess is accessible/available after the loop...
You are right, I just checked, thanks for pointing out! I may as well delete it from my post to not confuse the OP or at least any future reader. Apologies for the misinformation.
You guys are awesome! Thanks so much