Skip to content

Instantly share code, notes, and snippets.

@Jbot29
Created July 6, 2015 17:25
Show Gist options
  • Select an option

  • Save Jbot29/637accee715e61577e92 to your computer and use it in GitHub Desktop.

Select an option

Save Jbot29/637accee715e61577e92 to your computer and use it in GitHub Desktop.
'''
Part 1: Make a program that keeps track of your budget. The user can type in commands via the terminal to make changes/add/show the budget.
- Create a program with a simple ui loop (a function that has a while loop which keeps the program running). THe loop will repeatedly display a list of commands and ask the user for input. (Commands are listed below)
- Once the input action is complete, display the list of command options again until the user quits (enters "q").
- Each command has an associated function that gets called when the user enters the right letter. You will write these functions.
Commands:
"a" Add an item to the budget - should ask the user for each field name, amount, monthly
"s" Show items in the budget - calculates the total amount of expenses
"r" Remove an item from the budget
"q" Quit Program
'''
'''
**** Finish part one before moving on to Part 2 ****
A csv file is a very simple file that is used quite often. Usually a csv file will look something like this:
(a simple expenses csv file)
---
name,amount,monthly
food,1000.00,y
rent,2000.00,y
braces,2000.00,n
---
A csv usually starts with a header line that lists the names of the fields so someone reading or importing it into a spreadsheet app knows what each column is for.
Your goal is to write a simple budget app. This application will have a simple interface that shows the list of commands to the user, and allows the user to enter a command and keep doing various commands until they say
quit.
It will store the data it gets from the user in a csv file.
Add the following commands
1. "s" - Save file -> this converts your internal data structure to a csv and rights it out
2. "r" - Read File -> reads from a csv and converts the data into your internal data structure.
To test your output, you should be able to open the file in a spreadsheet application (e.g. Excel) after closing.
'''
#store file namefix this so not global. Also list these once when show and data underneath and also do dictionary if if/else etc
def ui_loop():
response = ''
categories = ['name', 'amount', 'monthly']
stored_data = {'file_name': 'untitled', 'categories': categories, 'data': []}
while response.lower() != 'q':
print '''
"a" - Add an item to the budget
"s" - Show items in the budget
"r" - Remove an item from the budget
"q" - Quit Program
"d" - Save Program
"i" - Read File
"ac" - Add column
"rc" - Remove column
'''
response = raw_input('> ')
commands = {'a': add_item,
'r': remove_item,
's': show_items,
'd': write_file,
'i': read_func,
'ac': add_column,
'rc': remove_column}
if response.lower() in commands:
stored_data = commands[response.lower()](stored_data)
elif response.lower() == 'q':
pass
else:
print 'Please enter a valid command...'
def add_item(stored_data):
data = {}
for i in stored_data['categories']:
answer = raw_input('%s > ' % i.title()).title()
if i == 'amount':
while not is_num(answer):
answer = raw_input('Please enter a number > ')
answer = float(answer)
elif i == 'monthly':
while answer.lower() not in ('y', 'n'):
answer = raw_input("Please enter 'y/n' > ")
data[i] = answer
stored_data['data'].append(data)
return stored_data
def is_num(string):
try:
float(string)
return True
except:
return False
def add_column(stored_data):
column_name = raw_input('Name the category you would like to add > ')
stored_data['categories'].append(column_name)
for i in stored_data['data']:
answer = raw_input('Enter data for the "%s" category for the "%s" > ' % (column_name, i['name']))
i[column_name] = answer
print '\nAdded column "%s"' % column_name
return stored_data
def remove_column(stored_data):
column_name = raw_input('Name the column you would like to remove > ')
while column_name not in stored_data['categories']:
column_name = raw_input('Please name a valid column > ')
if column_name in ('name', 'amount'):
print "Can't remove this column....."
return stored_data
else:
for i in stored_data['data']:
del i[column_name]
stored_data['categories'].remove(column_name)
print '\nRemoved column "%s"' % column_name
return stored_data
def remove_item(stored_data):
answer = raw_input('Name the item you wish to remove > ')
while answer.lower() != 'q':
for i in stored_data['data']:
if i['name'].lower() == answer.lower():
stored_data['data'].remove(i)
print '%s removed...' % answer.title()
return stored_data
answer = raw_input("'%s' doesn't exist, try again or type q to quit > " % answer)
return stored_data
def show_items(stored_data):
total = 0
for i in stored_data['data']:
print ''
total += i['amount']
for a in stored_data['categories']:
print '%s: %s' % (a.title(), i[a])
print "\nTotal: %s" % total
return stored_data
def write_file(stored_data):
if stored_data['file_name'] == 'untitled':
file_name = raw_input('Enter your file name > ')
else:
file_name = stored_data['file_name']
with open("%s.csv" % file_name, 'w') as f:
f.write("%s\n" % ",".join(stored_data['categories']))
for i in stored_data['data']:
data = []
for b in stored_data['categories']:
data.append(str(i[b]))
f.write("%s\n" % ",".join(data))
print '\n%s.csv saved to working directory........' % file_name
return stored_data
def read_from_file(stored_data):
file_name = raw_input('Name the file you would like to load > ')
while not is_file(file_name):
file_name = raw_input("File doesn't exist. Please enter a valid file name or press 'q' to quit > ")
if file_name.lower() == 'q':
return None
stored_data['file_name'] = file_name
with open("%s.csv" % file_name, 'r') as f:
data = f.readlines()
return data
def convert_data_to_array(data, stored_data):
categories = data[0].strip('\n').split(',')
stored_data['categories'] = categories
for i in range(1, len(data)):
elements = data[i].strip('\n').split(',')
data_dic = {}
for a in range(len(elements)):
data_dic[stored_data['categories'][a]] = elements[a]
data_dic['amount'] = float(data_dic['amount'])
stored_data['data'].append(data_dic)
return stored_data
def read_func(stored_data):
data = read_from_file(stored_data)
if data == None:
print '\nFailed to load file.....'
else:
stored_data = convert_data_to_array(data, stored_data)
print "\nFile loaded successfully...."
return stored_data
def is_file(file_name):
try:
with open("%s.csv" % file_name, 'r') as f:
return True
except:
return False
ui_loop()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment