我建议使用列表来追加猜测。我以这种方式更改了您的代码(在我的情况下为 Python 3):
import random
give_number = int(input("We will roll a 6 sided dice. What do you think the number will be?\n "))
guess_number = 1
guessList = []
guessList.append(give_number)
dice = random.randint(1,6)
while give_number != dice:
if give_number > dice:
give_number = int(input("Sorry, that answer is too high! Try again!\n "))
#guess_number = guess_number + 1
if give_number not in guessList:
guessList.append(give_number)
if give_number < dice:
give_number = int(input("Sorry, that answer is too low! Try again!\n "))
#guess_number = guess_number + 1
if give_number not in guessList:
guessList.append(give_number)
if give_number not in guessList:
guessList.append(give_number)
print ("Congratulations, you were right, the answer was {}! It took you {} tries.".format(dice, len(guessList)))
如果你想检查输入是整数还是在你的范围内,你可以看看这段代码:
import random
def inputIsInt(inpStr): # checks if the input is an integer in range (1, 7).
try:
if int(inpStr) in range(1, 7):
return True
else:
return False
except ValueError:
return False
give_number = input("We will roll a 6 sided dice. What do you think the number will be?\n ")
while not inputIsInt(give_number):
print("Sorry, your input is not an integer or out of range")
give_number = input("We will roll a 6 sided dice. What do you think the number will be?\n ")
guessList = []
guessList.append(int(give_number))
dice = random.randint(1,6)
while int(give_number) != dice:
if int(give_number) > dice:
give_number = input("Sorry, that answer is too high! Try again!\n ")
while not inputIsInt(give_number):
print("Sorry, your input is not an integer or out of range")
give_number = input("We will roll a 6 sided dice. What do you think the number will be?\n ")
if int(give_number) not in guessList:
guessList.append(int(give_number))
if int(give_number) < dice:
give_number = input("Sorry, that answer is too low! Try again!\n ")
while not inputIsInt(give_number):
print("Sorry, your input is not an integer or out of range")
give_number = input("We will roll a 6 sided dice. What do you think the number will be?\n ")
if int(give_number) not in guessList:
guessList.append(int(give_number))
if int(give_number) not in guessList:
guessList.append(int(give_number))
print ("Congratulations, you were right, the answer was {}! It took you {} tries.".format(dice, len(guessList)))