« Web, HTML, Tech Forum

Anyone wanna do my python homework for me!?

Posted by Kat

posted

Forum: Web, HTML, Tech

lmk if you're good at python cuz my comp sci class is kicking my ass lmao


Report Topic

3 Replies

Sort Replies:

Reply by EngiQu33ring

posted

I won't do it for you, but I'm a python programmer and can help point you in the right direction


Report Reply

Reply by Kat

posted

@EngiQu33ring

hi, thank you so much for offering your assistance, i was wondering if you knew how to use regular expressions? I want to limit the users input to only the numbers 26, 28, 30, 32, or 34.
I thought i did it correctly but when I input any of those numbers it does not work.

Heres the bit of code:

    while option == "1":
        jean_size = input("Please enter your jean size:")
        while not re.match("^[26,28,30,32,34]*$", jean_size) or jean_size == "" or len(jean_size) > 2:
            jean_size = input("Please enter your jean size:")


Report Reply

Reply by EngiQu33ring

posted

Square brackets in regex indicate that you want any character from that list, not that you want any matching value from that list. If you want specific strings, you have to use parenthesis:

re.match('(20)|(30)|(40)', <some string here>)

will get you any instance of the numbers 20, 30, or 40 in your string, whereas

re.match('[20,30,40]', <some string here>)

will get you any string containing 0, 2, 3, 4

Additionally, is there a particular reason you're using regex? It seems like:

jean_size in ['26', '28', '30', '32', '34']

is a lot more straightforward at determining if the provided jean_size is correct. It would also cover any cases where the user provides a string like "226" or "", as neither of those match anything in the list.

This isn't as necessary, but you can also leave off that first

jean_size = input(...)

so long as you instantiate the variable above the first while loop. Personally, I would use something like:

while jean_size not in ['26','28','30','32','34']:
    jean_size = input("Please enter your jean size: ")
print('got something!')

for your inner while.

Also, just another side note about regex, but if you want to get two characters and only two characters, try this instead:

re.match("^[abc]{2}$", <some string>)

This will match "aa", "ab", "cb", etc, but will not match "a" or "aaa". Putting a group of characters/string segments next to "{<number>}" will search for exactly that many characters from the set.

Generally though I recommend avoiding regex if you just need simple string comparison.


Report Reply