Kapil Soni
Kapil Soni

Reputation: 47

Repeat Loop upon False

The function below calls for the input command and check if str.isalnum().

def enterPass(str):
    x = raw_input("enter password Alpha or Alphanumeric! 'No_Space' :")
    if x.isalnum():
        print "saved"
    else:
        print "try again"
    return;

Followed from the above is the below function, which exists when the function enterPass has been called 3 times.

_try = 1
while (_try <= 3):
    enterPass("password")
    _try += 1

My intention was that upon entering password it should verify if it is Alpha-Numerics or not. If so, it should prompt "Saved" and quit, if not then it should ask for the password again, and if the user cannot get the password right 3 times, the program shoudl quit.

The problem I am facing is that I am unable to quit this program once it had successfully accepted the isalnum() with "Saved" prompt. It is going again in the loop asking to enter my password again. Please suggest how I can make this function work as intended, and possibly more efficienty.

The above program is just for academic purpose and has no useful application at present.

Upvotes: 0

Views: 902

Answers (2)

nurtul
nurtul

Reputation: 408

You could import sys and do sys.exit(0)

import sys


if x.isalnum():
        print "saved"
        sys.exit(0)

Now sys.exit will give you a bunch of errors when it's exiting the program when running in an IDLE, ignore those because in the actual final program they will not appear.

But that is if you want to terminate the whole program. If you simply want to break out of the loop and continue the program with something else you can do

if x.isalnum():
        print "saved"
        break

Break must also be in a loop for it to work.

Upvotes: 0

TerryA
TerryA

Reputation: 59974

A function is probably not needed in this case, as you can then use break:

tries = 0
while tries < 3:
    x = raw_input("Enter password Alpha or Alphanumeric! No spaces! ")
    if x.isalnum():
        print "Saved"
        break
    print "Try again"
    tries += 1

Here's a test:

Enter password Alpha or Alphanumeric! No spaces! Hi!@#
Try again
Enter password Alpha or Alphanumeric! No spaces! !@#!@#
Try again
Enter password Alpha or Alphanumeric! No spaces! @@@@
Try again
>>> 

Enter password Alpha or Alphanumeric! No spaces! No!
Try again
Enter password Alpha or Alphanumeric! No spaces! Okay
Saved
>>> 

Upvotes: 2

Related Questions