Reputation: 7
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!")
Upvotes: 1
Views: 153
Reputation: 77357
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: "))
Upvotes: 1
Reputation: 2415
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!
Upvotes: 0
Reputation: 5554
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.
Upvotes: 3