In you code you refer to a “sensor” attached to A0, but you did not explain what you are really have connected there. Of course, you should not apply a voltage greater than the Arduino VCC, so you can't directly attach it to say the 12V output of the power supply. You could monitor the 3.3V or 5V outputs, but even there I would suggest including some series resistance in case something unexpected happens, say like you accidentally set the A0 pin to output mode.
In the code, I suggest defining two variables, one to represent the current power state (on or off) and the other the previous power state (also on or off) - then you can check for a change, which it seems is what you want.
Something like this maybe:
const int analogPin = A0; // pin that the sensor is attached to
const int ledPin = 2; // pin that the LED is attached to
const int ledPin2 = 3; // pin that the LED2 is attached to
const int threshold = 850; // arbitrary threshold level of analog input
bool PowerOn,PreviousPowerOn = false;
void setup()
{
pinMode(ledPin, OUTPUT);
pinMode(ledPin2, OUTPUT);
}
void loop()
{
PowerOn = analogRead(analogPin) > threshold;
if ( !PreviousPowerOn && PowerOn )
{ // power went on, turn on a LED for 3 seconds
digitalWrite(ledPin,HIGH);
delay(3000); // 3 sec DELAY
digitalWrite(ledPin,LOW);
}
if ( PreviousPowerOn && !PowerOn )
{ // power went off, turn on another LED for 3 seconds
digitalWrite(ledPin2,HIGH);
delay(3000); // 3 sec DELAY
digitalWrite(ledPin2,LOW);
}
// power did not change, do nothing.
PreviousPowerOn = PowerOn; // keep power state for next pass
}
If that does not work, try displaying the analogRead value, but given I have not tested it at all, anything is possible!