-2

I am trying to take user input as a string and check it against a list of characters, I want the user to create a word using only characters from the list.

So far I can check that the first letter is correct but any more than that and my test fails!

wordInput = str(input("words please: "))
if wordInput in ['w', 'v', 'g']:
print("yes")
else:
    print("no")

I'm not sure how I can take the input and split it so that my test recognizes each individual character of the input rather than testing the input literally against the characters in the list.

Any help would be gratefully received, Thank you

Georgy
  • 12,464
  • 7
  • 65
  • 73
Mortgage1
  • 35
  • 1
  • 1
  • 6
  • 2
    use a for in loop to go through each letter at a time `for letter in word_input:` – Chris Doyle Mar 19 '20 at 12:16
  • 1
    Don't need to use `str(input(..`, – it already [returns a string](https://docs.python.org/3/library/functions.html#input). – Jongware Mar 19 '20 at 12:24
  • not too sure why I've been marked down? if you would like to explain I would be more than happy to edit my question – Mortgage1 Mar 19 '20 at 12:31
  • You could have written this with a simple loop. So far, the answers below use more advanced techniques (more "pythonic") but looping over `word_input` and testing one character at a time is not entirely illogical. (Also, your indentation is bad. Also, you are not testing "that the first letter is correct... it only works on *one* letter inputs.) – Jongware Mar 19 '20 at 12:33
  • that's kind of why I asked for help? – Mortgage1 Mar 19 '20 at 12:36
  • Ah – you did not *know* there was a `for` in Python? Check out the [official Python Tutorial](https://docs.python.org/3/tutorial/controlflow.html#for-statements), "4.2. `for` Statements". – Jongware Mar 19 '20 at 12:38

3 Answers3

1

The pythonic way here is to use sets:

def validate_input(userword, accepted_chars):
    return set(accepted_chars).issuperset(userword)

def main():
    # input() always returns a string in Py3    
    userword = input("words please:")
    if validate_input(userword, "wvg"):
        print("ok")
    else:
        print("ko")

if __name __ "__main__":
    main()
bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118
1

The pythonic way here is to use all:

word_input = input("words please: ")
if all(ch in ['w','v','g'] for ch in word_input):
    print("yes")
else:
    print("no")

.. for ch in word_input yields every character in word_input one by one. As soon as the test ch in [..] fails, all will return False; if all tests pass, it returns True.

Jongware
  • 22,200
  • 8
  • 54
  • 100
0

One way is to match all characters against the master list .

wordInput = str(input("words please: "))
only_valid_characters = ['w', 'v', 'g']
validatedInput = [valid_char for valid_char in wordInput if valid_char in only_valid_characters]

if len(wordInput) == len(validatedInput):
    print("yes")
else:
    print("no")
Kris
  • 8,680
  • 4
  • 39
  • 67