HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

A command-line application that manages my lending accounts

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
manageslineapplicationthatcommandaccountslending

Problem

I'm learning Python and tried to solve a problem that I have. That problem is "managing" the people who owe me money. Basically, my project goal is:

  • v0.1 - command line application



  • v0.1.1 - command line application that works on persistent data



  • v1.0 - a (non web-base) GUI application that works on persistent data



I think I'm close to finishing v0.1 so I'm looking for feedback before moving on. Here is the Github Repo. From file structure, Python conventions, or even terms that I misused in the program itself, please do share your comments.

Project Structure

.
├── LICENSE.txt
├── README.md
├── main.py
└── modules
    ├── Account.py
    ├── Borrower.py
    ├── __init__.py
    └── helpers.py


main.py

```
#!/usr/bin/python3.5
''' Main program '''

import os
import sys
from datetime import date
from modules.Borrower import Borrower
from modules.helpers import clear_delay, press_enter

def main():
''' The main function that allows the user to interact with the rest of the program. '''
# Setup
os.system("clear")
database = {}

# Greet the user.
print("Good day! Welcome to our lending company!")
clear_delay(1)

# Ask for their name.
print("What is your name? ", end='')
name = input()
clear_delay(1)

# Name validation.
if name in database:
print("Welcome back, {}".format(name))
clear_delay(1)
elif name not in database:
print("Name not found. Do you want to register? (Y/N)")
user_wants_to_register = input().upper() == 'Y'
clear_delay(2)

if user_wants_to_register:
database[name] = Borrower(name)
print("You are now registered to our services, {}.".format(name))
clear_delay(2)
else:
print("See you soon!")
clear_delay(2)
sys.exit()

# Interface loop.
choice = None
while choice != 'Q':
print("How may we help you?")
print("[0]: Create a new account o

Solution

That's more a better user interface than clean code, but why ask user if they already registered if u would register them or close program anyway? Always haven't liked that in websites. Signing or register should be one button.

def sigin_or_register(users):
    print('Signin or register: ')
    name = input()
    if name in users:
        print("Welcome back, {}".format(name))
    else:
        print("You are now registered to our services, {}.".format(name))


As to the code I'll will review it a bit later, but this long if else should be refactored into a list or a dictionary of possible action functions like [action1, action2, action3].

def create_account(accounts, user):
    try:
        amt = prompt('How much will you borrow?\nAmount: ', int)
    except ValueError:
        print('Invalid Value')
        # Ask for a confirmation.
        print('A 5% interest rate will be applied weekly on this account.')
        agree = prompt('Enter "YES" to confirm', lambda i: i.upper() == 'YES')
        if agree:
            accounts[user].open_account(amt, date.today(), 5)
            print('Account created! Summary: ')
            accounts[user].show_credits(-1)
            press_enter()

def prompt(string, as_type=None, delay=1):
    print(string, end='')
    inp = input()
    clear_delay(delay)
    if as_type and inp = '':
        return None
    return as_type(inp)

def check_accounts(accounts, users):
    if not accounts[user].accounts:
        print('You have no accounts under your user.')
        clear_delay(2)
    else:
        acc_id = prompt('Enter account id (leave blank to show all acounts): ', int)

        if acc_id is None:
            database[user].show_credits()
        try:
            database[users].show_credits(acc_id)
        except Exception as e:
            print('Invalid accout id')
        press_enter()

def exit():
    print("Thank you for using our services. See you soon!") 
    sys.exit()

actions = (
    ('0', (create_account, 'Create a new account on my name'),
    ('1', (check_accounts, 'Check accounts under my name'),
    ('Q', (exit, 'Exit the program')),
)
    choice = None
    print("How may we help you?")
    actions = OrderedDict(actions)
    choices_prompt = '\n'.join(f'[{key}]: {hint}' for key, (action, hint), actions.items())
    while True:
        choice = prompt('How may we help you?\n' + choices_prompt, str.upper)
        action, key = actions[choice]
        action(accounts, user)


Notice also the prompt function refactoring. This code may not work, but it shows the idea.

Code Snippets

def sigin_or_register(users):
    print('Signin or register: ')
    name = input()
    if name in users:
        print("Welcome back, {}".format(name))
    else:
        print("You are now registered to our services, {}.".format(name))
def create_account(accounts, user):
    try:
        amt = prompt('How much will you borrow?\nAmount: ', int)
    except ValueError:
        print('Invalid Value')
        # Ask for a confirmation.
        print('A 5% interest rate will be applied weekly on this account.')
        agree = prompt('Enter "YES" to confirm', lambda i: i.upper() == 'YES')
        if agree:
            accounts[user].open_account(amt, date.today(), 5)
            print('Account created! Summary: ')
            accounts[user].show_credits(-1)
            press_enter()


def prompt(string, as_type=None, delay=1):
    print(string, end='')
    inp = input()
    clear_delay(delay)
    if as_type and inp = '':
        return None
    return as_type(inp)


def check_accounts(accounts, users):
    if not accounts[user].accounts:
        print('You have no accounts under your user.')
        clear_delay(2)
    else:
        acc_id = prompt('Enter account id (leave blank to show all acounts): ', int)

        if acc_id is None:
            database[user].show_credits()
        try:
            database[users].show_credits(acc_id)
        except Exception as e:
            print('Invalid accout id')
        press_enter()


def exit():
    print("Thank you for using our services. See you soon!") 
    sys.exit()


actions = (
    ('0', (create_account, 'Create a new account on my name'),
    ('1', (check_accounts, 'Check accounts under my name'),
    ('Q', (exit, 'Exit the program')),
)
    choice = None
    print("How may we help you?")
    actions = OrderedDict(actions)
    choices_prompt = '\n'.join(f'[{key}]: {hint}' for key, (action, hint), actions.items())
    while True:
        choice = prompt('How may we help you?\n' + choices_prompt, str.upper)
        action, key = actions[choice]
        action(accounts, user)

Context

StackExchange Code Review Q#162682, answer score: 2

Revisions (0)

No revisions yet.