1

I'm trying to validate an input by using a list that holds the strings that are valid inputs but I can't seem to get it to work correctly, any help?

choice = ["A","a","B","b"]
def main():
    test = input()
    if validate(test):
        print("Entered a")
    else:
        print("did not enter a")

def validate(val):
    try: 
        val = choice.index[1]
    except:
        return False
    else:
        return True
main()
2
  • did you mean choice.index[val]? Commented Oct 3, 2015 at 20:39
  • I suspect it should be choice.index(val) (with parens, not brackets, and looking for val, not assigning to it). But that idiotic bare except: (NEVER USE BARE EXCEPT!) is masking the problem. If the except were targeted to the ValueError only, it wouldn't mask the TypeError using brackets raises. Of course, it's still a pointless way to test (return val in choice being correct and simpler), but that's why the original code breaks. Commented Oct 3, 2015 at 21:32

4 Answers 4

3

No need for an exception in validate, just check if the list contains the element by using the in operator:

def validate(val):
    if val in choice: # checks if the value is in the list.
        return True

No need for an else clause in validate() either since the function will return None which will evaluate to False.


To make this better, just return the element (which will evaluate to True again):

choice = ["A","a","B","b"]
def main():
    test = input()
    if validate(test):
        print("Entered " + val)
    else:
        print("Did not enter a valid value")

def validate(val):
    if val in choice:
        return val
Sign up to request clarification or add additional context in comments.

Comments

3

try this one liner

def validate(val):
    return val in choice

and you could do something like this:

test = inputFromUser()

print validate(test) and "Entered " + test or "Did not enter a valid value"

Comments

0

Is this what you want? This will check the input up against members of val. If the entry is in vals, it will accept it.

vals = ["a","b","c"]
def main():
    test = input()
    if validate(test):
        print("Valid entry")
    else:
        print("did not enter valid info")
def validate(val):
    for i in vals:
        if val == i:
            return True
    return False
main()

I'm slightly confused by your question, but I hope this helps.

1 Comment

Yes thank you, sorry I'm new to python so this probably should've been relatively simple
0

Can you try using following and see if it works for you ?

def validate(val):
    if val in choice
         return True
    return False

returning False explicitly to be very clear about what the function does, you can live without that

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.