Python multiple number guessing game

2024/11/17 19:26:26

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")
Answer

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)
https://en.xdnf.cn/q/118766.html

Related Q&A

How to produce a graph of connected data in Python?

Lets say I have a table of words, and each word has a "related words" column. In practice, this would probably be two tables with a one-to-many relationship, as each word can have more than o…

Syntax for reusable iterable?

When you use a generator comprehension, you can only use the iterable once. For example.>>> g = (i for i in xrange(10)) >>> min(g) 0 >>> max(g) Traceback (most recent call la…

Buildozer Problem. I try to make apk file for android, but i cant

artur@DESKTOP-SMKQONQ:~/Suka$ lsbuildozer.spec main.pyartur@DESKTOP-SMKQONQ:~/Suka$ buildozer android debugTraceback (most recent call last):File "/usr/local/bin/buildozer", line 10, in <…

how to run python script with ansible-playbook?

I want to print result in ansible-playbook but not working. python script: #!/usr/bin/python3import timewhile True:print("Im alive")time.sleep(5)deploy_python_script.yml:connection: localbeco…

How to concatenate pairs of row elements into a new column in a pandas dataframe?

I have this DataFrame where the columns are coordinates (e.g. x1,y1,x2,y2...). The coordinate columns start from the 8th column (the previous ones are irrelevant for the question) I have a larger exam…

Python: using threads to call subprocess.Popen multiple times

I have a service that is running (Twisted jsonrpc server). When I make a call to "run_procs" the service will look at a bunch of objects and inspect their timestamp property to see if they s…

Find a substring [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.Want to improve this question? Update the question so it focuses on one problem only by editing this post.Closed 5…

Image processing with single to multiple images

I have an Image showing below: I need to crop the order using python coding. What I need is only the card. So I want to crop the border. How to do it??This is the output I got using the code mentione…

SQLAlchemy Automap not loading table

I am using SQLAlchemy version 2.0.19 (latest public release). I am trying to map existing tables as documented in https://docs.sqlalchemy.org/en/20/orm/extensions/automap.html#basic-use I created a SQL…

Create a base 12 calculator with different limits at diferent digits with python

I want o create a calculator that can add (and multiply, divide, etc) numbers in base 12 and with different limits at the different digits.Base 12 sequence: [0,1,2,3,4,5,6,7,8,9,"A","B&q…