简体   繁体   English

如何使程序检查用户输入是否在随机整数的5、10、15、20等范围内?

[英]How do I make my program check whether user input is within 5,10,15,20, etc of the random integer?

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

So this code currently takes the user input and says whether the user guessed the random integer, or if they should guess higher/lower. 因此,此代码当前接受用户输入,并说明用户是否猜测了随机整数,或者他们是否应该猜测较高/较低的值。 I want to edit the code to now say whether the user input is within 5,10,15, etc of the random integer. 我想编辑代码以说出用户输入是否在随机整数的5、10、15等范围内。

So if the random integer was 30, and the user inputs 20, the program would say something like "You are within 10; guess higher." 因此,如果随机整数是30,并且用户输入20,则程序将显示类似“您在10内;猜得更高”的字样。

Any advice? 有什么建议吗? I'm extremely new to python, so please respond with more simple methods if possible. 我对python非常陌生,因此请尽可能使用更简单的方法进行响应。

Thanks. 谢谢。

PS: Oh, preferably without the use of modules, mainly because I'm still learning. PS:哦,最好不要使用模块,主要是因为我还在学习。

I think this does what you want, and it cuts down on the if chains a little: 我认为这可以满足您的需求,并且可以减少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))

Let's look. 我们看看吧。 at the last if statement a little further and the final print line. 在最后if声明远一点,并最终print线。 We are checking to see if guess_error , defined above (line 15) guess_error = userInput - randomNumber is less than 0 (negative). 我们正在检查上面定义的guess_error (第15行)是否guess_error = userInput - randomNumber小于0(负数)。 If it is less than zero, then we make the variable next_guess_direction equal to the string "higher," because the next guess needs to be larger than the last one ( randomNumber was larger than userInput . If guess_error is not negative, then it is positive, because we already eliminated the we eliminate the possibility of 0 using: 如果它小于零,则使变量next_guess_direction等于字符串“ higher”,因为下一个猜测必须大于最后一个猜测( randomNumber大于userInput 。如果guess_error不为负,则它为正,因为我们已经消除了,所以我们使用以下方法消除了0的可能性:

    if randomNumber == userInput: # Let's check this first!
        print ("YOU WIN!!!")

So, if guess_error is positive, we know that userInput was larger than randomNumber and we set next_guess_direction equal to the string "lower." 因此,如果guess_error为正,我们知道userInput大于randomNumber ,并且将next_guess_direction设置next_guess_direction等于字符串“ lower”。 Finally, we print out everything that we have found: 最后,我们打印出发现的所有内容:

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

I am using an older version of formatting where %i and %s are placeholders for integer and string, respectively. 我正在使用旧版本的格式,其中%i%s分别是整数和字符串的占位符。 I then define what should be formatted there using %(acceptable_ranges[i], next_guess_direction) , which simply means to put acceptable_ranges[i] in for the integer and next_guess_direction in for the string. 然后,我使用%(acceptable_ranges[i], next_guess_direction)定义应该在那里格式化的内容,这简单地意味着将整数的next_guess_direction acceptable_ranges[i] Keep in mind, we found i in acceptable_ranges[i] right above the if statement. 请记住,我们在if语句上方找到iacceptable_ranges[i]

I know that is all long, but I did not know how much detail you needed! 我知道这很长,但是我不知道您需要多少细节!

Update: I see you ask to do it without modules. 更新:我看到你要求不使用模块来做。 Here's a solution: 这是一个解决方案:

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

-- original answer: You can do this with numpy's ceil function. -原始答案:您可以使用numpy的ceil函数来执行此操作。

For instance: 例如:

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

A solution using the 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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python-检查用户输入以确保它是整数-没有字母等 - Python - Check user input to make sure it is an integer - no letters, etc 如何将用户输入的格式设置为1.“整数”,“ 2。整数”,而不使代码重新运行? - How do I format my user input as 1. “integer”, 2. “integer” and not make the code run all over again? 我怎样才能以我的程序识别它是 int 还是 float 的方式接受用户输入? - How can I accept the user input in such a way that my program recognizes whether it is an int or a float? 我如何让我的程序向用户提出更多问题? - How do i make my program ask further questions to the user? 如何使程序确定输入是否为python中的int? - How can I make a program determine whether or not the input is an int in python? 如何检查此用户是匿名用户还是我系统上的实际用户? - How do I check whether this user is anonymous or actually a user on my system? 如何检查Python中的整数输入? - How do I check an input for an integer in Python? 如何检查我的 ini 文件并读取用户输入? - How do I check my ini file and read user input? PYTHON:如何使程序生成具有随机文件名的文件 - PYTHON : How do I make my program produce a file with a random file name 如何检查用户是否按下了ESCAPE? - How do I check whether the user has pressed ESCAPE or not?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM