Giulio Andreotti, who has died aged 94, was the ultimate insider of Italian political life. For half a century he was at the heart of power. His tenure at the highest echelons of government was unequalled in Europe. From the early 1960s to the early 90s, he was – almost uninterruptedly – either prime minister or a senior minister. Andreotti was in all but six of the 45 governments that ran from May 1947 to April 1992, led seven of them and, at various times, was the minister of defence, foreign affairs (five times), finance, treasury, and interior. He held the post of prime minister for longer than any other postwar Italian politician except Silvio Berlusconi, yet he never led the Christian Democratic party.

His tenacity in remaining at the centre of affairs became a source of fascination in itself. Just as Julius Caesar had become Divo Giulio, the god Julius, so the makers of the 2008 film Il Divo, a biopic about Andreotti, attributed to the infinitely pragmatic modern Giulio seemingly mesmeric powers all the more striking for his superficial drabness.

Andreotti was the most controversial figure in the political life of what came to be known as Italy's First Republic (from 1946 to the political and constitutional turmoil of 1992-94). As a senior Christian Democrat, he played a leading part in all significant political watersheds while never taking a major political initiative. Few of Italy's contentious issues left him untainted, from those surrounding the construction of Rome's Fiumicino airport, which opened in 1961; to the murky banking scandals of Roberto Calvi, found hanging under Blackfriars bridge, London, in June 1982; and Michele Sindona, found poisoned in his cell in 1986 while serving a life sentence for murder.

Magistrates asked parliament 27 times for permission to investigate Andreotti, and 27 times parliament rejected the request. Yet he was never directly implicated, let alone indicted, in the most significant of them all, the mother of all scandals, the great Tangentopoli ("bribesville") affair of the 1990s that brought down the Christian Democratic party along with the other four parties that made up almost all the governments of the First Republic. Andreotti's personality and, above all, his innermost political convictions, remained shrouded in mystery – an extraordinary achievement for someone so frequently in the public eye, so often investigated by the press and magistrates, so often interviewed, and so prolific a writer.

This most powerful of men lived modestly with his wife, Livia, whom he had married in 1945, and with whom he had two sons and two daughters. Andreotti, who had interceded on behalf of endless supplicants like a true padrino (godfather), did not use his power to pursue personal wealth or to enhance the prospects of his closest relatives.

He had a slight malformation of the spine that gave him a stooping gait, which was used by caricaturists to represent him as a malevolent, hunchbacked dwarf (he was actually quite tall) with disproportionately large ears, always dressed in black, lurking in the dark corners of the republic, holding the strings of the political puppet show that unfolded year after year.

He was born in Rome. His father died when Giulio was two, and the family survived on his mother's miserly widow's pension. While at university, he joined the Federation of Italian University Catholic Students and became its president in February 1942. This enabled him to meet and befriend many of the personalities who would dominate post-fascist Italy. Andreotti obtained a first-class law degree from the University of Rome in 1941, specialising in ecclesiastical law. His frail physique prevented him from being drafted, but not from spending most of the second world war establishing a formidable network of connections and making friends of differing political hues. In the dying days of the fascist regime, Andreotti cultivated the entire Catholic establishment vigorously, especially those notables who had spent the years of fascism lying low, waiting for a change of fortune.

Having secured his rear, he set about energetically organising the new generation of Catholic intellectuals and politiciansn 1944, at the age of 25, he became a member of the national council of the newly founded Christian Democrats. In 1946 he was elected to the assembly as one of the representatives for Rome. He was subsequently elected in all parliamentary elections until 1991 when he was appointed life senator (one of the five such posts in the gift of the president of the republic).

His control over the Christian Democratic party machine in Rome and beyond was overwhelming. He was widely regarded by the higher echelons of the civil service to be "their" man. He also had the trust of the Vatican, and Rome's most prominent property and banking interests. One of the results of this meticulous and painstaking accumulation of power was that he was usually able to top the chart of personal preference votes at all elections (under the old electoral system, voters could indicate, after voting for a party, which of the candidates on the list they preferred).

In 1947 De Gasperi appointed him undersecretary to the presidency of the council. This non-cabinet post – equivalent to a minister without portfolio – enabled him to be at the centre of all government activities. He was, in effect, the prime minister's main fixer. However, he was also given a practical task: the reorganisation of the cinema industry. Andreotti piloted through parliament legislation giving the government greater power over the economy, which helped the industry to produce, by 1954, some 200 films a year, making Italy the largest producer of films in the world after the US.

His uninhibited attitude towards artistic production contrasted sharply with that of his more traditionalist colleagues: "More legs and fewer rags," he intoned as he censored Vittorio De Sica's 1952 film Umberto D, the dismal story of a struggling pensioner. His wishes were fulfilled as the industry prudently moved away from the sombre neo-realism of the immediate postwar years towards mildly saucy comedies and the sub-De Mille-style epics, set in antiquity with their cast of thousands of buxom Roman ladies. This relaxed pragmatism became his trademark. It permitted him to shift from the left to the right and back again without anyone being particularly surprised.

In 1954, after the death of De Gasperi, Andreotti became his own man, organised his own supporters and became home secretary interior minister in the first of the many governments led by Amintore Fanfani. Between 1955 and 1958 he was minister of finance, then minister of defence, holding this post from 1959 to 1966 – unmoved and unmoveable – while prime ministers succeeded each other: Antonio Segni (1959), Fernando Tambroni (1960), Fanfani (1960-62), Giovanni Leone (1963) and Aldo Moro (1963-66).

He then moved on to the industry ministry (1966-68). Out of government between 1968 and 1972, he "missed" (by luck or supreme cunning) the dying days of the first centre-left government, the student revolt, the rebirth of working-class militancy (the hot autumn of 1969) and the first wave of terrorism. Yet he was far from idle. As leader of the Christian Democrat parliamentary group, he played a leading and mediating role in the incessant factional party infighting.

In the early 1960s he was a pillar of the party's right, whose main objective was to prevent the formation of a coalition government with the Socialist party – the centro-sinistra (centre-left). At the last minute, the swift-footed Andreotti switched his support and rallied round Moro and Fanfani, the architects of the new coalition whose aim was to reform the country while isolating the communists.

Andreotti had thrown his weight behind the new centre-left coalition in 1963 only after ascertaining that it was acceptable to those whose assent he regarded as crucial: the US and the Vatican. He knew them well. As minister of defence, Andreotti was the politician closest to the Americans. As a personal friend of Cardinal Giovanni Battista Montini, who was about to become pope as Paul VI, he was intimately acquainted with Vatican thinking. Andreotti backed novelties only after he had secured the maximum consensus.

For some, politics is the art of bold decisions, striving forward, changing the landscape and making a difference. But for Andreotti, politics was about caution and prudence. It was the art of managing human affairs in an imperfect world. People were fallible and corrupt, flawed and sinful, and one had to accept them as they were. They might be changed by divine intervention, but not by human intercession.

This attitude enabled this genuinely religious man, who went to mass every day and to confession every week, to behave with what may appear as unchecked cynicism. His most celebrated aphorism was his response to a journalist who wondered whether Christian Democrats would ever be weary of wielding power: "Political power wears out only those who haven't got it."

By 1972 the Socialist party had withdrawn its support from the government, and the centre-left coalition came to an end. A period of great political uncertainty unfolded. Without the socialists, it was extremely difficult to form a stable government – even by Italian standards. Andreotti emerged as prime minister (1972-73), leading a weak coalition of the centre-right, thus consolidating his image as a conservative scourge of the left, whether communist or socialist.

That was a time of great changes: the end of the long postwar boom, the oil crisis and the termination of the Bretton Woods system of fixed exchange rates. Italy, a country with few energy resources and a weak currency, reeled under the impact. Terrorism escalated, as did organised crime. But it was also a time of rapid modernisation. Workers and women gained new rights, divorce was legalised, central power was devolved. Andreotti's "rightwing" government did not forcefully oppose these changes. In practice, it facilitated them.

The Communist party made great electoral gains in 1975 and 1976, and called for a "historic compromise" with the Christian Democrats. Moro, now de facto party leader, had come to the conclusion that a deal with the communists was inevitable. It was necessary to proceed gradually. First the communists would be "allowed" to support a Christian Democrat government in parliament, then they would have a major say in its programme, and, eventually, in the fullness of time – after a lengthy apprenticeship, once it had become apparent that they were not bloodthirsty Stalinists but quite reasonable social democrats – they would be brought into government.

For this to succeed, it was indispensable to have a prime minister who would reassure the Vatican, the Americans, the European community, big and small business and Italy's vast bureaucracy. Who better than Andreotti to perform this delicate balancing act? He loyally accepted and led the government from 1976 to 1979.

However, Moro's kidnapping and assassination by the Red Brigades in 1978 caused such a momentous political crisis that the compromise did not survive, though Andreotti did. He used one of his rare absences from government (1979-83) to forge a new alliance with the staunchly anti-communist socialist leader Bettino Craxi and those Christian Democrats who, unlike him, had been hostile to an entente with the communists. When Craxi became prime minister in 1983, Andreotti was back in government as foreign minister, holding the post until 1989. And then, for the seventh and last time, he became prime minister.

Like many before him, Craxi had failed to modernise the country, and during his premiership, moral standards in the conduct of public affairs degenerated further. Andreotti appeared to take less and less interest in domestic matters. This became more evident when, having regained the office of prime minister (1989-92), he repositioned Italy's role in international affairs, enthusiastically supporting Mikhail Gorbachev's programme of perestroika (energetically backed by Pope John Paul II), distancing himself a little from the US (he thought, quite rightly, that Washington had never been able or willing to understand Italian political problems), while remaining staunchly pro-European. He played a key role in the Maastricht treaty (1992), particularly in obtaining Margaret Thatcher's endorsement – no mean feat. As he said, much later: "Mrs Thatcher is a woman of great intelligence … but she has an authoritarian disposition. It is not easy to sit around a table with her."

By 1992 the tocsin bell was ringing for the unlamented First Republic. Andreotti appeared to survive unscathed from the corruption investigations of the Tangentopoli affair, but the past was catching up with him. In March of that year, his righthand man in Sicily, Salvo Lima, was murdered by the mafia in what was seen as an internecine dispute (Lima was also the link between Andreotti and the mafia). Andreotti was later accused by Tommaso Buscetta, a mafia supergrass, of having been involved with organised crime, and of having exchanged a ritual kiss with the capo di tutti i capi (boss of all bosses), Salvatore Riina. The kiss was an unlikely story, but the Palermo court investigating his links with the mafia did accept that such links had existed, but only until 1980, and that he could no longer be prosecuted – not quite the vindication he had hoped for.

That Andreotti had had links with the mafia did not surprise anyone, but his last administration was more decisively anti-mafia than any other postwar Italian government. Much of the credit goes, of course, to brave investigative magistrates such as Giovanni Falcone and Paolo Borsellino, who were both murdered in 1992, but Andreotti too moved firmly against Cosa Nostra. More powers were granted to the police. Co-ordination between the various anti-mafia police "pools" improved. Mafiosi were kept in jail pending appeal (a departure from previous practice). Bidding for public contracts – a traditional source of revenue for the Sicilian and Neapolitan mafia – was made more transparent. Indeed, the murder of Lima was widely regarded as a mafia revenge for Andreotti's decision to call off the pact of mutual tolerance he appeared to have with Cosa Nostra, another instance, claimed his opponents, of his amazing duplicity.

Andreotti was also accused of having ordered the murder of a rightwing journalist, Carmine Pecorelli, in 1979. Pecorelli was the editor of a small-circulation newspaper, allegedly close to the secret services and specialising in scandal-mongering and blackmail. He had, or so it was said, some evidence that both the "secret services" (ie the CIA) and Andreotti had been connected with the killing of Moro – one of the many groundless conspiracy theories that have entertained Italians over the years. The Pecorelli affair lasted, incredibly, for more than 20 years. The connection between Pecorelli and Andreotti was never established, but in 1996 the prosecutors thought they had enough evidence to indict Andreotti.

This time parliament could not protect him and he was brought before the court, along with various neo-fascists and mafiosi. In 1999 the court ruled he was not guilty. In 2002 the court of appeal overturned the verdict and condemned Andreotti to 24 years in jail. He took it philosophically: "To give 24 years to a man who is over 80 is almost like wishing him a long life." Finally, in 2003, the court of cassation (Corte Suprema di Cassazione), the country's court of last resort, overturned the sentence. Once again Andreotti was innocent – at least of this particular crime, thus vindicating those who argued that it was hardly credible that a statesman of Andreotti's standing would risk so much to eliminate a rather pathetic blackmailer.

Until the long and exhausting trial got under way, Andreotti had remained in the international limelight, esteemed and revered. In 1995, invited by Yasser Arafat, he went to Gaza, part of a wider Middle Eastern tour that included Iran, Israel and Syria, and was received with honours normally reserved for a head of state and not to a retired politician facing criminal charges. Gorbachev, after his resignation, sent him an effusive letter, praising him as one of the greatest living international statesmen. Henry Kissinger celebrated Andreotti's "razor-sharp political mind". Few Italian politicians had obtained such international recognition.

Yet these were also the years in which he was being indicted as a mafioso. Those who were incredulous that Andreotti would stoop so low were reminded that his realism might have led him to treat the mafia as he treated anyone who had power – as opponents to be taken seriously, whose interests must be taken on board, and who, if they cannot be eliminated, must be conciliated. He had, after all, consistently exhibited a supreme indifference to the idea of supping with the enemy, and invariably displayed a lack of anger, passion or any desire of revenge.

These traits were well depicted in Il Divo, directed by Paolo Sorrentino, which narrates the events surrounding Andreotti's trials and tribulations of 1991-92. It is said that Andreotti, when watching it, momentarily lost his temper, then admitted that the film was aesthetically remarkable, but that the suggestion that he was somehow responsible for many of the "illustrious corpses" of the First Republic was ludicrous – a fair reaction.

He is survived by Livia and his four children.

• Giulio Andreotti, politician and writer, born 14 January 1919; died 6 May 2013