Incidentially it reminds me of an interesting fact I heard: FAA regulations also require that there be two people in the cockpit at all times, no exceptions. If the pilot or even co-pilot wants to even use the bathroom briefly, thus a flight attendant needs to take their place for that time. The reasoning is to avoid a scenario where a suicidal pilot decides to take the rest of the plane down with them.
This is far from the primary reasoning for the rule. Having two pilots always on the flight deck greatly reduces the likelihood of human error compared to sole operation. Pilots and co-pilots are constantly forced to verbalize flight conditions, control inputs, and reactions to one another in a way that makes them much more salient. This is the same reason surgery teams include multiple doctors.
More generally, sterile cockpit rules increase flight crew members' attention to essential operational activities. This is especially true during critical phases of flight (i.e., taxiing, take-off, landing, flight below 10,000 ft, etc.) Flight attendants can and do enter the cockpit during flights, but it happens pretty rarely. Pilots leaving the flight deck for any reason is even more unusual.