1

Hello I am a new programmer in the Python language. I was having trouble defining the variable user_guess because I was planning on defining it later in my program when the user inputs their answer. I later found the correct answer which is what the code below represents. My question is: If I introduce my variable, but plan on defining it later in my program, do I set it equal to 0?

user_guess = 0
magic_number = 5

while user_guess != magic_number:
    print("What is the magic number?")
    user_guess = int(input())

print("You have correctly guessed the magic number!")
  • `None` or `not magic_number` are both good values here =) – Cireo Dec 08 '20 at 00:09
  • 1
    Picking a tiny nit here: `input()` can take a prompt as an argument, so you don't need a separate `print(...)` before it. – Pranav Hosangadi Dec 08 '20 at 00:11
  • Excellent question generally, in this specific example there are other approaches to this https://stackoverflow.com/questions/743164/emulate-a-do-while-loop-in-python for reference – JeffUK Dec 08 '20 at 00:51

3 Answers3

3
user_guess = None

None is the value in Python that signifies a lack of a meaningful value. It's the best value to use when you must define a variable but have no real value to assign to it.

luther
  • 5,195
  • 1
  • 14
  • 24
1

It depends on how that variable is used later. In your case, you only define it early so that the while loop runs at least once. It could be anything except 5. 0 is okay but user_guess = None to hint that it needs to be filled in would be common.

If the variable has a reasonable default and is only changed sometimes, use that.

meaning_of_life = 42
if os.path.exists('meaning.txt'):
    meaning_of_life = int(open('meaning.txt').readline())

And if the variable is set unilterally, don't include a default

meaning_of_life = int(input("Give meaning: "))
tdelaney
  • 73,364
  • 6
  • 83
  • 116
0

import random

user_guess = []
magic_number = random.randint(1,10)

while user_guess != magic_number:
    print("What is the magic number?")
    user_guess = int(input())
print("You have correctly guessed the magic number! was " + str(magic_number) + " and you guessed it in " + str(user_guess) + " tries!")




You could also clear it with [] which sets it to nothing. You can set a random number with random.randint and shows how many tries you have taken to get the correct number!
Cohen
  • 2,375
  • 3
  • 16
  • 35