Do photons lose energy while travelling through space? Or why are planets closer to the sun warmer?

The reason being closer to a heat source makes you warmer is the inverse square law. Think of it this way: If you have a $1~\mathrm{m}^2$ piece of material facing the Sun and located at Mercury's orbit, it will be quite hot. What does the shadow of this square look like at Earth's orbit (about $2.5$ times further away than Mercury)? Well, it will be $2.5$ times bigger in both directions, covering about $6~\mathrm{m}^2$. So the same amount of power can be delivered either to $1~\mathrm{m}^2$ on Mercury or to $6~\mathrm{m}^2$ on Earth. Every square meter of Earth gets about $6$ times less Solar power than every square meter on Mercury. The light is not losing energy to the surrounding medium, even if the medium exists.

Several points that need addressing:

  • The seasons are due to the tilt of the Earth, but not because of the atmosphere. When the sunlight is grazing the ground at a low angle the same amount of heating is spread over a larger area than when the sun is directly overhead, so the temperature drops. The atmosphere has a negligible effect on absorbing radiation (on the way down).

  • The solar system is filled with low density clouds of dust and solar wind, but this does very little to scatter light. If you look at the ecliptic on a very clear night away from light pollution you can just see a faint glow called the zodiacal light, which is sunlight scatter from dust in the disk of the solar system.

  • Photons do not lose any energy when propagating through vacuum (and a negligible amount in the interplanetary medium). It gets colder further from the sun because the photons spread out as the square of the distance from the sun. Imagine a series of spheres of increasing radius centred on the sun. The same number of photons pass through each sphere, but the area of the spheres increases as the square of the radius. So the number of photons per unit area goes down with the square of the distance. So does the heating on an object which absorbs photons.