God instituted purgatory because he is infinitely merciful and loving. He wants everyone to be saved and to be with him in heaven. Therefore, we end up in purgatory if our soul still carries sins, or remnants of sins, at the time of our death.
In purgatory we are purified and prepared for heaven, because we experience burning shame and remorse for our sins. Purgatory is temporary. People who suffer here on earth due to war, pain, torture, or persecution are already being purified for heaven (Mt. 5:4-10). Our time in purgatory can also be reduced through prayer, the offering of Holy Mass, and by other means.