You cannot use lenses meant for Canon, Pentax, Sony Alpha, Olympus/Panasonic 4/3.
You can use lenses meant for Nikon F mount, including those made by Tamron, Tokina, Sigma, Carl Zeiss, Vivitar, Angenieux etc..
The camera will not be able to focus automatically if there is no motor in the lens. Lenses with motors in them are those designated AF-S or AF-I.
The camera will not be able to meter if the lens does not have a CPU, eg manual lenses like AiS, Carl Zeiss ZF.
Virtually any lens u can mount on nikon cameras u can mount on D40. Its just a matter of whether you can have metering and autofocus or not.
I'm using a manual focus 50mm f1.4 and a 100-300mm Cosina lens bought from cash converter due to budget issues... works pretty well just that you cant have autofocus and metering sometimes when you needed it....