Why do we use external pressure when calculating work done by gas?
The ideal gas law (or other equation of state) is valid only when a gas is in thermodynamic equilibrium.  In a rapid irreversible expansion or compression, the pressure depends not only on the volume (and temperature) but also on the rate of change of volume.  This is because a gas has a viscous property which acts to dissipate mechanical energy and convert it to internal energy. In a reversible process, where the rate of change of volume is negligible, the ideal gas law can be used.  But the ideal gas law (or any other equation of state for that matter), cannot be used to determine the pressure (or more precisely, the compressive stress) in an irreversible process. 

At the interface between the gas and its surroundings (say the inside face of a piston) where the gas is doing work, by Newton's 3rd law, the pressure of the gas matches the "external pressure," and, if this external pressure is known, the amount of work that the gas does on its surroundings can still be determined. In the "vertical piston" example, if one does a force balance on the piston during the process, one obtains:
$$P_{gas,I}=\frac{Mg}{A}+P_{atm}+\frac{M}{A}\frac{d^2V}{dt^2}=P_{ext}$$ where $P_{gas,I}$ is that gas pressure at the interface with the piston (the subscript I is present because, in an irreversible process, the pressure of the gas within the cylinder may not even be uniform), and the mass times acceleration of the piston is included. The work done by the gas on its surroundings during the process is obtained by integrating this equation between the initial and final equilibrium states to yield$$W=\int{P_{gas,I}dV}=Mg\Delta h+P_{atm}\Delta V=\int{P_{ext}dV}$$This equation acknowledges that, as a result of the viscous property of the gas, the kinetic energy of the piston has been damped out by the time the system reaches its final state.