Why does a gas heat up when compressed and cool as it expands?

Adiabatic compression

As a container wall moves in  - compressing the gas - it increases the speed of each molecule that hits it (think of hitting a ball with a racket), so increasing the temperature of the gas. The faster the wall moves in the greater the extra speed given to each molecule it collides with , and the greater the temperature increase.

Adiabatic expansion
As the container wall moves out - and the gas expands - the gas molecules are slowed down by their collisions with the receding wall (think of killing the pace of a ball by moving the racket back as it hits it), cooling the gas. You might also think that the faster the wall moves away the more the gas is cooled - but another factor is also in play; the faster the wall moves away, the greater the number of molecules that aren't moving fast enough to hit it at all - and so aren't slowed down by the gas' expansion. This latter factor predominates - so that the maximum amount of cooling to a gas occurs over a slow expansion.

If the containing wall is moved out suddenly - faster than any of the gas molecules are moving - then no cooling occurs at all, as none of the gas molecules is slowed by impact with the receding wall. This situation is similar to a gas' expansion into a vacuum where no cooling occurs either.

So the heating or cooling that occurs during an adiabatic compression or expansion depends on the speed at which it happens. If the change in volume occurs very slowly, then both compression and expansion follow the same curve, and are called 'reversible'. Such a reversible adiabatic compression or expansion follows a mathematically derivable curve = constant. Under faster, irreversible adiabatic changes the gas temperature ends up higher than it would have been under a reversible compression or expansion.
links:
Isothermal and adiabatic expansion
Adiabatic expansion & compression
Hyperphysics: Adiabatic process