Density functional theory (DFT) calculations were carried out to analyze the electronic and structural properties of pristine and aluminum or phosphorus doped (8,0) single walled carbon nanotube (SWCNT) as a sensor for the detection of nitrogen dioxide (NO2) and ammonia (NH3). The binding energies, equilibrium gas-nanotube distances, the amounts of charge transfer and molecular orbital schemes as well as the density of states have been calculated and used to interpret the mechanism of gas adsorption on the surface of nanotubes. In agreement with the experimental data, our results show considerable binding energy and energy gap alteration due to the adsorption of NO2 on pristine SWCNT. The results reveal that the doping of both Al and P atoms increase the capability of the nanotube for the adsorption of NO2, and the effect is more significant for the Al-doped nanotube. The Al-doped nanotube can also be considered as a good sensor for NH3 due to its high binding energy, considerable amount of charge transfer and energy band gap alteration.