我是Python新手。我正在尝试编写一个小游戏,要求最终用户从1到1000中选择一个数字,并将其保存在他们的头脑中(该数字未提供给程序)。程序应该能够在10次猜测中找到数字。就像我通常做的那样,我走错了路。我的程序大部分时间都在工作,但有时在10次猜测中找不到数字。这是我的密码:
# script to guess a user's number between 1 and 1000 within 10 guesses
# import random so we can use it to generate random numbers
from random import randint
# Variables
lowerBound = 1
upperBound = 1000
numGuesses = 1
myGuess = 500
failed = False
# Welcome Message
print("#####################################################################################################"
"\n# #"
"\n# Please think of a number between 1 and 1000. I will attempt to guess the number in 10 tries. #"
"\n# #"
"\n#####################################################################################################")
while numGuesses <= 10:
# if the lower and upper bounds match we've found the number
if lowerBound == upperBound:
print(f"\nYour number is {str(lowerBound)}. It took me '{str(numGuesses)} guesses!")
break
print(f"\nIs the number {str(myGuess)}? If correct, type CORRECT. If low, type LOW. If high, type HIGH.")
# uncomment for var output
# print(f"\nGuesses = {str(numGuesses)}\nLower bound = {str(lowerBound)}\nUpper bound = {str(upperBound)}")
userFeedback = input("\nResponse: ").upper()
if userFeedback == 'HIGH':
print(f"\nGuess #{str(numGuesses)} was too high")
if numGuesses == 10:
failed = True
break
upperBound = myGuess - 1
myGuess = randint(lowerBound, upperBound)
elif userFeedback == 'LOW':
print(f"\nGuess #{str(numGuesses)} was too low")
if numGuesses == 10:
failed = True
break
lowerBound = myGuess + 1
myGuess = randint(lowerBound, upperBound)
elif userFeedback == 'CORRECT':
print(f"\nYour number is {str(myGuess)}! It took me {str(numGuesses)} guesses!")
break
numGuesses += 1
if failed:
print(f"\nMy final guess of {str(myGuess)} was not correct. I wasn't able to guess your number in 10 tries.")
很明显(现在)我减少数字的方法行不通。我原本想问它是不是500,如果更低,问它是不是250。如果再次降低,询问是否为125,依此类推。如果更高,询问是否为750875,以此类推。这是正确的方法吗
我想这件事想得太久了,我相信我的头脑已经成熟了。谢谢
这是不对的
如果您已将范围缩小到
6
和8
之间,并且您正在猜测7
,那么之前的代码将调用4
,而这超出了您的搜索范围我已经更新了我的代码,我想我已经做到了。谢谢你的提示
相关问题 更多 >
编程相关推荐