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 randintguessesTaken = 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")
You need four guesses to match for random numbers, you can also shorted your code using a list comp:
from random import randintguessesTaken = 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)]))
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 randintguessesTaken = 0
randomNumber = [str(randint(1, 9)) for _ in range(4)] # create list of random numswhile guessesTaken < 10: guesses = list(raw_input("Guess Number: ")) # create list of four digitscheck = "".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 guessprint("Congratulations, you are correct")breakelse:guessesTaken += 1 # else increment guess count and ask againprint(check)