I am making a random number guessing game and I was wondering if when your guess is 3 less than or more than the answer it would print something like "Close! The answer was (the answer)"
import random
while True:
dicesize = raw_input('What size die do you want to guess from?>')
number = random.randrange(1, int(dicesize))
guess = raw_input('What is your guess?>')
if int(guess) == number:
print 'Correct!'
print " "
# less than 3 print "close"?
# more than 3 print "close"?
else:
print 'Nope! The answer was', number
print " "
(I have the print " " to make a space between each of the loops)
while True:
dicesize = raw_input('What size die do you want to guess from?>')
number = random.randrange(1, int(dicesize))
guess = int(raw_input('What is your guess?>'))
if guess == number:
print('Correct!')
print(" ")
elif abs(number-guess) < 3:
print("Close")
else:
print('Nope! The answer was', number)
Just get the absolute value abs(number-guess)
, which will cover both cases, if the guess is less than 3 above or below the number.
In [1]: abs(10-7)
Out[1]: 3
In [2]: abs(7-10)
Out[2]: 3
More simply, use chained conditionals
if number-3 < guess < number+3:
print("Close")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With