Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a command so that when something is 3 less than or 3 more than the answer it would do something?

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)

like image 796
Joshkinz Avatar asked Mar 18 '23 04:03

Joshkinz


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 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
like image 173
Padraic Cunningham Avatar answered Mar 26 '23 01:03

Padraic Cunningham


More simply, use chained conditionals

if number-3 < guess < number+3:
    print("Close")
like image 33
Veedrac Avatar answered Mar 26 '23 01:03

Veedrac