2

I have been writing a Python 3 program that includes a keyboard input and I wanted to test what comes in, to make sure it meets certain criteria, namely it should be a single character and only a, b or c. Being new to Python, I have cobbled together some code from other pages here, and it seems to work, but I'm not sure that it follows best practice (or even is correct programming). So any comments/improvements or alternatives most welcome.

chars = set('abc')
trigger = 0
while (trigger == 0):
    answer = input(':')
    if len(answer) != 1:
        print ('Please enter only one character')
    if any ((c in chars) for c in answer):
        trigger = 1
    else:
        print ('please answer a,b or c')
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
N. Blain
  • 21
  • 1
  • 2
    If this is **working code** that you think could be improved, see [codereview.se]. If you're unsure, delete the question and go and **test it**. If you are aware of a specific problem, [edit] to provide a [mcve]. In general, the guidance on validating user input is at https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response. – jonrsharpe Dec 31 '17 at 14:40
  • Many thanks, the link you provided took me to what I was looking for, although I hadn't come across that page in my searches. – N. Blain Dec 31 '17 at 22:05

1 Answers1

2

Create a list of valid inputs, and use in to test. Example:

>>> rv = input()
a
>>> rv in ['a', 'b', 'c']
True
>>> rv = input()
test
>>> rv in ['a', 'b', 'c']
False
Roland Smith
  • 42,427
  • 3
  • 64
  • 94