PID - Proportional Integral Derivative control
Think of it like a thermostat - yours may be at say 80 degrees, and you want it a little colder. You select the option 75 degrees. Your home’s heating system will now attempt to change the temperature to that, but in a way that won’t destroy itself. Then, if someone say opened a window and let in a lot of hot air, the system will try to re-adjust the internal temperature back to 75 degrees.
There’s plenty of threads on this forum that explain how it works/how to do it.
Mechanical stops are still easier, but if you insist on solving it with code I’m sure there’s a way to keep track of encoder counts on motors that will allow you to stop the motor from turning after it reaches a certain amount of counts, but this would require you to start your code with a robot fully reset every time