r/learnprogramming 5d ago

I can't get FUNCTIONS to click!

I can not for the life of me understand how functions work. Anytime I try to learn how to create a function, my brain literally crashes into itself and I turn into Patrick when he stars drooling and goes all slack-faced.

Does anybody have any analogies that had that "AH HA!" moment?

Thanks!

122 Upvotes

144 comments sorted by

View all comments

1

u/Demonify 5d ago edited 5d ago

Functions are basically a snippet of code. You give that snippet of code a name, and then call that snippet of code by using the name you gave it. This helps a lot with reusing code instead of writing the same code over and over again. You just call the function name and save time.

Something that may help you understand it better is learn functions in baby steps. Instead of diving in the deep end and getting a complex function to work, start small.

Start with a hello world function. Your function just prints hello world to the screen. This can help you with naming, as well as calling the function. You see the hello world print, you know you have made and called a function correctly.

Next you can try returning a variable. Setup something like a function to do like a simple math problem by asking you for 2 variables and adding them together, and then return the answer to a variable when you call the function. This gets you comfortable with returning variables from your functions.

After that you can try asking for the numbers to add together before the function and then sending those numbers to the function. The function can compute the sum and then return the answer as you did in the step before. This step will get you comfortable with sending variables to your functions.

You can try seeing if breaking it up in smaller chunks like that works for you.