I would suggest reading Martin Silvertant's answer to Why is the shape of the letter “a” in computer fonts different from its handwritten version? who answers this very question very thoroughly.
The history of typography is very interesting.
Here is a visual graphic showing the evolution of the letter g.
Note that the written style of the letter g did exist and looked something like the g on the top, where the print/computer one is based on the bottom.
These kinds of mysteries abound in English, and indeed, likely in all languages. Quirks, habits, and inconsistencies shape the way we write and speak.
Fun fact, google recently changed from its previous g to the written style g.
They also changed the colors and simplified all of the letters.
Modern letter forms are the product of a combination of tradition, technical considerations, readability considerations, and interactions between handwriting and printed texts as well as between several flavors of the latin alphabet (roman type, blackletter and gaelic). We can’t make more than educated guesses as to why certain variants survived while others didn’t. After all, there isn’t any committee that decides things like this, language evolves naturally, usually for efficiency. For example conjunctions are convenient and faster than saying “can not” “will not” and “do not” all the time. Can’t, won’t, and don’t is simply easier, but no one formally decided this.
It can be assumed the reason two variants of a and g mainly survived was because the two-storey variants are not feasible in handwriting, while they have advantages in print. The double-storey a is easier to distinguish from the letter o compared to this one: a. The double-storey g is narrower and also easier to distinguish due to its unique shape. So essentially the double-story versions help us not mix them up with other letters so reading is faster and with no confusion.