Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate user input in python [duplicate]

I am brand new to python and I am trying to figure out how to validate user input. I want to ask the user to submit a DNA sequence and want to validate that it is a DNA sequence. Acceptable inputs can have upper or lowercase ATCGs and spaces and I'm not sure exactly how to do it.

So far I can ask for the input but not verify it.

import sys
Var1 = raw_input("Enter Sequence 1:")

I then want to do something like:

if Var1 != ATCG (somehow put 'characters that match ATCG or space)
    print "Please input valid DNA sequence"
    sys.exit() (to have it close the program)

Any help? I feel like this should be rather simple but I don't know how to specify that it can be any ATCG, atcg or space.

like image 382
scooterdude32 Avatar asked Dec 22 '25 13:12

scooterdude32


1 Answers

You can use all, str.lower, and a generator expression:

if not all(x in "agct " for x in Var1.lower()):
    print "Please input valid DNA sequence"
    sys.exit(1) 

In the above code, the last two lines will be run if any character in Var1 is not one of the following:

"A", "T", "C", "G", " ", "a", "t", "c", "g"

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!