Is there a team, so when something is 3 less or 3 more than the answer, will it do something?

I am making a random number guessing game, and I was wondering if, when your guess is 3 less or more than the answer, it will print something like "Close! The answer was (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 a print "" to make a space between each of the loops)

+4
source share
2 answers
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 an absolute value that will cover both cases if the guess is less than 3 or less than the number. abs(number-guess)

In [1]: abs(10-7)
Out[1]: 3

In [2]: abs(7-10)
Out[2]: 3
+5
source

Simply put, use conventions

if number-3 < guess < number+3:
    print("Close")
+2

All Articles