It's a bit complicated financially and the details vary based on fixed vs variable terms but I'll try to offer a simplified example of why pre-payment penalties exist.
Imagine I go to a bank today and take out a $100,000 mortgage on my house at a fixed rate of 2% (yeah - that's 2020) on a 5-year term[0] with a 25-year amortization.
The bank gives me that $100,000 cash today on the expectation that they will get it back with 5 years of interest (calculation is a bit complex but should work out to just over $9k over the 5 years).
We could keep it simple and say that once you've agreed to pay a bank $9k in profit, they are in the business of making sure they get that profit. Repaying any amount of the debt ahead of schedule does not exempt you from paying that anticipated profit.
In the banks' defence, the details are a little more complicated in practice. Banks rarely lend out their own money. When I take out this mortgage, the bank just issues a $100,000 bond to an investor. The bank presumably guarantees the bond so the risk to the investor is less than the mortgage itself and, so, the bond has a lower interest rate - say 0.5%. The difference in interest rates is the actual profit to the bank.
Bonds have a couple characteristics:
a) they are fixed-term (in this case, 5 years); and
b) payout of both interest and principal is guaranteed (by the bank)
So if you decide to pay back your mortgage (or some amount) ahead of schedule, the bank still has to pay out their bond commitments and that money needs to come from somewhere. And the bank isn't gonna front it. Depending on markets and current interest rates, the bank may be able to re-use that bond on someone else's mortgage so your penalty may be reduced in some cases.
[0] These shorter-than-amortization terms are a thing here in Canada. Not sure if it works the same in other countries.