SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Y Daniel Lang
Chapter:
.loops
Exercise:
Check Point
Question:2 | ISBN:978013274719 | Edition: 6

Question

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") 

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

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
>>> 
0 0

Discussions

Post the discussion to improve the above solution.