[英]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语句上方找到
i
在acceptable_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.