reading a sensor and using an if statement

What you need to understand is the concept of the "Finite State Machine". Everything you have described can be directly described by a distinct state of an FSM.

For more information: http://hacking.majenko.co.uk/finite-state-machine