The earth revolves around the sun in an elliptic orbit. Before the sun's energy reaches the surface it must pass through the atmosphere.
Air takes up space - it consists of billions of air molecules.
Our atmosphere has evolved over 100's of millions of years. N2 is not chemically active so after millions of years it is now the largest composition. H2O formed oceans, large amounts of CO2 are dissolved in the oceans. Plants combine CO2 and H2O in the presence of sunlight to produce O2. CO2 enters mainly from the decay of vegetation, also from volcanoes, animal life and the burning of fossil fuels.