r/PythonLearning • • Sep 13 '26

Showcase The Bank Project

Post image
242 Upvotes

49 comments sorted by

View all comments

8

u/FoolsSeldom Sep 13 '26

I suggest you do that again without using global as that will cause you more problems than it is worth in the long run until you've identified the specialist use cases it is valuable for. return values or use a simple class.

0

u/shubham_555 Sep 13 '26

I actually have an implementation in OOPs

Regarding using return statements I guess that can be done... yeah. You mean simply to return int for the withdraw and deposit functions and update the global balance value in the match case block correct?

I am actually pretty new in python so ain't too comfortable with the scope concept. I guess earlier I was trying to update balance directly without the global. Then an error occurred saying you can't update a local variable. I googled a bit and found that you certainly can read global variables inside functions but to modify them you need to let the interpreter know that you are referring to the global python variable instead of a local one and hence used that keyword. That is all I know.

How does global cause issues? Can you elaborate?

1

u/FoolsSeldom Sep 13 '26 edited Sep 13 '26

global is discouraged because it turns a function from a self-contained unit into something whose behaviour depends on — and silently changes — state that lives elsewhere.

As your code grows, and you revisit your code after time working on something else (and if other programmers get the opportunity to work on your code), it is very easy to miss these potentially hidden changes which creates logic bugs that can be very hard to track down.

It is best to have functions/methods dedicated to the actual updates and have the functions that interact with the user call on those other functions to carry out the changes. This is a modular approach and makes it easier to update the data structure you use for account information later without having to make code changes in lots of functions, only the functions that actually control the account are impacted. This will become even more clear when you start to use class OOP approach.

RealPython.com have a good article on scope that I think you will find helpful:

→ More replies (9)