[SOLVED] Validate user input uses only specific characters (7 random letters) for a word game in Python 3.10

Issue

I’m very new to programming, but I’m getting my feet wet by creating a word game.

import random
HowManyVowels = random.randint(1,5)
vowels = ["A" , "E" , "I" , "O" , "U"]
RoundVowels = random.sample(vowels,HowManyVowels)
HowManyConsonants = 7 - HowManyVowels
Consonants = ["B" , "C" , "D" , "F" , "G" , "H" , "J" , "K" , "L" , "M" , "N" , "P" , "Q" ,"R" , "S" , "T" , "V" , "W" , "X" , "Y" , "Z"]
RoundConsonants = random.sample(Consonants,HowManyConsonants)
RoundLetters = RoundVowels + RoundConsonants 
print(RoundLetters)
import time
WordsGuessed = []

timeout = time.time() + 60*1   # 1 minute from now
while True:
    test = 0
    if test == 1 or time.time() > timeout:
        break
    test = test - 1
    PlayerWord = input("What letters can you make from these letters?")
    WordsGuessed.append(PlayerWord)

print(WordsGuessed)

I have gotten to where it can randomly select the letters for a round and limit a round to a minute. The input validation is where I am getting hung up. So if I run the code and the letters [ A E M R T S V ] are selected, the user should only be allowed to use those letters. Repetition will be allowed, and it must be over 3 length (but these two rules will be easier to implement).

The question is how do I restrict user input to the characters chosen each round (both uppercase and lowercase).

Solution

Here’s an easy way to validate. Loop through the letters in the word they input and make sure they’re in the allowed list of letters. It’ll look something like this:

for letter in PlayerWord: # This will loop through the input word
  if letter not in RoundLetters:
    print('Letter not in allowed list')
    check = True
    break
if check:
  check = False
  continue
else:
  wordsGuessed.append(PlayerWord)

Also, just a side note, group together all your import statements at the top of your code.

Answered By – KrabbyPatty

Answer Checked By – Clifford M. (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *