Transient flow in pipe is a much debated topic in the field of hydrodynamics. The water hammer effect caused by instantaneous valve closing is an important branch of transient flow. At present, the fluid density is regarded as a constant in the study of the water hammer effect in pipe. When there is gas in the pipe, the variation range of density is large, and the pressure-wave velocity should also change continuously along the pipe. This study considers the interaction between pipeline fluid motion and water hammer wave propagation based on the essence of water hammer, with the pressure, velocity, density and overflow area set as variables. A new set of water hammer calculation equations was deduced and solved numerically. The effects of different valve closing time, flow rate and gas content on pressure distribution and the water hammer effect were studied. It was found that with the increase in valve closing time, the maximum fluctuating pressure at the pipe end decreased, and the time of peak value also lagged behind. When the valve closing time increased from 5 s to 25 s, the difference in water hammer pressure was 0.72 MPa, and the difference in velocity fluctuation amplitude was 0.076 m/s. The findings confirm: the greater the flow, the greater the pressure change at the pipe end; the faster the speed change, the more obvious the water hammer effect. High-volume flows were greatly disturbed by instantaneous obstacles such as valve closing. With the increase of time, the pressure fluctuation gradually attenuated along the pipe length. The place with the greatest water hammer effect was near the valve. Under the coupling effect of time and tube length, the shorter the time and the shorter the tube length, the more obvious the pressure fluctuation. Findings also confirm: the larger the gas content, the smaller the fluctuation peak of pipe end pressure; the longer the water hammer cycle, the smaller the pressure-wave velocity. The actual pressure fluctuation value was obviously lower than that without gas, and the size of the pressure wave mainly depended on the gas content. When the gas content increased from 1% to 9%, the difference of water hammer pressure was 0.41 MPa.