Python Forum
Simple Question for Most - Help Explain Please
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Simple Question for Most - Help Explain Please
#1
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")
Reply
#2
you are right - as the code is at the moment you don't need it
Reply
#3
In this particular case there is no difference, you don't need that first line with number_guess.
Reply
#4
Thank you both for answering. Is there a short answer as to when I might need to use the number_guess-"0" line?
Reply
#5
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:
Reply
#6
Thank you for the reply. I understand and am grateful for the response.
Reply
#7
(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...
Reply
#8
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.
Reply
#9
You guys are awesome! Thanks so much
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Simple question help me plz PedroGPT 4 4,586 Nov-07-2016, 08:19 PM
Last Post: nilamo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020