Search code examples
pythonloopsiterationuser-registration

if True: update, if False: restart


import getpass

class UserRegistration(object):

    def __init__(self):
        pass

    def register(self):
        register = self.register
        self.username_and_password = {}
        username = raw_input("Choose Username> ")
        password = getpass.getpass("Choose Password> ")
        confirm_password = getpass.getpass("Confirm Password> ")
        if password == confirm_password:
            self.username_and_password[username] = password
        else:
            print "Passwords didn't match"
            return register

go = UserRegistration()
go.register()

Simple program that prompts user for username and password

If the passwords don't match, I want it to restart the process and prompt the user to enter password again

At the moment, it prints the string but doesn't restart the process.

Any ideas?


Solution

  • Call the method again:

       else:
            print "Passwords didn't match"
            self.register()
    

    def register(self): is a method of the class, so you call it with self.register,, there is no need to use register = self.register

    If you just want to prompt for the password and store multiple instance details in the dict:

    class UserRegistration(object):
        username_and_password = {}
        def __init__(self):
            self.username = ""
        def register_name(self):
            self.username = raw_input("Choose Username> ")
            self.register_pass()
    
        def register_pass(self):
            password = getpass.getpass("Choose Password> ")
            confirm_password = getpass.getpass("Confirm Password> ")
            if password == confirm_password:
                self.username_and_password[self.username] = password
            else:
                print "Passwords didn't match"
                self.register_pass()
    

    You can also use a while loop:

    class UserRegistration(object):
        username_and_password = {}
        def __init__(self):
            self.username = ""
        def register_name(self):
            while True:
                self.username = raw_input("Choose Username> ")
                if self.username in self.username_and_password:
                    print "Username taken, please try again"
                    continue
                else:
                    return self.register_pass()
    
        def register_pass(self):
            while True:
                password = getpass.getpass("Choose Password> ")
                confirm_password = getpass.getpass("Confirm Password> ")
                if password == confirm_password:
                    self.username_and_password[self.username] = password
                    return
                else:
                    print "Passwords didn't match"
                    continue