Hello I am having trouble completing this python assignment. I keep getting the error message list index out of range. h

Business, Finance, Economics, Accounting, Operations Management, Computer Science, Electrical Engineering, Mechanical Engineering, Civil Engineering, Chemical Engineering, Algebra, Precalculus, Statistics and Probabilty, Advanced Math, Physics, Chemistry, Biology, Nursing, Psychology, Certifications, Tests, Prep, and more.
Post Reply
answerhappygod
Site Admin
Posts: 899604
Joined: Mon Aug 02, 2021 8:13 am

Hello I am having trouble completing this python assignment. I keep getting the error message list index out of range. h

Post by answerhappygod »

Hello I am having trouble completing this python
assignment. I keep getting the error message list index out of
range. how do i fix it instruction and code
below.
code:
# Main function
def main():
# User input filename
fname = input("Enter text file name: ")
# Function call to get data from text file
data = ReadFile(fname)
# Loop
while True:
# Function call ro print menu
and get option
option = Menu()

# If user chose option 1 then
printing balance
if option == 1:

CheckBalance(data['Balance'])

# If user chose option 2 then
adding income
elif option == 2:
income =
AddIncome(data)

data['Balance'] += income

# If user chose option 3 then
adding expense
elif option == 3:
expense =
AddExpense(data)

data['Balance'] -= expense

# If user chose option 4 then
printing monthly total
elif option == 4:

MonthlyTotal(data)

# If user chose option 5 then
printing monthly statement
elif option == 5:

PrintStatement(data)

# If user choce option 6 the
writing monthly statement to
# a file
elif option == 6:

StatementToFile(data)

# If user chose option 7 then
changing name of customer, changing
# month, and clearing
expense/income data. Finally writing data to
# file and breaking the
loop
elif option == 7:

data['Name'] = ChangeName()

data['Month'] = NewMonth(data['Month'], data)

data['Expense/Income'] = {}

SaveToFile(data, fname)

break
else:

print("\nError: Invalid option!")
# Function to read data from text file
def ReadFile(filename):
user_data = {}
File = open(filename, 'r')
lines = File.readlines()
user_name = lines[0].strip()
balance = float(lines[1].strip())
date = lines[2].strip()
user_data['Name'] = user_name
user_data['Balance'] = balance
user_data['Month'] = date
user_data['Expense/Income'] = {}
for i in range(3, len(lines)):
line =
lines.split('$')
name = line[0].strip()
amount =
float(line[1].strip())

user_data['Expense/Income'][name] = amount
File.close()
return user_data
# Function to print menu and return user option
def Menu():
print('\n1. Check balance')
print('2. Add income')
print('3. Add an expense')
print('4. Check monthly total')
print('5. View monthly statement')
print('6. Save monthly statement to file')
print('7. Exit')
user_option = int(input("\nSelecet option:
"))
return user_option
# Function to print balance amount
def CheckBalance(balance):
print("\nAccount balance:
${:.2f}".format(balance))
# Function to add income
def AddIncome(data):
name = input("\nEnter source of income:
").title()
amount = float(input("Enter amount of income:
$"))
if name in data['Expense/Income']:
data['Expense/Income'][name]
+= amount
else:
data['Expense/Income'][name]
= amount
return amount
# Function to add expense
def AddExpense(data):
name = input("\nEnter name of expense:
").title()
amount = float(input("Enter amount of expense:
$"))
if name in data['Expense/Income']:
data['Expense/Income'][name]
-= amount
else:
data['Expense/Income'][name]
= -amount
return amount
# Function to print monthly total
def MonthlyTotal(data):
total = 0
for i in data['Expense/Income']:
total +=
data['Expense/Income']
print("\nMonthly total expense/income:
${:.2f}".format(total))
# Function to print the monthly statement
def PrintStatement(data):
print("\n{}\t{}".format(data['Name'],
data['Month']))
print("\n\nMonthly Statement")
print('-' * 40)
print('Name','-'*28,'Amount')
print('-' * 40)
for k,v in data['Expense/Income'].items():
print("{:<30}{}".format(k,
'${:.2f}'.format(v).rjust(10)))
print("Total Balance:
${:.2f}".format(data['Balance']))
# Function to write monthly statement to a file
def StatementToFile(data):
fname = input("\nEnter file name to save:
")
File = open(fname, 'w')
File.write("{}\t{}".format(data['Name'],
data['Month']))
File.write("\n\nMonthly Statement\n")
File.write('-' * 40)
File.write('\nName '+'-'*28+' Amount\n')
File.write('-' * 40 + '\n')
for k,v in data['Expense/Income'].items():

File.write("{:<30}{}\n".format(k,
'${:.2f}'.format(v).rjust(10)))
File.write("Total Balance:
${:.2f}\n".format(data['Balance']))
File.close()
# Function to change month
def NewMonth(month, data):
File = open(month+'.txt', 'w')
File.write("{}\t{}".format(data['Name'],
data['Month']))
File.write("\n\nMonthly Statement\n")
File.write('-' * 40)
File.write('\nName '+'-'*28+' Amount\n')
File.write('-' * 40 + '\n')
for k,v in data['Expense/Income'].items():

File.write("{:<30}{}\n".format(k,
'${:.2f}'.format(v).rjust(10)))
File.write("Total Balance:
${:.2f}\n".format(data['Balance']))
File.close()
months =
['January','February','March','April','May','June','July','August',


'September','October','November','December']
month = month.split()
if month[0] == 'December':
month[0] = 'January'
month[1] = str(int(month[1])
+ 1)
else:
month[0] =
months[months.index(month[0])+1]
new_month = month[0] + ' ' + month[1]
return new_month
# Function to change name
def ChangeName():
new_name = input("\nEnter new name: ")
return new_name
# Function to write new data into text file
def SaveToFile(data, filename):
File = open(filename, 'w')
File.write(data['Name']+'\n')
File.write(str(data['Balance'])+'\n')
File.write(data['Month']+'\n')
File.close()
# Main function call
if __name__ == "__main__":
main()
txt file:april2022.txt
John Doe
1245.98
April 2022
Gasoline -85
Food -250
Paycheck 1234.56
Deposit 50
Join a community of subject matter experts. Register for FREE to view solutions, replies, and use search function. Request answer by replying!
Post Reply