r/PythonLearning • u/Stonyax97 • 4d ago
Showcase I JUST finished my second python project!
Lately I have been working on this ATM For Teens, just to understand OOP and some concepts more (which I REALLY DID)
this isn't meant to be a real ATM (obviously, it's very beginner and not security is there), here is my First project.
So, I have learnt quite a lot since last project, I learnt a bit more about python syntax, I also understood the approach of classes a lot better. I learnt git (just the essentials).
Since I always wanted to Make iPhone apps, and now I have a Mac, I'm thinking whether I should start learning swift and swiftUI, or move to something else, or keep learning python. what do you guys think? I Do want a job as an IT engineer (or anything with coding tbh, cybersec too but that would require C knowledge a bit more lol)
Otherwise, if you guys have any criticism or suggestions for the ATM, then I would be veryyy happy to hear some! here's the repo: https://github.com/Stonyax97/ATM-For-Teens
6
u/mobile_site_refugee 4d ago
I’d recommend working on formatting. Try putting your classes in a separate file, then importing them.
I don’t know why you keep calling os.system(‘clear’), but you probably don’t need that. I don’t see why you’d need globals either, that’s a mess you want to avoid generally.
Also, a bit nitpicky, but I don’t think “time as t” is a standard anywhere, at least not like “numpy as np” is. Helpful to keep it standard if anyone else looks at your code.
0
u/Stonyax97 4d ago
ik about the separate file, but in a program where the code is less than 500 lines it makes no sense to me. It's actually simpler to add things and debug things this way for me at least (in this small program)
os.system('clear') is to clear the terminal, I want to make the program feel like a TUI without using any actual TUI lib (like curses for example).
I don't really have to follow standards in simple aliases. but thanks tho, plus anyone will first read the import time as t and it would be a bit clear. but thanks again!
3
u/mobile_site_refugee 4d ago
Alright man.
You should be using the Path class from pathlib for your FILE_PATH constant as well.
1
2
u/S1enderVoid 3d ago
os.system('clear') is to clear the terminal, I want to make the program feel like a TUI without using any actual TUI lib (like curses for example).
os.system()is unsafe and has been deprecated in the newer Python versions, I recommend you use the subprocess module instead: https://docs.python.org/3/library/subprocess.htmlAlso, if you like TUI interfaces you can check out the following, just sharing it in case you'd maybe want to use them for future projects.
1
u/Stonyax97 3d ago
Damn i did not think os.system(‘clear’) would be unsafe. Why is that tho?
Yeah i will definitely use the subprocces module thanks 🙏
For rich and textual… broooo thank you so much this is way better than curses 😭
It’s basically overpowered print()2
u/S1enderVoid 3d ago
Damn i did not think os.system(‘clear’) would be unsafe. Why is that tho?
Oh, apologies . . . It is unsafe if you're dealing with commands that require variables that can be changed by the user, you can probably guess where this is going, but it makes it quite easy for an attacker to carry out shell injection which is a no-no. Subprocess makes it easier to deal with, but you still have to do some input sanitization.
In your case it is safe, but again it poorly handles output and a lot of other stuff. Plus it's almost deprecated, so people on newer python versions will get trouble.
4
u/Money_Ad_5277 4d ago
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/Stonyax97 4d ago
Hey! Thanks for the advice!
for putting user class into diff file, well at such a small program scale it makes 0 sense to me. it just makes debugging hard and adding features too. but at a bigger scale? yeah def. Il keep this in mind tho thanks.
"Operations with accounts.json should be extracted into a separate class"
how could that be done? could u give a little example if possible or just explain?
"Transaction should be separate class, you can apply polymorphism here (abstract base transaction and withdraw/deposit transaction) with repr or str magic methods"
I have to look a bit more into this, but when making this I tried to challenge my self to make it using the syntax I know. and did learn a few things if needed.
"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"
yeah, idk I just used the name it popped up first, cuz it pops out of nowhere lol. but yeah I should defiantly call it wait or sum like that.
plus the waiting time is just enough to read, 1.5s isn't much wait time. but il take it into consideration.
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
how is the a=b painful? I
empty lines for me are acc for readability, I mostly remember code structure, so it helps when debugging and adding features.
PEP linter is actually nice! il just have to get used to its formatting since I'm used to my own philosophy lol.I don't want 19 years old signing up. if ur not eligible then the program quits. simple. Its intentional. breaking the loop makes no sense here. do I give him a chance to retype?
'savemethod - 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'could you show me how this would look like? I can't imagine a save function as a class? what args do we pass?? save is basically assigning the changed in memory variables to the accounts and then writing it to json.
'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'
could u explain why a choice id dictionary is better here? I don't see an apporach.Thank you so much for this feedback!
2
u/Money_Ad_5277 3d ago edited 3d 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 classesYou 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 1107 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 pointThere can be typos)
Edit: reddit formating and return in enter method
2
u/Stonyax97 3d ago
Hey!
Ive took the time to actually understand this and look up the terms.
this is gold advice, thank you so much. but at this scale? it makes NO SENSE.
first the FileDB. why should I create my own wrapper when with open() does the job for me?
I agree with the fact that it would help make the code cleaner plus no scattered with open file everywhere.for the data class that's frozen, I agree too, transactions are meant to be frozen. il try to look into it.
Il set up PEP right now and start using it! thanks!
"Also assign uuid for users - easiest lookup in general"
when logging in, I wouldn't possibly ask for the user to input UUID. id have to loop through each dict to find the username inside it, then use dict.keys() to get the UUID. kinda complex. but I get the approach, many people will have the sane name. yk this project is just for fun and learning not a real project lol. that's very clear the way passwords are stored."You won't keep accounts in memory, only in accounts.json"
wouldn't they need to stay in memory when interacting with it eventually?
for the balance being. created using transactions history. that is SMART. I love it. I would implement this in v1.2.2.
"7. Because it's not a error per se and program should print declination message and stop gracefully"
I forgot the thing we where talking about here could u re explain LOL sorry
8. I understand the approach here, and it's actually smart, but wouldn't that action() result in too many functions?
2
u/Stonyax97 3d ago
oh oh I get it now. you meant, instead of loading the whole accounts dict, we only load the logged in user only. ahhhh I see. how could that be implemented in the easiest way? (no huge structure changes, I want to move to swift or c or rust). also what would u suggest for me to do next?
2
u/Money_Ad_5277 3d 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/Stonyax97 3d ago
Ah I see how it is.
Thanks tho dude like this is actually helpful!
Yeah I could build an ATM app, but I’m tired of the ATM concept, feels useless to me. So I’m gonna go head first into swift 😭
There’s a lot of tutorials out there and AI for personal questions, so Im not that worried. I use AI as a question machine and for hints and it’s been doing wonder to me.Thank you for everything! Btw I pushed v1.2.2 if you want to check it out. It’s very simple changes but I implemented the balance created from transactions history. I love it!
1
u/Money_Ad_5277 3d 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 things1
u/Money_Ad_5277 3d ago
I understand that it can make no sense, but I was given a problem like this and was forced to do it this way xD
And most of my tips are fixes of my errors from back thanFileDB. repositories - yes, overkill, but when you want to switch to real db (or api), or even test an app, they come in handy. Because form is almost as important as content
uuid - when user log in, you store only uuid, without email, password and whole transaction array.
Also having array of users like [{id: 1, username: "user 1"}, {id: 2, username: "user 2"}]
Lookup by id becomesuser, *_ = list(filter(lambda user: user["id"] == user_id)) or [None] # python devs are going to kill me for thatYou can change key to username to lookup user by username.
Accounts in memory - yes - for file approach, but only for a short period of time, no - for db approach
7 you raised an error on line 256 to exit program instead of using break
8 Yes, but it's common problem of all apis, you can't magically understand what user wants and transform it to a function
2
u/Stonyax97 3d ago
Ah yeah I see. Thanks 🙏
Btw what’s your current status with coding/programming? Is it your job? Hobby? Or side project?
1
u/Money_Ad_5277 3d ago
Hobby -> field of study -> job
2
u/Stonyax97 3d ago
where are you now?
2
u/Money_Ad_5277 3d ago
At job and field of study steps
1
u/Stonyax97 3d ago
Oh that’s nice dude wish you the best. I also want to follow in the same steps. In what field are you? Backend, front end? Cybersec?
→ More replies (0)
1
1
u/Zestyclose_Cod_898 1d ago
Can some tell me what kind of questions they ask for data center engineer python automation, hardware specificity in interview?
•
u/Sea-Ad7805 4d ago
Nice, run program above by clicking Memory Graph Web Debugger and see its state change step by step.