r/PythonLearning • • 12d ago

Showcase I JUST finished my second python project!

Post image
255 Upvotes

34 comments sorted by

View all comments

4

u/Money_Ad_5277 12d ago • Bravo

It's nice to see someone actually learning!

No hate to you, I was like this a year ago.
Few tips:
don't put everything in main.py, you clearly can extract User class to dedicated file called user.py and import it wherever you want.
Operations with accounts.json should be extracted into a separate class
User class shouldn't have any print statements, throw errors/return results and handle it in your program
Transaction should be separate class, you can apply polymorphism here (abstract base transaction and withdraw/deposit transaction) with repr or str magic methods
Toast - exists. Usually it's a popup, but here it just sleep. I guess it's to mimic real world app? But here you would use async/await to not block user input
Please, use PEP linter, it's painful to see a=b and random empty lines before else/elif - you want to maintain good code readability

if deposit_amount + self.balance > 500:
print('You can only have up to $500 in your account')

No magic numbers, use static class/env to store them.
Variable naming: cuser, c, etc
Consistency: you know global, but it create_account you referencing global variable accounts, without letting anyone know that it's global variable

raise SystemExit() - bad, there is "break" keyword to exit loops without exiting whole program

I hope some of those tips will help you improve!

Some advanced stuff (DIP, data structures, lambdas)

save method - should be separate class, injected into User, to act like a db. You can even try to use mongodb/mysql container running to fully understand async/await

main while loop
creating a dictionary like
{
"choise_id": {
"description": "some stuff", action: log_in # log_in is method
}
}

will make your loop significantly smaller

2

u/[deleted] 12d ago

[removed] — view removed comment

2

u/Money_Ad_5277 12d ago edited 12d ago

I'll just num all points to make it easier xD

1 Separate files/Debugging. Pycharm/VSCode has a tool (debugger) to make debugging easier, it doesn't matter home many files you have it will enter or exit them when code reaches certain points, with watch and dynamic evaluation your possibilities are almost unlimited

2 As your accounts.json is a small database

class FileDB: #(DB) can make a base class, but useless for now
def init(self, connection_string): # connection_string is your filepath self.connection_string = connection_string self._file = None

def connect(self): self._ensure_created() # your CREATING FILE STRUCTURE code corruped = self._check_corruption() # your CHECKING FOR CORRUPTED FILE that returns true if file is corrupted and false if not 
if corrupted: # usually you want to throw error, if file is corrupted, for manual fix self._recreate_file() # and problem here, if file is corrupted AGAIN, it won't check it
#Now, you can create a context manager https://www.geeksforgeeks.org/python/context-manager-in-python/ 
def __enter__(self, mode): 
 self._file = open(connection_string, mode)
 return self._file
def __exit__(self):
 self._file.close()

3 They will be a frozen objects (check @ dataclass) - but it's maybe a bit overkill for you

4 Yeah, better name should be nice but you don't need it anyway, as input() is blocking execution and a person can read everything just fine

5 PEP is general rules you want to follow if working with a team and it's focused on readability, making a new line after "if" usually means "end of code block" but you follow it with "else/elif"

6 With FileDB created, your save function will evolve into a repository In simple words: a class that is responsible for managing database entity (creation, deletion, modification or reading)

class FileUserRepository: # (Repository) - you may or may not want to create a base repository
def init(self, db): 
 self.db = db

def get_user_transactions(self, user_id):
 with self.db("r") as cursor:
  accounts = json.load(cursor)
  user = accounts.get(user_id, None) 
  if not user:     return None # or more verbose result  
  return user["transactions"] # check https://refactoring.guru/design-patterns/factory-method to create concrete transaction classes

You won't keep accounts in memory, only in accounts.json
Also assign uuid for users - easiest lookup in general
And user balance should always come from transactions + 100 - 10 couldn't possibly result in 110

7 Because it's not a error per se and program should print declination message and stop gracefully

8 Having a dictionary will help immensely

options = {
 "1": {"description": "Check balance", "action": check_balance}, # here {"description": "Check balance", "action": check_balance} could be a custom class Option("Check balance", check_balance)
 "2": {"description": "Deposit Money", "action": deposit},
}
while True:
 for k, v in options.items():
  print(f"{k}-{v["description"]}")

 user_choice = input("Choose an option: ")

 selected_option = options.get(user_choice, None)

 if selected_option:
  action = selected_option["action"]
  action() # selected_option["action"]() - is fine, but looks strange
 else:
  print("Please choose a valid option")
  # Yep, that's whole while code
print("Goodbye!") # if you throw, you won't reach this point

There can be typos)

Edit: reddit formating and return in enter method

2

u/[deleted] 11d ago

[removed] — view removed comment

2

u/[deleted] 11d ago

[removed] — view removed comment

2

u/Money_Ad_5277 11d ago

Unfortunately, it can't. It's totally different approach that almost requires you to have a class dedicated to working with accounts.json by opening, modifying and closing it

The closed to me is React Native, I don't have capabilities to recommend any of those languages, sry

A very fun experience would be for you to create an atm app with real db behind it (it's free and actually not that complicated), because you will eventually be working with those when developing ios apps. Or extend your program by working with ui (tkinter or similar lib)

2

u/[deleted] 11d ago

[removed] — view removed comment

1

u/Money_Ad_5277 11d ago

Have a great time and a lot of fun studying it!

Okay, I have one last tip: do whatever you want!
A ui for calculator, game-related helpers or a small app that no-one except you will use - that's how we learn things