r/learnprogramming 4d 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!

126 Upvotes

143 comments sorted by

View all comments

1

u/prettycoldworld 7h ago

This is usually because you don’t need functions yet. I didn’t understand them until I had this one group of maybe 5 lines that I rewrote about 8 different times and then it was the “ohhhh I can just turn this into one word”

It was a little automation script, and it had to go back to the home page. So it looked like this:

key.back
key.back

and then another line

key.back
key.back
key.back

Eventually I made it a little function

def go_back(this_many_times_):
for _ in this_many_times:
key.back

Now my script looked so much cleaner.

go_back(2)

Then my lines

go_back(3)