Jordan Bolton
Jordan Bolton

Reputation: 29

Python limiting character input

I'm trying to only allow the letters a, b or c in an input for a .dat file in a Python program (code below), but I'm having difficulty getting the program to do this correctly.

varClass = "class" + input("Which class are you in? [A/B/C]: ").lower() + ".dat"
if not re.match("^[a-c]*$", varClass):
    print("Enter the correct class number")

This is what I have already, but it still continues to run even after an incorrect character has been entered.

Upvotes: 1

Views: 77

Answers (2)

Padraic Cunningham
Padraic Cunningham

Reputation: 180411

Take the input first, check it then add class and .dat, you have already added class and .dat before you check the input, adding then checking is doing things a bit backwards:

allowed = {"a","b","c"}
inp =  input("Which class are you in? [A/B/C]: ").lower()
if not allowed.issuperset(inp):
     print("Enter the correct class number")
else:
     var = "class{}.dat".format(inp)

If you have certain specific letter combinations you will have to add those in the set and check:

    inp =  input("Which class are you in? [A/B/C]: ").lower()
    if inp.lower() not in {"ab","ac"}:
         print("Enter the correct class number")
    else:
         var = "class{}.dat".format(inp)

Upvotes: 0

vks
vks

Reputation: 67968

varClass = "class" + input("Which class are you in? [A/B/C]: ").lower() + ".dat"
if not re.match("^class[a-c]\.dat$", varClass):
    print("Enter the correct class number")

Your match will always return false as match matches from beginning and you have class at the beginning.

Upvotes: 1

Related Questions