I'm looking for ideas on how to optimize the following code. I don't really know how to condense anything, I'm still very new to coding and this is the first time I've really created anything besides "Hello World".
import pandas as pd
import csv
#Method that calculates the Current Budget of the contents in the .csv file
def currentBudget():
fileTransaction = open("transactions.csv", "r")
info = fileTransaction.readlines()
fileTransaction.close()
budget = 0
for line in info[1:]:
budget += float(line.split(",")[2])
print("\nCurrent Budget €"+str(budget)+"\n")
#Introductory using ASCII Markdown for Headers
def introduction():
print("Budgetísimo".center(120,"-"))
print("Welcome to Budgetísimo, a personal budget application that allows you to record and keep track of all your transaction\n")
#Choices of the User
def userChoice():
print("What would you like to do: ")
print("(a) Record a Transaction")
print("(b) Calculate Current Budget")
print("(c) Exit Programme")
def userTransactionOutputOption():
print("Please select one of the following options: ")
print("(a) View Transactions using Date Range")
print("(b) View specific Number of Transactions")
def transactionDate():
data = pd.read_csv('transactions.csv', sep=",", index_col=0)
data['Date'] = pd.to_datetime(data.Date)
userStartDate = input("Start Date (DD-MM-YYYY): ")
userEndDate = input("End Date (DD-MM-YYYY): ")
afterStartDate = data["Date"] >= userStartDate
beforeEndDate = data["Date"] <= userEndDate
beweenDates = afterStartDate & beforeEndDate
filteredDates = data.loc[beweenDates].sort_values(by="Date")
print(filteredDates)
#The code
def userInputs():
prompt = True
while prompt == True:
userInput = input("\nEnter your Choice: ").lower()
df = pd.read_csv('transactions.csv', sep=",", index_col=0)
dfData = pd.DataFrame(df)
if userInput == "a":
fileTransaction = open("transactions.csv", "a", newline="")
print("Please enter the following data when prompted to do so: ")
userDescription = input("Description: ")
fileTransaction.write(userDescription+",")
userDate = input("Date (DD-MM-YYYY): ")
fileTransaction.write(userDate+",")
userAmount = input("Amount: ")
fileTransaction.write(userAmount+"\n")
currentBudget()
print("Your Transaction has been recorded! :) \n")
fileTransaction.close()
elif userInput == "b":
currentBudget()
transactionHistory = input("Would you like to see your Transaction History? (Y/N): ").lower()
if transactionHistory == "y":
userTransactionOutputOption()
userTransactionOutput = input("Enter your Choice: ").lower()
if userTransactionOutput == "a":
transactionDate()
elif userTransactionOutput == "b":
howManyTransaction = int(input("Please specify how many Transactions you want the System to Return: "))
print("\nYour Last "+str(howManyTransaction)+" Transactions: ")
print(df.tail(howManyTransaction))
else:
print("Please enter A (Date Range), B (Specific Transaction).")
elif transactionHistory == "n":
print("Your Last 10 Transactions: ")
print(df.tail(-10).sort_values(by="Date"))
else:
print("Please enter Y (yes) or N (No).")
elif userInput == "c":
prompt = False
print("\nProgramme Terminated\n")
exit()
else:
print("Please enter A (Transaction Input), B (Transaction Output), C (Exit Programme).")
I am unsure how to reduce it, I have a file called app.py where I put the methods, but there is one method that contains what is essentially the entire code. I know this is not really good practice, but this is the first time doing anything like this and I'm really lost on what I should be doing. If anyone could help that would be amazing! :)
print
s in functions to call repeatedly! One thing you might consider is factoring the different actions you take, depending on theuserInput
variable, into separate functions. That way, the body of your main function is cleaner and easier to read, and then you have a separate function for each functionality. \$\endgroup\$