1

Like using this to validate that an input is only alpha-numeric:

while True:
    str = input('')
    if str.isalnum():
        break
    else:
        print("Please include only alpha-numeric characters.\n")

This code has worked for all instances that I have tested it in, but is this bad practice?

  • I don't see anything wrong with your code (except for the fact that `str` is a builtin and you should not shadow it with a variable) – Andrea Corbellini Feb 16 '16 at 18:32
  • That is a good example of how to use a break, it is not bad practice. – CasualDemon Feb 16 '16 at 18:48
  • 1
    This is actually the recommended practice. See [Asking the user for input until they give a valid response](http://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response/23294659#23294659) – gil Feb 16 '16 at 19:03

2 Answers2

0

That's fine. Here is a note, however: you can find out if the while loop exited with a break or without one by using else:

x = 0
while x < 4:
    x += 1
else:
    print("no break")

# prints no break

If you break, however:

x = 0
while x < 4:
    x += 1
    if x == 2:
        break
else:
    print("no break")

# Does not print
zondo
  • 19,901
  • 8
  • 44
  • 83
-2

you can abstract it further

def verified_input(prompt='',test_condition=lambda x:1,err_message="Please Enter Valid Input"):
    while True:
        result = input(prompt)
        if test_condition(result):
           return result
        print( err_message )


def verified_alnum(prompt,err_message="Please enter Only alpha numerics"):
      return verified_input(prompt,lambda x:x.isalnum(),err_message)



result = verified_alnum("Enter Password:","A password must be only letters and numbers")

this allows you to create any number of test conditions quickly and relatively verbosely

Joran Beasley
  • 110,522
  • 12
  • 160
  • 179