简体   繁体   中英

How to make sure a user can only input certain characters in Python?

In my program 6 letters will be randomly generated every time and given to the user. I want the user to then only be able to input using those 6 letters,and if they don't it will be an error. When I try to use a for loop it repeats the code the number of letters the user entered times. When I use regex it only accepts it if it is exactly the same. How could I fix this?

Code

from random_word import RandomWords
r = RandomWords()

print("WELCOME TO THE ANAGRAM GAME!")
word = r.get_random_word(minLength = 6, maxLength = 6)
print(word)

done = time.time() + 60 * 1
while time.time() < done:
    q1 = input("Enter your anagrams")
    if re.findall(word, q1):
        print("Correct")
        answers = []
        answers.append(q1)
        print(answers)
        score = 0
    else:
        print("Wrong")

Compare the sets of letters:

if set(word) >= set(q1): # Same (or fewer) letters

Operator >= checks if the right operand is a subset of the left operand.

If you have those random letters in a list:

if set(userInput).issubset(set(randomLetters)):
    #dosomething

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM