O2 Sensor Error Code vs Loose Gas Cap

I had a similar problem with my 02 Impala and always thought I was just consistently putting the gas cap on wrong…when I brought to my mechanic they replaced one of the O2 sensors and the check engine light has not come on since.