It is important to pick proper letter writers; people who know you well enough to write a meaningful letter and who feel comfortable saying only good things about you. I highly recommend that you start interacting with professors as early in your careers as possible to have solid options for letter-writers when the time comes.
Should you ask me for a letter? It depends on how much we have interacted and on what basis. In general, if you have taken only a single course from me and have not interacted with me in any other context, I will say “no.” Unless there was a remarkable amount of interaction in that course, it would be difficult for me to write a strong letter. If you are unsure, then ask me if I feel comfortable writing you a strong letter, and I will tell you.
If I am going to write you a letter, I want a lot of information from you to help me write the strongest letter I can. Specifically:
I would like at least three weeks warning, but I understand that sometimes you find out about an opportunity at the last moment. Be clear about the earliest due dates for the letter and send me a reminder a few days before it is due.
Send me your application materials. Include any essays you have written as part of your application, such as a personal statement or research plan.
Remind me of the major types of interactions we have had, including what courses you have taken from me, what projects you have worked on for me, what events you may have helped organize with me, or anything else that you think is relevant. You would be amazed how easy it is to forget one of those. When possible, please also remind me of dates (even just the year) so that I can be as specific as possible in my letter, which is always stronger.
Give me a list of at least three points that you would like me to include in the letter. Please do not be modest; I want to know what you feel is most important for me to describe. Some important points to illustrate include your: knowledge, creativity, critical thinking, rigor, technical skills, leadership, teamwork, written and verbal communication, initiative, enthusiasm, reliability, maturity, and your basic social skills. I would like you to remind me of incidents where you have demonstrated some of these traits. These are also all points that you should try to emphasize about yourself in any personal essay.
Tell me why you want whatever it is to which you are applying. If it is an application to a Ph.D. program, what do you plan to do with the degree? If it is for a fellowship, how will this additional money enhance your options? This information will help me know how to best position your letter. While your target audience might have specific expectations of your goals, I do not, so be honest. If you are not sure of what you want to do with your Ph.D., I will not say that in the letter, but knowing this fact will help me give you better advice.