I'm a beginner to Python programming and have come upon an issue with my current assignment. The assignment reads as follows...
- Your program should secretly generate a 4-digit number (or a string containing only digits, 4 characters long) which has no digits repeated.
- Your program should then ask the user to enter a guess for the code. The user's guess should be 4 characters long, consisting only of digits, with no digits repeated. Your program should verify the input is valid before scoring it, and prompting the user to re-enter input if necessary. Invalid input does not count against the codebreaker's number of guesses. Your code may ignore (strip off) leading or trailing whitespace from the input, but should count internal spaces as incorrect input.
- On each turn, print the turn number and get the user's guess. If the input is valid, the output for the turn should be the user's guess, followed by the feedback. Feedback is a 4-character string: 'X' for each digit in the right position; 'O' for each digit that is in the code but not in the right position; '-' for all others. Note that the X's and O's should be together; feedback is only how many pegs of each type, not which ones or where they are.
- Maintain a history of all guesses and the feedback, so it can be printed for the user on each turn.
Right now I am just focusing on the "Feedback" portion of the assignment. My code is currently:
import random
def validateInput():
inputGuess = input("Enter your guess as 4 numbers:")
while True:
if len(inputGuess) != 4:
inputGuess = input("Enter your guess as 4 numbers:")
else:
numberList = list(inputGuess) ##
invalidNumbers = False
for number in numberList:
if number not in ['1','2','3','4','5','6','7','8','9']:
invalidNumbers = True
if invalidNumbers == True:
print ("Possible numbers are 1, 2, 3, 4, 5, 6, 7, 8, 9.")
inputGuess = input("Enter your guess as 4 numbers:")
else:
return numberList
guessesRemaining=10
code=['1','2','3','4']
while guessesRemaining > 0:
report=[]
guess=validateInput()
guessesRemaining -= 1
if guess[0] == code[0]:
report.append("X")
if guess[1] == code[1]:
report.append("X")
if guess[2] == code[2]:
report.append("X")
if guess[3] == code[3]:
report.append("X")
tempCode=sorted(code)
tempGuess=sorted(guess)
if tempCode[0]==tempGuess[0]:
report.append("O")
if tempCode[1]==tempGuess[1]:
report.append("O")
if tempCode[2]==tempGuess[2]:
report.append("O")
if tempCode[3]==tempGuess[3]:
report.append("O")
report2=report[0:4]
dash=["-","-","-","-"]
report3=report2+dash
report4=report3[0:5]
print(report4)
For example, if the user guess 1879 and the code is 1234, I receive "X O --" but I want to receive "X---". Also, any advice on streamlining my code would be awesome. For simplicity, I made the "random code" just [1,2,3,4] for now.