Well, there is also an aspect of practicality there… If you have a piece in the key of D major, then there will (very likely) be a bunch of F# notes. Since we have a key signature at the beginning of the piece and at the beginning of every line, we know that when we see a note sitting on the second line from the top (in bass clef), it is actually an F#. You could dispense with the key signature and write every time the # sign before each F - that would work, but be less practical. Even less practical, imagine you’d write Gb instead every time where there should be an F#, then you’d have to most likely also use a bunch of “natural” signs to undo that flattening again, as there certainly also are a lot of natural G notes in your song. So, the whole thing would be much more messy to write, but even more so to read.
Also, all this is connected to the circle of fifths - might be worth checking out if you are not familiar with it already!
But, really neat to see someone asking these questions - this is something I learned a long time ago, and never really questioned it or thought more about it