I am going to ask the obvious question here... have you been to a shop and tried them yourself?
That said, probably one of the most common responses you'll get is that you're not buying a camera but buying into a
system. This is absolutely true. You buy into a proprietary lens mouns as well as a whole range of flashes and other accessories. But of course it certainly seems like you're buying a camera when you're handing over several hundred dollars for one, so you want a camera body that you're happy with.
Nikon and Pentax are different systems although they are also quite similar in that both use exactly the same sensors. As you say, there are many lenses available for Nikon. There are also many lenses for Pentax but they are not produced or distributed in such great quantities, so for example you would often be able to buy a certain Nikon lens straight away but it might take a couple of weeks to get hold of a Pentax equivalent.
Something else to consider: Nikon's lenses may be more widely available, but on the D40 your choice will be somewhat limited because older manual focus lenses will not work at all, and many autofocus lenses will not autofocus because the D40 has no AF motor. The Pentax will work with any Pentax K-mount lens going back several decades. So actually in the case of the D40 I don't think either company really has the advantage as far as available lenses go. As 'RMThompson' says the D50 is compatible with more Nikon lenses than the D40 so I would definitely consider that too.
Nikon does have high-end 'pro' bodies while Pentax does not; they are instead hoping that professionals will be attracted by their forthcoming digital medium format system. Pentax do currently offer a more advanced model in the K10d which competes very well with the D80. One argument is that Nikon has more users so it's easier to get help or advice... but as you see, we have this thing called the 'internet'; you could probably find a forum for people who stick peanut butter in their ears, so it's really not that hard to find other Pentax users or reviews.
The Pentax dSLRs do have Image Stabilisation, however Nikon offer Vibration Reduction lenses. The VR lenses are more effective, but obviously they cost more and only work on individual lenses whereas an in-camera system works with any lens; therefore which system is 'better' is a matter of preference and priorities.
Both cameras use the exact same sensor, and the image processing on both is good; by now both companies seem to have got the most out of the sensor and they should perform well even at higher sensitivity (ISO).
Basically I think you would be happy with either; either camera, and either system... so either go to a store and try each camera (and perhaps also the D80/D200/K10D) and as many lenses as you can find before they kick you out, and get a 'feel' for each system... or toss a coin
