I would like to know between the microcontrollers PIC and AVR which is the best?
There are advantages and disadvantages to each, which have already been thoroughly discussed on the Internet. As far as the Arduino world goes, AVR is better because it has much better support. You can add support for some PIC microcontrollers but you won't find as many Arduino libraries that that work with PIC, you won't find as many Arduino tutorials for PIC, and you won't find as many people here on the forum who can help you with using your PIC.
Aamiral:
ie how do I know that I need 40 pins instead of 28?)
If your project requires more I/O pins than the 28 pin chip can provide, then consider using the 40 pin chip. In the AVR world, 28 pin chip usually means the ATmega328P and 40 pin usually means the ATmega1284P. In addition to more I/O pins, the ATmega1284P also has more memory. So you might consider using the ATmega1284P for a project that requires more memory even if it doesn't need the extra I/O.
Aamiral:
Can you advise me a programmer for AVR and PIC microcontrollers (especially those who have pins on 4 sides).
You can use an extra Arduino board as an "Arduino as ISP" programmer for the AVR. If you want to buy a dedicated ISP programmer for AVR, I recommend the 6 pin USBasp: https://www.ebay.com/itm/271489740923
The microcontroller's IC package makes absolutely no difference to your choice of a programmer.
As for a programmer for PIC, I have no clue. Do you see how that goes?
Can you advise me a programmer for AVR and PIC microcontrollers (especially those who have pins on 4 sides).
Back when chips were in those (big) Dual-Inline-Packages, it was pretty common to drop the chip into a programmer/test socket to load the code, and then insert it into a socket on your project or product. That was because programming the chips in those days required access to lots of pins ("parallel programming") and high voltages, and the big sturdy chips were easy to move around and socket.
More modern chips typically have some sort of "in-circuit serial programming", which uses far fewer pins, so as SpyCatcher says, they're usually programmed after they have been soldered into the project.
It small volumes, this is usually done by manually connecting a cable.
In larger volumes, you usually put together some "test fixture" that will automatically make contact with the needed pins.
For very high production volumes, the manufacturer or distributor can pre-program chips for you, for a small fee.
As for picking a microcontroller, I once wrote an Instructable that some people have found useful.
I consider it moderately obsolete at this point (it's from 2007, near the infancy of Arduino, for example, and well before Raspberry Pi), but some of the concepts should still be valid...