Author Topic: Any Python pros out there willing to clean my code?  (Read 1131 times)

I don't know how to make it more neater than this. Can anyone give me advice without changing the way the whole script works?
Also what it does is it has a database of users. You are supposed to login with the correct info, you can exit the program, logout, or register. It's my first real code that I spent some effort on.

Edit: Updated the script.

Code: [Select]
from tkinter import *
import time, sys, getpass


database = {}
database["admin"] = "123"
database["user"] = "000"

logged = 'false'
listcommands = (
    "Logout, Quit, Removal(Admins Only)"
    )

def main():
    while True:
        print("Say 'help' for a list of commands.")
        command = input(">>").lower()
        if command == 'help':
            print(listcommands)
        elif command == 'quit':
            quitter()
        elif command == 'logout':
            logout()
        else:
            print("Command not valid")

def main2():
    print("Welcome! Login, register or quit.")
    while True:
        command2 = input(">>").lower()
        if command2 == "login":
            login()
        elif command2 == "register":
            register()
        elif command2 == "quit":
            quitter()
        else:
            print("Command not valid")

def login():
    print("Please login.")
    while True:
        username = input("Username: ").lower()
        password = getpass.getpass("Password: ")
        if username in database.keys():
            expected_password = database[username]
            if expected_password == password:
                print("Welcome " + username)
                global logged
                logged = 'true'
                main()
            else:
                print("Login is incorrect. Try again.")
        else:
            print("User does not exit. Try again.")

def register():
    print("Register your information")
    time.sleep(1)
    newuser = input("Username: ").lower()
    newpass = getpass.getpass("Password: ")
    database[newuser] = newpass
    print("Successful!")
    main2()

def quitter():
    print("Are you sure you want to quit? Y/N?")
    while True:
        commandquit = input(">>").lower()
        if commandquit == "y":
            print("Quitting...")
            time.sleep(2)
            sys.exit(0)
        elif commandquit == "n":
            print("Returning to main board...")
            global logged
            if logged == "true":
                time.sleep(1)
                main()
            else:
                time.sleep(1)
                main2()
        else:
            print("Command not valid.")


def removal():
    print("Work in progress...")
    time.sleep(1)
    main()

def logout():
    print("Are you sure you want to log out? Y/N")
    while True:
        commandlogout = input(">>").lower()
        if commandlogout == "y":
            print("Logging out...")
            time.sleep(1)
            main2()
        elif commandlogout == "n":
            print("Returning to main board...")
            time.sleep(2)
            main()
        else:
            print("Command not valid.")


app = Tk() # Trying to put it into a GUI here. Too tired to do it at this moment
app.title("Python Test")
label = Label(app, text="Python Test Label").pack()
button = Button(app, text="Login",command=lambda: main2()).pack()
app.geometry("500x300")
app.mainloop()
       

« Last Edit: May 24, 2013, 11:52:08 PM by Blockzillahead »

I thought these forums were lurking with Pythoneers. I guess not.

I thought these forums were lurking with Pythoneers.
why would you think that
« Last Edit: May 24, 2013, 10:29:12 PM by Night Fox »

why would you think that

because I posted a smaller code some time ago and people jumped at me because my code was messy and inefficient.

why would you think that
He hasn't gotten a reply in 20 minutes.

because I posted a smaller code some time ago and people jumped at me because my code was messy and inefficient.
I can't say for sure, but I doubt it takes a lot of knowledge in a specific language to know that some code is messy
He hasn't gotten a reply in 20 minutes.
I meant the first part

looks alright.

you could shorten the imports by doing import time, sys, getpass though

edit:
i'm guessing this works right
« Last Edit: May 24, 2013, 11:32:37 PM by otto-san »

looks alright.

you could shorten the imports by doing import time, sys, getpass though

edit:
i'm guessing this works right

very nice

so it works or not? its kinda messy but its decent. im not looking / testing it though lol

so it works or not? its kinda messy but its decent. im not looking / testing it though lol

Yes it works. I was just asking for advice to make it more compact.

Right now I'm trying to port it into an actual GUI rather than the Python IDLE.

Speaking of port, where is port? I'd think he'd be all over this thread.

Speaking of port, where is port? I'd think he'd be all over this thread.

I'm a bit busy so I'm just gonna say two things

Code: [Select]
# why is this a tuple when it only has one item and you're treating it as a string anyway!?
listcommands = (
    "Logout, Quit, Removal(Admins Only)"
    )

# why not just use a dict for command->function mapping and do it that way
        if command == 'help':
            print(listcommands)
        elif command == 'quit':
            quitter()
        elif command == 'logout':
            logout()
        else:
            print("Command not valid")

I'm a bit busy so I'm just gonna say two things


Ya I was going to change that from a tuple to just a variable with a string but forgot about it.
Scratch that. I will change it to a list actually since I plan to make a way to create your own commands.

But I haven't thought of using a dict for the command, nice idea.
« Last Edit: May 25, 2013, 10:34:18 AM by Blockzillahead »

But I haven't thought of using a dict for the command, nice idea.

Code: [Select]
def handle_foo(*args):
    print 'hello world'

commands = {
    'foo': handle_foo
}

def parse_line(line):
    command, *args = line.split(' ', 1)
    handler = commands.get(command)

    if handler:
        handler(*args)
    else:
        print 'unknown command'

also comes with the advantage of being able to make a list of commands like this:

', '.join(commands.keys())
« Last Edit: May 25, 2013, 12:55:42 PM by Port »

Code: [Select]
def handle_foo(*args):
    print 'hello world'

commands = {
    'foo': handle_foo
}

def parse_line(line):
    command, *args = line.split(' ', 1)
    handler = commands.get(command)

    if handler:
        handler(*args)
    else:
        print 'unknown command'

also comes with the advantage of being able to make a list of commands like this:

', '.join(commands.keys())

Does .join add to the dictionary or combine things in it?