1

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.

1
  • varClass already contains "c" and "a" because you preppend "class" :X Commented Feb 26, 2015 at 9:54

2 Answers 2

1
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.

Sign up to request clarification or add additional context in comments.

3 Comments

acctually it will always match true due to that "class" begins with c
@Johan if input is c only then it will match.else it will fail
I'm talking about his code, it will always match true, @vks your code is correct
0

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)

7 Comments

While your not all logic matches the OPs, I don't think the OPs is actually correct....
As the input is being written to a .dat file, how can I implement this as well?
@JordanBolton, the same way, if you only want abc in the class name then the logic is the same.
@PadraicCunningham not sure a class of abababababcababa should really be valid... - think it should be that it's either A or B or C... one letter, that's it
@JonClements, True but I have no idea what the class names can be
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.