Attempting to generate different responses based on closeness of guess to the randomly generated number. Commented out sections are my attempts at generating a different response for a guess that is within 10 numbers of the random number.
import random
while True:
number = random.randint(1,1000)
guess = 0
tries = 0
while guess != number:
guess = input('Please enter your guess, number must be between 0 and 1000: ')
tries += 1
if guess < number:
if number - 10 <= guess:
print('Getting warm but still too low!')
print('Too Low!')
elif guess > number:
if number + 10 >= guess:
print('Getting warm but still too high!')
print('Too High!')
print("Great Guess! The number was %i and you guessed it in %s tries!") % (number, tries)
again = raw_input("Enter 'y' or 'n' to select to play again: ")
if again == 'n':
break
Yields the below output when within the specified range of the randomly generated number.
Please enter your guess, number must be between 0 and 1000: 256
Getting warm but still too low!
Too Low!
Please enter your guess, number must be between 0 and 1000: 257
Great Guess! The number was 257 and you guessed it in 13 tries!
The problem is due to indentation, as a beginner you should see how basic nested loop work. The code after indentation will yield the correct result. I have added an additional else to handle print "Too Low" and "Too High"
import random
while True:
number = random.randint(1,1000)
guess = 0
tries = 0
while guess != number:
guess = input('Please enter your guess, number must be between 0 and 1000: ')
tries += 1
if guess < number:
if number - 10 <= guess:
print('Getting warm but still too low!')
else:
print('Too Low!')
elif guess > number:
if number + 10 >= guess:
print('Getting warm but still too high!')
else:
print('Too High!')
else:
print("Great Guess! The number was %i and you guessed it in %s tries!") % (number, tries)
again = raw_input("Enter 'y' or 'n' to select to play again: ")
if again == 'n':
break
The problem is because the condition of the first 'if clause' is met first, the others condition will be ignored. You could re-arrange the if clause to show the message as you want:
if number - 10 <= guess:
print('Getting warm but still too low!')
elif guess < number:
print('Too Low!')
elif number + 10 >= guess:
print('Getting warm but still too high!')
elif guess > number:
print('Too High!')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.