问题描述
我正在尝试创建一个包含多个数字的猜数字游戏.计算机生成 1 到 9 之间的 4 个随机数,然后用户有 10 次机会猜出正确的数字.我需要将反馈显示为 YYYY
表示猜出的 4 个正确数字,YNNY
表示猜出的第一个和最后一个数字等(你明白了).下面的代码不断返回说IndexError: list index out of range
.
I am trying to create a number guessing game with multiple numbers. The computer generates 4 random numbers between 1 and 9 and then the user has 10 chances to guess the correct numbers. I need the feedback to display as YYYY
for 4 correct numbers guessed, YNNY
for first and last number guessed etc. (you get the point). the code below keeps coming back saying IndexError: list index out of range
.
from random import randint
guessesTaken = 0
randomNumber = []
for x in range(4):
tempNumber = randint(1, 9)
randomNumber.append(tempNumber)
Guess = []
Guess.append(list(input("Guess Number: ")))
print(randomNumber)
print(Guess)
if randomNumber[0] == Guess[0]:
print("Y")
elif randomNumber[1] == Guess[1]:
print("Y")
elif randomNumber[2] == Guess[2]:
print("Y")
elif randomNumber[3] == Guess[3]:
print("Y")
elif randomNumber[0] != Guess[0]:
print("N")
elif randomNumber[1] != Guess[1]:
print("N")
elif randomNumber[2] != Guess[2]:
print("N")
elif randomNumber[3] != Guess[3]:
print("N")
推荐答案
你需要四次猜测来匹配随机数,你也可以使用 list comp 缩短你的代码:
You need four guesses to match for random numbers, you can also shorted your code using a list comp:
from random import randint
guessesTaken = 0
randomNumber = []
Guess = []
for x in range(4):
tempNumber = str(randint(1, 9)) # compare string to string
randomNumber.append(tempNumber)
Guess.append(input("Guess Number: "))
print("".join(["Y" if a==b else "N" for a,b in zip(Guess,randomNumber)]))
您还可以使用 enumerate 检查匹配索引处的元素:
You can also use enumerate to check elements at matching indexes:
print("".join(["Y" if randomNumber[ind]==ele else "N" for ind, ele in enumerate(Guess)]))
给用户一个循环的猜测:
To give the user guesses in a loop:
from random import randint
guessesTaken = 0
randomNumber = [str(randint(1, 9)) for _ in range(4)] # create list of random nums
while guessesTaken < 10:
guesses = list(raw_input("Guess Number: ")) # create list of four digits
check = "".join(["Y" if a==b else "N" for a,b in zip(guesses,randomNumber)])
if check == "YYYY": # if check has four Y's we have a correct guess
print("Congratulations, you are correct")
break
else:
guessesTaken += 1 # else increment guess count and ask again
print(check)
这篇关于Python 多个数字猜谜游戏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!