0
votes

I'm trying to write a python script that achieves the following:

  1. First, prompt a user to enter the username or press enter to exit.
  2. Prompt a user to enter quantity.
  3. Next, use regular expression to make sure that the username consists of 5 to 10 alphabetical characters.
  4. Use regular expression to make sure that quantity consists of only numerical values and the quantity entered is between 0 and 100
  5. If both the username and quantity are valid, then print the username and quantity. Otherwise print an error message.
  6. Finally, prompt the user for username again or press enter to exit.

    import re, sys
    username = "" 
    username = input('Enter Username (Press ENTER to exit): ') 
    while username != "": 
        quantity = input('Enter Quantity: ') 
        if re.match("[a-zA-Z]{5,10}$", username) and re.match("[0-9]{1,2}$", quantity) and type(quantity) is int and quantity > 0: 
            print('Username: ', username, "\n" 'Quantity: ', quantity) 
        else: 
            print('Error: Enter a username consisting of 5-10 alphabetical letters and a valid integer between 1 and 100') 
        username = input('Enter Username (Press ENTER to exit): ')
    

    How would I achieve these requirements? When I run my program I always print the error message and can't properly print the username and quantity. Thank you for taking the time and I appreciate any help I can get.

1
So what is your question at all? - Nico Albers
How would I achieve these requirements? When I run my script it automatically prints the error message and will not print the username and quantity as desired. - JDUHIG
You should extend your question with this information ;-) from this point on you only see some explanation what you want to do and tried but no question :-D - Nico Albers

1 Answers

0
votes

If you are having trouble understanding a complex condition, test each component individually. In your case, type(quantity)will not be int it will be str, which also means that quantity > 0 would raise a TypeError (you are not getting there because the typetest shortcircuits the condition).

A slightly better condition would be:

if re.match("[a-zA-Z]{5,10}$", username) and re.match("[0-9]{1,2}$", quantity) and int(quantity) > 0

This is hardly pythonic, but it will get the job done.