The primary function of the alveolar walls is to facilitate the exchange of oxygen and carbon dioxide between the alveoli and the blood. This process occurs through diffusion, driven by the concentration gradients of these gases. The thinness of the alveolar walls and the presence of surfactant are crucial for minimizing the diffusion distance and maintaining the alveoli open during breathing.