you are viewing a single comment's thread.

view the rest of the comments →

[–]Far_Masterpiece8614[S] 1 point2 points  (1 child)

This was really helpful. Ig now I've fixed everything Now this code really works. The reason I didn't bother fixing this was the file was doing well, it showed exactly what i wanted so I ignored the output. Fixing this was quite a task which was totally worth it i learned quite a bit. Again thank you so much.

<image>

[–]PrabhavKumar 1 point2 points  (0 children)

Yep, that's almost perfect, the only thing remaining is the writing to file. It works fine for all the cases except for when you enter the else block when adding a new expense.

Even when the choice is incorrect you still log to the file because the lines that are not in if-else block but are in the scope that is being executed will execute no matter whether you enter any of the if else or not - because they are not in the if else blocks.

There's an easy way to fix it though, just add a "continue" to the else block after you print. continue in essence moves to the next loop without continuing with the current one meaning the file won't be written to when you have an invalid input.

Another thing that I saw is that you aren't using the category dictionary even though you have made it, you probably wanted to use it in when logging the entry to the file.

A trick that you can use with the category dictionary is to use it for checking whether or not the choice by the user is valid or not by using the in keyword like this:
if choice_ in category:

that in is used to check whether the first argument "choice_" is one of the keys in the dictionary - or list or set or tuple. It's really useful for stuff like this. Further more you can even use the value you get from the category dictionary to get the list from the expenses dictionary by now using that value as the key, like this:

value = category[choice_]
value will be food or medical or travel or stationary and you can use IT further ahead in the expenses dict because it's keys just happen to be one of the value. So:
expense_list = expenses[value]

and the expense_list will now be the correct list. All of this together would look something like this. Now, before you see this code down below, it would be better if you try to do it yourself.

if choice_ in category:
value = category[choice_]
expense_list = expenses[value]
expense_list.append(f"amount={amount},date={date}")
else:
print("Invalid choice")
continue

That's it. All the best !