What is wrong if guess is initialized to 0 in line 8 in Listing 5.3?
LISTING 5.3 GuessNumber.py
1 import random
2
3 # Generate a random number to be guessed
4 number = random.randint(0, 100)
5
6 print("Guess a magic number between 0 and 100")
7
8 guess = -1
9 while guess != number:
10 # Prompt the user to guess the number
11 guess = eval(input("Enter your guess: "))
12
13 if guess == number:
14 print("Yes, the number is", number)
15 elif guess > number:
16 print("Your guess is too high")
17 else:
18 print("Your guess is too low")
It would be wrong if it is initialized to a value between 0 and 100, because it could be the number you attempt to guess.
Executable code at guess = -1 :
import random
# Generate a random number to be guessed
number = random.randint(0, 100)
print("Guess a magic number between 0 and 100")
guess = -1
while guess != number:
# Prompt the user to guess the number
guess = eval(input("Enter your guess: "))
if guess == number:
print("Yes, the number is", number)
elif guess > number:
print("Your guess is too high")
else:
print("Your guess is too low")
Output:
Python 3.2.1 (default, Jul 10 2011, 21:51:15) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>>
Guess a magic number between 0 and 100
Enter your guess: 5
Your guess is too low
Enter your guess: 50
Your guess is too low
Enter your guess: 80
Your guess is too high
Enter your guess: 60
Your guess is too low
Enter your guess: 70
Your guess is too high
Enter your guess: 65
Your guess is too low
Enter your guess: 66
Your guess is too low
Enter your guess: 68
Yes, the number is 68
>>>