是否有一个命令,以便当某个东西比答案少3或3个时它会做什么?

时间:2014-10-16 21:30:01

标签: python random numbers generator

我正在制作一个随机数字猜谜游戏,我想知道当你的猜测小于或小于答案时,它会打印出类似“关闭!答案是(答案)”

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

(我有打印“”以在每个循环之间留出空格)

2 个答案:

答案 0 :(得分:5)

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)

如果猜测值低于或低于数字3,则只需获取absolute value abs(number-guess),这将涵盖两种情况。

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

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

答案 1 :(得分:2)

更简单地说,使用链式条件

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