LONDON — The troubling gap between politics and governance in Pakistan came into stark relief on Tuesday, when lawmakers elected the country’s 12th president just hours after Taliban militants shot their way into a major jail, freeing about 250 prisoners.

As predicted, Mamnoon Hussain, a little-known textiles magnate from Karachi and a loyalist of Prime Minister Nawaz Sharif, won the presidential vote in the national and provincial legislatures. He will take over from President Asif Ali Zardari, a contentious figure who is due to step down on Sept. 8.

The election was another important democratic step in a country that has seen four military coups since the 1950s, the most recent in 1999. It confirmed Mr. Sharif, whose party emerged victorious from May’s general election, as the most powerful civilian leader.

But away from the democratic process lay sobering reminders that Taliban insurgents, not power-hungry generals, now present the most pressing challenge to state authority in Pakistan.