There are a lot of distractions readily available on a computer, and people are easily distracted.
To stay focused while writing code, try to work on paper as long as possible.
Some of the most productive “programming” I’ve ever done was on paper. Or with a colleague at a whiteboard.
That’s because writing code is mostly thinking. Identifying the problem and its constraints; designing the solution within those constraints; considering implications past and future in light of the design: it’s all thinking. And focused thinking can be done without a computer.
At some point there will be typing. But how much more productive, how much more focused, will that typing be when the code is merely expressing an idea already formed in your notebook?