function that checks valid words with certain letters, loop functions

Question:

Hello I am trying to create a function that will retrieve a word of any length and combination of the six letters such as odd, Pow. I want the function to see if the word is valid. If it is not I then want the person to type a new word in and then check that word to see if it is valid. If it is not I want to continue the loop until the word contains only the six letters. Thank you.

accepeted_letters = "U", "P", "D", "O", "W", "N"
user_input_uppercase = str(input("Select one or more of each 
letter to be displated [U, P, D, O, W, N], Thank you ")).upper()
user_input_string = str(user_input_uppercase).replace(" ", "")

def valid():
    global accepeted_letters, user_input_string
    while user_input_string[0] not in accepeted_letters:
        user_input_uppercase = input("Please Enter one or more 
of the following letters: [U, P, D, O, W, N]").upper()
    if user_input_uppercase in accepeted_letters:
        pass 

valid()
Asked By: Eric

||

Answers:

You need to prompt for input in a loop, and either break the loop or return the value from your function when the condition is met. An easy way to test your valid letter condition is to turn the user’s input into a set and then check to see if it’s a subset of the valid letters.

valid_letters = "UPDOWN"

def get_valid_letters():
    while True:
        user_letters = input(
            "Select one or more of each letter: ["
            + ", ".join(valid_letters)
            + "], Thank you "
        ).upper().replace(" ", "")
        if set(user_letters).issubset(valid_letters):
            return user_letters

print(get_valid_letters(), "is valid!")
Answered By: Samwise
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.