MOSUL, Iraq — Iraq’s prime minister entered the city of Mosul on Sunday to declare victory in the nine-month battle for control of the Islamic State’s former stronghold.

On a walk through the city’s eastern districts, Haider al-Abadi was thronged by men holding cameraphones as music blared and others danced in the streets.

“The world did not imagine that Iraqis could eliminate Daesh,” he said, using the Arabic acronym for the Islamic State. “This is all a result of the sacrifices of the heroic fighters who impressed the world with their courage.”

But in a sign of how tenaciously the Islamic State has fought, even as Abadi was touring the town the sound of airstrikes echoed through the skies and smoke rose from the last pocket of territory the militants control, thought to be no more than 200 yards long and 50 yards wide.

The confusion of that moment came as a reminder that even though a complete victory now seems assured, it has come at a tremendous price. On a walk through its oldest quarters Sunday, the stench of bodies filled the air. Amid the rubble were the arms of a young child, still wrapped in pale pink sleeves.

As he toured the city, Abadi met commanders in west Mosul who led the battle but did not make a formal speech declaring the city free of militants, though one had been expected.

The battle drawing to a close was the toughest yet in the Islamic State war, one that lasted far longer than anticipated. When the offensive was launched last October, U.S. officials were privately predicting a two-month fight, and expressed hope that mass civilian displacement and widespread destruction could be avoided.

Instead, the fight lasted for nine months, longer than the siege of Stalingrad and longer than the final Allied push into Germany in World War ll. It has cost thousands of lives, uprooted hundreds of thousands of people and shattered vast stretches of the city.

And the declaration of victory does not end the war. The Islamic State cannot now roll back the array of forces ranged against it. It is on a path to defeat in the Syrian city of Raqqa, the original capital of the militants’ so-called state, where an offensive launched by U.S.-backed Kurdish and Arab forces is making progress. But that battle is only just getting started.

Over the past three years since Islamic State leader Abu Bakr al-Baghdadi declared the existence of a “caliphate” in Mosul, his group has been driven out of 60 percent of the territory it once controlled in Iraq and Syria, according to the U.S. military.

But that still leaves it in control of an extensive chunk of land spanning the border of the two countries and several other pockets, including key towns such as Hawija, Tal Afar and Qaim in Iraq and most of the entire province of Deir al-Zour in Syria.

As the battle for Mosul has demonstrated, the Islamic State is prepared to fight for every inch it holds, even as the neighborhoods its cadres lived in are destroyed around them.