如何让我的程序检查用户输入是否在随机整数的5,10,15,20等之内?

时间:2015-11-23 04:31:44

标签: python random

import random

print("Pick a number from 1-50")

randomNumber = random.randint(1,50)
correct = False

while not correct:
    try:
        userInput = int(input("Insert your number here. "))
    except ValueError:
        print("That is not a Number!")
        continue
    if userInput > randomNumber:
        print("Guess lower.")
    elif userInput < randomNumber:
        print("Guess Higher.")
    else:
        print("You got it!")
        break

因此,此代码当前接受用户输入并说明用户是否猜到了随机整数,或者是否应该猜测更高/更低。我想编辑代码,现在说明用户输入是否在随机整数的5,10,15等之内。

因此,如果随机整数是30,并且用户输入20,那么程序会说&#34;你在10以内;猜得更高。&#34;

有什么建议吗?我对python非常陌生,所以如果可能的话,请用更简单的方法回复。

感谢。

PS:哦,最好不要使用模块,主要是因为我还在学习。

3 个答案:

答案 0 :(得分:2)

我认为这可以满足您的需求,并且可以减少if链:

import random

print("Pick a number from 1-50")

randomNumber = random.randint(1,50)
correct = False

while not correct:
    try:
        userInput = int(input("Insert your number here. "))
    except ValueError:
        print("That is not a Number!")
        continue
    if randomNumber == userInput: # Let's check this first!
        print ("YOU WIN!!!")
        break # We use break b/c changing correct would still run rest of loop

    acceptable_ranges = [5, 10, 15, 20, 25, 30, 25, 40, 45, 50]
    guess_error = userInput - randomNumber
    i = 0
    while abs(guess_error) > acceptable_ranges[i]: # see how close they are
        i += 1
    if guess_error < 0: # let's figure out where they need to go
        next_guess_direction = "higher"
    else:
        next_guess_direction = "lower"

    print (("You are within %i: Please guess %s")
           %(acceptable_ranges[i], next_guess_direction))

我们来看看。在最后if语句中稍微进一步,最后print行。我们正在检查上面定义的guess_error(第15行)guess_error = userInput - randomNumber是否小于0(否定)。如果它小于零,那么我们使变量next_guess_direction等于字符串“higher”,因为下一个猜测需要大于最后一个(randomNumber大于{{1}如果userInput不是负数,那么它是正数,因为我们已经消除了我们消除0的可能性:

guess_error

因此,如果guess_error是肯定的,我们知道 if randomNumber == userInput: # Let's check this first! print ("YOU WIN!!!") 大于userInput,我们将randomNumber设置为等于字符串“lower”。最后,我们打印出我们发现的所有内容:

next_guess_direction

我使用的是较旧版本的格式,其中 print (("You are within %i: Please guess %s") %(acceptable_ranges[i], next_guess_direction)) %i分别是整数和字符串的占位符。然后我使用%s定义应该在那里格式化的内容,这只是意味着将%(acceptable_ranges[i], next_guess_direction)放入整数并将acceptable_ranges[i]放入字符串中。请注意,我们在if语句正上方的next_guess_direction中找到i

我知道这很长,但我不知道你需要多少细节!

答案 1 :(得分:1)

更新:我看到你要求在没有模块的情况下这样做。这是一个解决方案:

def ceil(xx):
    if int(xx) < xx:
        return int(xx) + 1
    else:
        return int(xx)

def generate_response(actual, guess, interval=5):
    diff_interval_units = (guess - actual) / float(interval)
    within = ceil(abs(diff_interval_units)) * interval
    response = "You are within %d" % within
    if diff_interval_units > 0:
        response += "; guess lower"
    elif diff_interval_units < 0:
        response += "; guess higher"
    return response

- 原始答案: 您可以使用numpy的ceil函数执行此操作。

例如:

import numpy as np

def generate_response(actual, guess, interval=5):
    diff_interval_units = (guess - actual) / np.float(interval)
    within = np.ceil(np.abs(diff_interval_units)) * interval
    response = "You are within %d" % within
    if diff_interval_units > 0:
        response += "; guess lower"
    elif diff_interval_units < 0:
        response += "; guess higher"
    return response

答案 2 :(得分:0)

使用modulo operator的解决方案:

import random
randomNumber = random.randint(0,100)

def guess(divisor = 5):
    while 1:
        try:
            print("Pick a number from 0-100")
            userInput = int(input("Insert your number here: "))
        except ValueError:
            print("That is not a Number!")
            continue

        delta = randomNumber - userInput

        if delta == 0:
            print("You got it!")
            return

        remainder = delta % divisor
        # this takes advantage of python truncating non-floating point numbers
        rounded_delta = (abs(delta) / divisor) * divisor + divisor * bool(remainder)

        high_or_low = 'higher' if delta > 0 else 'lower'
        print("You are within %s. Guess %s." % (rounded_delta, high_or_low))