MaundyMoo
MaundyMoo

Reputation: 13

Lists for validation

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()

Upvotes: 1

Views: 127

Answers (4)

user2647463
user2647463

Reputation:

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

Upvotes: 0

Belvi Nosakhare
Belvi Nosakhare

Reputation: 3255

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"

Upvotes: 3

Dimitris Fasarakis Hilliard
Dimitris Fasarakis Hilliard

Reputation: 160687

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

Upvotes: 3

intboolstring
intboolstring

Reputation: 7120

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.

Upvotes: 0

Related Questions