'Why does sublime text not allow my code to run properly?

I am trying to create a login system for users.

This is my code:

def register():
    db = open("database.txt", "r")
    Username = input("Create Username:")
    Password = input("Create Password:")
    Password1 = input("Conform Password")

    if Password != Password1:
        print("Passwords do not match, restart")
        register()
    else:
        #checks length of Password
        if len(Password)<=6:
            print("Password is too short restart:")
            register()
        elif Username in db: # checks if the Username is in the database
            print("Username exists")
            register()
        else:
            db = open("database.txt", "a")
            db.write(Username+", "+Password+"\n") # "/n" creates a new line
            print("Success")

register()

This code is meant to output a request for the user to create a username then a password and then a confirmation of that password. This only outputs a request for a user to create a username but not a password in sublime text. I have tested this code in IDLE and it works perfectly.



Solution 1:[1]

I don't know why there is a problem with sublime, but what I know is that you have made several mistakes writing that code. Here is correct version:

import os


def register():
    if not os.path.exists("database.txt"): # if file does not exist, then create it
        with open("database.txt", "w") as f:
            f.write("\n")
    with open("database.txt", "r") as f:
        db = f.read()
    Username = input("Create Username: ")
    Password = input("Create Password: ")
    Password1 = input("Conform Password: ")
    
    if Password != Password1:
        print("Passwords do not match, restart")
        register()
    else:
        #checks length of Password
        if len(Password)<=6:
            print("Password is too short, restart")
            register()
        elif Username in [line.split(", ")[0] for line in db.split("\n")]: # checks if the Username is in the database (line.split(", ")[0] extracts username)
            print("Username exists")
            register()
        elif ", " in Username:
            print("Username must not contain \", \"")
            register()
        else:
            with open("database.txt", "w") as f:
                f.write(Username + ", " + Password + "\n" + db) # "\n" creates a new line
            print("Success")

register()

And do you know that you can't call a function inside if it's own for infinite many times? The recursion limit is something around 1000. So you will get exception after many restarts.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1