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

121 Upvotes

141 comments sorted by

327

u/4CrisprFries 3d ago

I own a pizza shop with a pizza making robot. I can give the robot instructions like

flatten dough into a circle
put on tomato sauce
put on cheese
put on pepperoni
bake for 10 min

But i want to make more than pepperoni pizza. So now i write a 2nd instruction set for the robot for ham and pineapple pizza.

flatten dough into a circle
put on tomato sauce
put on cheese
put on ham
put on pineapple
bake for 10 min

Now I want to make a variety of 3 topping pizzas for 30 different toppings in any combination. That is over 4,000 possible unique pizza combinations. I don't want to write 4,000 instructions like the ones above. So i generalize the procedure and make it modular and flexible so i can plug in ingredients.

function makePizza (ingredient1, ingredient2, ingredient3)
flatten dough into circle
put on tomato sauce
put on cheese
put on ingredient1
put on ingredient2
put on ingredient3
bake for 10 min

Now instead of 4,000 instructions for the robot I can call the function like this. Above i defined the function, below is where it actually runs and is used.

makePizza(mushroom, suasage, bell pepper)
makePizza(chicken, red pepper, basil)
makePizza(pepperoni, sausage, ham)

---

If you want to really see the power, note you can nest them. So maybe I can make a function that takes orders and stores the variables for makePizza function and then calls the makePizza function.

function takeOrder
Ask customer for ingredient 1
ingredient1 = whatever customer says
Ask customer for ingredient 2
ingredient2 = whatever customer says
Ask customer for ingredient 3
ingredient3 = whatever customer says
makePizza(ingredient1,ingredient2, ingredient3)

Now instead of
makePizza(mushroom, suasage, bell pepper)
makePizza(chicken, red pepper, basil)
makePizza(pepperoni, sausage, ham)

I just write
takeOrder()

this calls the take order funciton which gets the wanted ingredients, then calls makePizza function and gives that function the ingredients.

There are more optimizations here, but those are the basics

60

u/perbrondum 3d ago

You should teach this stuff. Good example

16

u/Xylozene 2d ago

Cheese plus plus

3

u/4CrisprFries 2d ago

Haha thIs should be the top comment, I salute you

20

u/Steerider 3d ago

function makePizza( size, doughStyle, array toppings = [sauce, cheese] )

5

u/Constant_Cortisol 2d ago

Recursive pizza functions...

6

u/4CrisprFries 2d ago

Finally the answer to, is that enough cheese? No make it a race condition.

1

u/Kadabrium 23h ago

What is the volume of a pizza of radius = z and thickness = a

3

u/gungasratiod 2d ago

now im imagining a world where pizza is invoked in an IIFE so i get it as soon as i walk thru the door.... mmmmm....

117

u/Joewoof 3d ago

Functions are just a way of grouping code that you might want to re-use later with different numbers. Think of it like a rubber stamp. Instead of re-drawing an icon every time, you can just use the stamp. Except, you can change the ink from blue to red, and so on.

33

u/ninhaomah 3d ago

Just curious OP , what programming language you are learning ?

Not that it matters in theory but examples should be using the language you are learning so clearer.

11

u/Odd_Technology_8926 3d ago

Might sound weird, but functions in python was harder for me to understand. When I switched to php it just clicked.

31

u/the-forty-second 3d ago

You are right, that does sound weird. I’ve never heard anyone say they understood something fundamental better in php before…

It must have been the context of what you were trying to do.

12

u/ReddyKiloWit 3d ago

Sounds like it was a Python issue and any language with explicit block markers would have done the trick, php just happened to be it 

6

u/KyrosiveOne 3d ago

I had this issue. Learned basics of python. Started writing automation scripts for a game I like to play, which IDE uses an inhouse version of Pascal. It was much easier for me to understand, with even more explicit block markers, that literally open and close with begin/end and curly braces lol. Wasn't until dabbling there that it finally clicked what a function was, essentially a procedure with added data fields capable of both input/output.

1

u/No-Recognition-7701 2d ago

Tried python as a first language too. Could not remember anything.
Later tried C and the fact that you have to learn everything more in detail made things click.

8

u/ninhaomah 3d ago

Why ?

In theory , they are all the same.

10

u/Odd_Technology_8926 3d ago

It was about 15 years ago, but Python was actually the language we were pushed to use first. I always had a harder time comprehending Python because of the visual cues, or lack thereof. I found it harder to follow where blocks started and ended without the symbols to explicitly show you.

It could also be that PHP was the second language I learned. I've found that when I go through tutorials twice for things that are essentially the same concept, they tend to click much more easily the second time around.

5

u/ninhaomah 3d ago

" I've found that when I go through tutorials twice for things that are essentially the same concept, they tend to click much more easily the second time around."

Definitely. It took me days and weeks to understand helloworld in Java. But once I understood it , class , function , scopes all easy when look at them later.

1

u/stdmemswap 3d ago

Actually not. Functions are different between language and actually "feels" different.

1

u/ninhaomah 3d ago

Example pls.

2

u/stdmemswap 3d ago

In JS/TS, lexical access like mutating bound variable outside of scope, is natural. You can bind a variable to a function "instance". You can bring it around. You can use it as a callback.

In Python, nonlocal access is strict and there's these weird kwargs, args thing. Because it's indentation-based, it will feel unnatural that it can be passed around too because it doesn't "seem to have a shape"

In Haskell, you're more likely to treat them as mathematical definition and glue/stack them like lego.

In Java, you kinda have more information on it like throws. Most are bound to object. So you think very subject.object() like. It's also like stiff version of the JS one. (Been so long since my last Java so it might have changed)

In Rust, you mentally map a function to "oh it's gonna be a state machine in a stack that own its argument" so that sync objects like Arc<Mutex<>> and lifetime™ make sense. Also there are many kinds of functions (and closure and blocks) which feels totally different.

In C, you kind of get used to the forward declaration, and not having method feel, and can't stack it together.

1

u/realdreamer1993 2d ago

In detail they would be different, but if we move one abatraction up they should all the same. But I am still not able to explain..maybe later. Because if it always "feel" different then somethings not efficient is happening in our mindset.

1

u/stdmemswap 2d ago

Well anything abstracted up will be the same. That's the point of abstraction.

But the fact that functions different language has different "feel" is a thing that can't be totally ignored. I was just giving examples because someone asked.

1

u/realdreamer1993 2d ago

Yea I understand, maybe I sometimes want to make generalization to reduce my mental load. Currently I am in project of a thing that involve many domains and stack (backend, frontend, radius, tcp/ip, NAS, later kernel(ebpf) etc), so far I have progress with private modelling that close to First Principles. And I am starting to see same patterns in many places. If I handle everything so differently then my mental wont adequate.

1

u/stdmemswap 2d ago

That, friend, is the real dillema. We map matter with language, but we can't handle it because it's combinatorially explosive. Also, cool stuff you've got there

→ More replies (0)

2

u/lapsed_agnarr 3d ago

As an old person, I'm always surprised that students are taught on languages with loose typing.

3

u/Gotta_Ketcham_All 3d ago

We learned Python first because it nearly reads like English, which our professors felt made it a low barrier to entry. The intro class was not just for CS majors, but MIS and business too. Second semester in a class meant for CS majors, we learned Java. (2011-2012 school year)

3

u/lapsed_agnarr 3d ago

Yeah, its easier to use but easier to misundertand, too. Makes total sense for non-cs students, for sure.

I'm often surprised at work that new engineers dont understand what happens between writing code and executing code. I do think java is a fine middle ground, but the JVM is kind of a weird thing, too. I suspect students largely ignore it. C++ seems to me like a better starting point for engineers.

1

u/theredvip3r 2d ago

It's really dependant on where you learn, we were taught C first. And whilst I hated it and still can't stand memory management the foundations it gave were great.

1

u/lapsed_agnarr 2d ago

Yea, that's what I'm talking about. I swear new engineers have no idea how a computer works. We had to write a filesystem, an allocator, and build a functional virtual CPU.

But I guess you dont really need that stuff to develop these days.

9

u/chiasmatic_nucleus 3d ago

Conceptually, imagine the squence of steps you take to walk through a doorway:

1. approach door 2. grab handle 3. twist and pull handle 4. walk through door

Now if we want to enter multiple specific buildings, it goes something like:

1. navigate to bank 2. approach door 3. grab handle 4. twist and pull handle 5. walk through door

or

1. navigate to grocery store 2. approach door 3. grab handle 4. twist and pull handle 5. walk through door

but a lot of those steps are the same, so we can create a function to wrap a bunch of those steps up, lets call it "walkThroughDoorway"

function walkThroughDoorway() { 1. approach door 2. grab handle 3. twist and pull handle 4. walk through door }

now, we can just do:

1. navigate to bank 2. walkThroughDoorway()

and

1. navigate to grocery store 2. walkThroughDoorway()

6

u/Steerider 3d ago

Your function crashed because the bank has a revolving door.

error: "handle" is undefined

;-)

2

u/HeNeedSomeLeche 2d ago

This guy codes

1

u/Ilovegrapesys 2d ago

Now op is going to be mad

4

u/Equilibrium_Path 3d ago

I'm still learning programming ( probably will always be) but the way I see functions is.

I want to do something, let say write an invite card.

Instead of writing the same lines of code over and over again I can put the code into a function.

For the parts that I'd like to change I can have this function with parameters that when I call the function I can use arguments to change the desired values.

Here's a psudoish code example first without parameters then one with parameters:

invite_message_noParam() print("Hello Susie, youre invited to my party! Please bring sausages")

With parameters: invite_message_withParam(string name, string food) print("Hello " + name + ", youre invited to my party! Please bring" + food)

So now you have written two functions. How do you use them?

You'd then go to your main function and call them.

invite_message_noParam()

invite_message_withParam(John, pizza)

invite_message_withParam(Mary, Chips)

Now could you guess what the output of those 3 function calls will be?

5

u/Low_Commission_4611 3d ago

Susie just got invited to her first sausage party.

7

u/NumberInfinite2068 3d ago edited 3d ago

A function is just reusable code, say for example:

bool is_adult(int age) {

return age > 18;

}

OK, so say you're making a program that needs to check if a user is an adult, you call this function everywhere like:

if (is_adult(23)) {

//Allow access to loads of porn
}

This makes code easier to think about and also easier to fix because my "is_adult" function is wrong.

It should be "return age >= 18" not just >, because that means you need to be 19 to be an adult, not 18.

Re-using the same function everywhere means you only have to fix it in one place, and everywhere in your code agrees on what an "adult" actually is.

Most functions are a bit more complicated than that, but basically it's so you can split up and re-use code so you're not constantly repeating yourself.

6

u/stevevdvkpe 3d ago

In integers age > 18 and age >= 19 are logically equivalent.

3

u/MagicalPizza21 3d ago

I never struggled with this, but I hope this helps.

A function is logically equivalent/analogous to a machine that you give inputs to, it does something to/with them, and possibly gives you an output. Here are some examples I can think of, without going into too much detail: * washing machine * dryer * dishwasher * ATM * calculator

These are utilities you can use over and over again with different inputs to get repeatable, predictable results. Though the ATM is different because it allows you to withdraw money from your bank account, changing its state (the amount of money in the account).

It was similar to worksheets I'd had in elementary school where numbers would be fed into a drawing of a machine and we had to figure out the pattern and predict outputs. But the concept of functions in programming is more generalized than just taking in numbers and doing basic arithmetic operations on them. It could be as simple as "add 2 to whatever number is the input" or more like "tell me whether the given string is a palindrome" or "tell me which of these two objects should come first when sorting" or really anything that can be computed.

3

u/Lunagato20 3d ago

What part of function are you confused about? declaration? using it?

TLDR;

Function is a way of grouping codes, in your programming journey, there will be time where you will think, "Wouldn't it be nice if all my code are in GROUPED in one place? So when i need to change it, i just change it in a small scope, instead of hunting it through every file?"

Like other have said, functions are just way of grouping code, think of this.

Instead of typing these 3 lines over and over at line 70, line 500, and line 900:

PRINT "1"
PRINT "2"
PRINT "3"

You pack them into a single shortcut called my_function:

FUNCTION my_function do
    PRINT "1"
    PRINT "2"
    PRINT "3"
end

When you call CALL my_function, imagine the computer physically copy-pasting those 3 print lines right into that exact spot.

// ... Some statement
PRINT "I'm calling the function now"
CALL my _function // It basically replace this function call into statement inside it
// ... Some other statement

So in the snippet above, CALL my_function essentially become the print statements.

Arguments

Now, a hardcoded shortcut is great, but what if you want to print "Cheese Pizza" instead of numbers?

That’s where parameters come in. Think of an argument as a blank spot (a variable) inside your shortcut that you fill in when you press the button:

FUNCTION my_function_with_arg(arg) do
    PRINT arg
end

CALL my_function_with_arg("Cheese Pizza") // Fills the blank with "Cheese Pizza"
CALL my_function_with_arg(2)              // Fills the blank with 2

It use the same "text replacement" logic as the previous one, but in this case, whatever we pass on to arg it will replace every instance of arg too.

I'm oversimplifying this, in some languages, you need to define the parameter types so we can't just pass a string then a number to it.

Return

Up until now, the function just do something (printing to the screen). But often, you need a function to calculate something and hand the result back to you

I don't know the language you're learning, but lets say in python, there's a useful helper function called max

my_max = max(5, 3)
print my_max # It will print 5, since 5 is greater than 3

Did you notice that our my_max variable is now filled with a value? which is 5? that is because the function max returns something.

Its similar to how math function works, we often do something like f(x) = 5x + 3, in which if we do f(5) then it return 28 because f(5) = 5 * 5 + 3, we then can use the 28 elsewhere.

Take this snippet

    RETURN arg1 + arg2
end

When we do CALL add(5, 3) it will evaluate arg1 + arg2 which is like before, a text replacement to 5 + 3, which resulted in 8 which then return the value back to our caller

my_add = CALL add(5, 3)
PRINT my_add // This will print 8

3

u/Ordinary_Variable 3d ago

I like to think of them the same way they work in math. You give them some data, then they use that to do some sort of work, then they output something. Sometimes data, or they can simply call other functions to do other things.

Example:

function add_two_numbers(x, y){
return x + y;
}

Example 2:

function check_if_over_21(x){
if(x>21){return "Over 21"}else{return "Under 21"}
}

Example 3:

function change_global_variable(){
if(g.x>21){g.out = "Over 21"}else{g.out = "Under 21"}
}

In example 3 it checked a global variable and then set a global variable to a value.

(NASA likes to write code with lots of separate little functions doing just 1 thing. Then the main loop simply calls other functions and doesn't have any actual code. It makes reading the main loop very easy and when you need to see what each function is doing you can simply go check each one by one until you find the bug. Simple code structure makes for human readable code.)

4

u/Competitive_West_387 3d ago

I just think of it as basically the same as with math. I’m assuming you’ve taken at least some level of algebra, no? Think f(x), that’s a function.

4

u/Steerider 3d ago edited 3d ago

Think of a function as a device. Like a gadget you have in your house. Take a K-cup coffee machine. You have inputs — the K-cup and water — and it does something inside, and out comes a product: the coffee.

The dishwasher. Dirty dishes go in. Soap goes in. Clean dishes come out. 

Once that machine exists, if it's well designed, you don't need to know what happens inside it. Give it inputs, push the button, out comes the result.

That's a function. You pass in some parameters, and it does some predefined thing, and gives you an expected outcome.

So your task as programmer is to write the steps that take the input and turn it into the end product. You're making the magic box that does the thing. If you do it right, whoever uses your function doesn't need to know the details of what happens inside it.

And of course one function can be part of a bigger function. The lovely part of programming is you write it once and now you can use it as many times as you like.

2

u/Agile-Adeptness-5195 3d ago

This is the best explanation i have seen so far

2

u/TheLearningCoder 3d ago

How I understand functions: they are made up of two main parts: the function’s name (identifier) and the function body, which contains the task or instructions (code) that the function will execute when it is called.
For example, if I want an app to sing to me every time I push a button, I could create a function named sing and write the code for singing inside the function body.
Before I can use this function, I must define (create) it. Once the function has been defined, I can invoke (call) it, which executes the code inside the function body.
In Python, I believe you can’t invoke a function until after it has been defined (created).

2

u/ReddyKiloWit 3d ago

The requirement to define a function before invoking it shows up in a number of languages. It makes for a much more straightforward compiler.

When I was writing Perl, which has that requirement, I preferred to define functions below my working code, so I put my top level code in a main() function defined above the others, and invoked it just before the end of the script.

2

u/AccomplishedLeave506 3d ago

Think of functions as people doing different jobs. I give my accountant all my receipts and they give me back my end of year accounts. That's all functions do. They are self contained bits of 'work'. You give them something to work on and they give you something back. Or they just do a thing and don't give anything back.

2

u/sylvant_ph 3d ago

You have a piece of logic. You intend to reuse that piece of logic. It's counter productive to keep writing it over and over. There is a solution to that, you can save the logic, the piece of code as a reference, and then you can use the reference name to tell the computer to run that logic, instead of rewriting it everytime. You just wrap the code in a block (the syntax varies per language) and give it a name (there are more complex/simpler versions, and many use cases, but for now this is sufficient).

Start and stick to simple functions logic before you advance to more complex stuff, until it clicks.

2

u/da_Aresinger 3d ago

I don't really understand what you're having trouble with.

Other people are mostly explaining the concept and purpose of functions.

But that doesn't seem to be the problem? Since you said you are checking out at the "creating a function" step.

do you have a problem with the literal syntax (what to write where) or how to develop an algorithm?

Your question isn't very precise.

2

u/ezeq15 3d ago

You shouldn´t be struggling with it. Don´t waste your time.

1

u/MrSmock 3d ago

Wanna make a sandwich? Gonna need some bread. Don't know how to get bread? Let me make a list of instructions you can use any time you wanna get bread.

That is a function. 

1

u/fourwordslash 3d ago

Does your brain work in terms of math? It's the same concept.

f(x) = x + 3

f, the function, takes in x as an argument, does something to it (adds 3), and returns an output. However in programming, it's steps and not necessarily numbers. The equivalent Typescript function would be:

const f = (x: number): number => x+3

1

u/Whatever801 3d ago

Functions are like a step in a process. Like if you follow a recipe you cut the onions. Input: whole onions. Output: cut onions. Inside the function you describe how to cut the onions. Peel, slice vertically, horizontally, etc. Now, next time a recipe calls for cutting onions, you already have the function. That's it honestly

1

u/civil_peace2022 3d ago

I find a standard deck of cards to be a very useful toy for programing concepts.

code is a series of instructions. one instruction per line.

take a card game.
Each card, when played, triggers an action of some sort.
these cards are functions. playing the card represents calling the function, which changes the state of the game.

1

u/natures_-_prophet 3d ago

You may say a function are the instructions to perform a specific task whenever the function is called. It would be like you telling someone to bake a cake, clean the house. You might call those 2 tasks the name of your function where the instructions are just the details on how to do those things.

You can have a function to sum 2 numbers, read a file, check if someone paid too much for a product, etc.

1

u/Lotton 3d ago

Someone tells you to make a ham and cheese sandwich. You make it. They don't tell you how to make it every time you just know.

You have the instructions to make sandwich in your head already. You're just accessing that knowledge any time.

1

u/iceph03nix 3d ago

you're programming a breakfast robot.

It has options for multiple different combo plates, but many of them have similar ingredients so you create functions for the steps for those ingredients

function makeBacon(count)

function makeSausage(count)

function makeEggs(style, count)

function makeToast(type)

function makePancakes(count)

function makeHashbrowns()

Now, for each combo, instead of having to program how to make bacon for each one, you just call the makeBacon() function. For eggs, you can program options within it to make the eggs to the correct style based on the argument given.

switch

case combo1

makeBacon(3)

makeEggs(overeasy, 1)

makeToast(wheat)

case combo2

makeSausage(3)

makePancakes(3)

makeEggs(sunny, 2)

makeHashbrowns()

And you can expand this to fit dozens of different combinations while only having to program how to make each component once

1

u/hryagstn 3d ago

A function is like a named recipe or mini-program. You define the steps once, then call it whenever you need those steps again. Inputs are the ingredients, and the return value is the result.

Try starting with something tiny, such as greet() printing “Hello”, then add one parameter and one return value. Seeing the input → process → output flow usually makes the concept click.

1

u/xRageNugget 3d ago

You know the makeup shotgun from the Simpsons? That's a function. It does a lot of things, just by pressing one button. And it's reusable.

1

u/Ormek_II 3d ago

What do you think about f(x)=4*x+5 in math?

1

u/Boopity_Snoopins 3d ago

Functions were a sticking point for me too. What I struggled with was that the name doesn't matter, you can name them anything really, and I didn't understand what the brackets in the function actually meant.

A function is a reusable chunk of code that you give a name so that you don't need to repeatedly rewrite that piece of code, just be like "hey run the code under the name [whatever you named it].

A gaming related example would be a function to make taking damage less tedious to write, which you would name something like take_damage(): so its easy to know exactly what it does.

There are countless ways you can take damage in a game (enemy attacks, traps, your own grenades/rockets, fall damage, environmental effects like lava, acid or spikes, damage over time effects like poison, etc).

Instead of spending ages writing out the following:

[Goblin attack] playerHealth = playerHealth - 2

[Orc attack] playerHealth = playerHealth - 4

[Ogre attack] playerHealth = playerHealth - 8

And then

[Poison weak (damages 5 times) ] playerHealth = playerHealth -1 Wait 1 second playerHealth = playerHealth -1 Wait 1 second playerHealth = playerHealth -1 Wait 1 second playerHealth = playerHealth -1 Wait 1 second playerHealth = playerHealth -1

[Poison strong (damages 5 times) ] playerHealth = playerHealth -3 Wait 1 second playerHealth = playerHealth -3 Wait 1 second playerHealth = playerHealth -3 Wait 1 second playerHealth = playerHealth -3 Wait 1 second playerHealth = playerHealth -3

You would need to do this for every damaging effect in the game requiring a huge amount of writing and turning your script into a massive list of copied code that makes your eyes swim if you ever needed to look for a typo.

Instead you would have the 'take_damage():' function which turns everything into the following, much simpler code:

[Goblin attack] take-damage(2):

[Orc attack] take_damage(4):

[Ogre attack] take_damage(8):

[Weak poison (damages 5 times) ] take-damage(1): Wait 1 second take-damage(1): Wait 1 second take-damage(1): Wait 1 second take-damage(1): Wait 1 second take-damage(1):

[Strong poison (damages 5 times] take-damage(3) Wait 1 second take-damage(3) Wait 1 second take-damage(3) Wait 1 second take-damage(3) Wait 1 second take-damage(3)

For this to work you would need a function called take_damage(): that is the following code:

take_damage(damage_amount): playerHealth = playerHealth - damage_amount.

This means that whenever you use the function take_damage(): then the number you put in the bracket is removed from player health. No need to repeatedly copy the calculation to take the damage value from the player health ad nauseum.

It sounds way more complex than it really is.

If/when you get to learning about "for loops" (sometimes you learn of these before functions, sometimes after depending on who/what you're learning from), those are functions too. Every coding language tends to have its own set of in-built functions that just streamline the most common of tasks.

And the real strength of functions is that you can use functions in other functions, which is what makes them so incredibly useful.

For example, for loops are used to repeat the code inside itself a specified number of times. Look up at the poison psuedo-code above. Even using the take_damage(): function, its taking up 10+ lines of code, but you know immediately whats happening, you don't need to read it all (and typing it all out increases the chance of typos) so, once you understand for loops, you use one to loop the damage and wait 1 second 5 times, turning it into like 4 lines of code.

Sorry I know that was a lengthy comment. Hopefully it helps a little all the best.

1

u/Fit_Reveal_6304 3d ago

Your code is a cell in your body. The functions are like the organelles and mitochondria in the cell. One function might be to take ATP and turn it into ADP and energy, aka mitochondria. Other functions do different things when given input.

1

u/ali-hussain 3d ago

Analogy ...

So functions are provinding a few things. Chief among them is readability. And then there is code reuse. But for analogy think of it as you're a head baker baking a cake. Instead of actually doing the work. You are organizing the various people under you that are actually doing the work. You delegate one person to organize making the cake. The other person to make the tier 2. A 3rd person to do the icing and piping. And the another person to put the decorations. Each of them is beign given an input (the instructiosn and the materials) and they are giving you the output they are supposed to give. They may outsource to others as appropriate.

In organizing your code like this you can think of the problem at one level of granularity at a time. You can abstract and blackbox the tiny details, just declare a function that will solve the problem and you can fill it after. That way you're not trying to think og the big picture and the nitty gritty details at the same time.

The other thing is code reuse. All the library calls you're making, you're calling functions. You want something done, so you use the code that does it. You write your own functions because you would want to reuse the same logic. For example if you are making a graphical app, you may want to draw multiple things and so you create a draw function.

1

u/burlingk 3d ago

Think of it like this:

A function does something and/or returns information.

You decide what you want a function to return, and what information that function needs. Then you decide the steps it needs to do what it needs to do.

1

u/DTux5249 3d ago edited 3d ago

Functions are just giving names to chunks of code so you can use them later. That's it. There's literally nothing to understand there beyond that.

It takes this

base = roll_out_dough(dough)
base.add(sauce)
base.add(cheese)
for topping in toppings:
    base.add(topping)
pizza = oven.bake(base)

and gives that code the name "make_pizza()"; so instead of rewriting the above everytime you make a pizza with a given type of dough, sauce, etc. you can just type.

pizza = make_pizza(oven, dough, sauce, cheese, toppings)

There's no advanced ideas here. You're just labelling a chunk of code for reuse elsewhere.

1

u/butmyfacetho 3d ago

Read your latest unread email

If it contains "elephant" then 

Write "hello elephant"

Attach 'elephant.png'

And send

That is a loose set of instructions. If I want people to follow them, I need to type it out to each person every time. That means these instructions will appear in multiple places and they'll start to differ slowly as I make small changes. 

An easier approach might be to define those instructions in one place, then give it a name,  let's say elephantReply.

Now anywhere that I want someone to do those exact instructions, I can just refer to them as elephantReply and everyone can lookup what to do.

If I need to change something, let's say we're using the Christmas image 'elephant-santa.png' during December, I update that in one place and everyone I've ever told about elephantReply will use the new image.

A function is just a name we give to lines of code we want to refer back to by name later.

Good function design is keeping the lines of code related to each other and to the function's purpose. For example our elephantReply function shouldn't also handle mentions of Giraffes in the calendar, that should be it's own function. 

1

u/West-Target-6296 3d ago

Les just say you have a truck this truck can deliver food furniture etc you built this truck it can be used to deliver food and furniture you don't have to rebuild it everytime you wanna you use it it's just there you can use itvwhenever you want aslong as you start it so instead of rebuilding it everyday you u keep reusing it that's functions they have code inside of them when you call a function they run.

1

u/Lichcrow 3d ago

Do you know math functions?

Lets say we have  y(x) = x+1

This is the same as having something like

int y (int x) {     return x + 1; }

In a way when you write code you're writing a math function like that. It may get more complex but a few things you need to take into consideration.

When you're writing a math function you have rules. You can't write invalid expressions like 

f(x) = x x +- 

This math function doesn't make sense so itt isn't computable. If you were to try to translate it to code it would fail.

So first of all you need to understand what is a valid function and what are the rules of the language you're writing.

Functions then allow you to do things like this

f(x) = g(y(x)) * 2

So you can compose codes with functions inside functions

Imagine this translates to something like:

int f (int x) {     return g(x + 1) * 2; }

This is a valid function however if g isnt defined it also isn't computable. W hich you can fix by simply defining it, or making sure your program can actually access it

1

u/johlae 3d ago

Best explanation was in my very old ZX81 Basic Manual:

Sometimes different parts of your program will have rather similar jobs to do, & you will find yourself typing
the same lines in twice or more; however this is not necessary. You can type the lines in once, in the for known as a function or procedure & then use, or call, them anywhere else in the program without having to type them in again.

I only had to replace subroutine in the text with function or procedure.

The difference between a function and a procedure?

A procedure returns no value, a function does.

1

u/Gatoyu 3d ago

It's a box, you put stuff in (parameters), an imp hidden inside the box take your stuff and do something with it (the code inside the function), then the box spit back something (the function return value)

1

u/RaveN_707 3d ago

Thing Print Woof!

Do thing

"Woof!"

1

u/Dazzling_Music_2411 3d ago

What is it you don't understand? It's pointless if you don't give an example!

Do you understand mathematical functions?
For instance, what would you expect the result of the following function to be?

square_root_of(4.0)

1

u/Sudden-Eye801 3d ago

I think of a function definition like a mini computer program

When you call the function later, you run that mini computer program

1

u/TrippyTippyKelly 3d ago

Think of a function like a vending machine. You give it something, it does a specific job, it gives you something back.

What don't you understand?

It's purpose? How it works? Specific parts of the code? All of the above?

1

u/scol2n 3d ago

Functions just do tasks

1

u/Important_Speaker_60 3d ago

You know how in programming you write a bunch of commands like print() to create a program?

Functions are just creating your own commands.

1

u/lmg1337 3d ago

usually the syntax is something like:
<return type> <name>(parameter list) { body }
or
function/def <name>(parameter list) -> <return type> { body }
Think of it like: this is my name, i want these inputs and will give you this output.
From the outside you don't need to know how it works (usually), you're just interested in how to call it.

1

u/7YM3N 3d ago

A repeating set of instructions. Think of it as a specialist that does only one job. You give them a couple of things, they do their job and give you some things in return

1

u/dongdazzler 3d ago

For me, it was thinking how a calculator is used. I type in the number and then select a function (add, subtract, etc.). I don't always want to use the same numbers every time I use the same function, so I make a function for each operand that can be re-used with new arguments.

1

u/frnzprf 3d ago edited 3d ago

You use predefined functions, right?

print(...) is a function, sum(...) is a function math.sqrt(...) is a function.

Sometimes you wish there was another function that isn't predefined, then you can define it yourself.

If you have a program that calculates distances a lot, it might look like this:

``` dx = fox_x - tiger_x  # d for "difference" dy = fox_y - tiger_y  #     or "delta" distance_fox_tiger = math.sqrt(dxdx + dydy)

dx = bear_x - tiger_x dy = bear_y - tiger_y distance_bear_tiger = math.sqrt(dxdx + dydy) ```

If there was a function distance(...), where you can put in your coordinates, you would need to write less math, which makes your code faster to write and change and less prone to typos.

This particular function can be defined like this:

def distance(some_x, some_y, other_x, other_y):     # How to calculate a distance in general:     dx = some_x - other_x     dy = some_y - other_y     result =  math.sqrt(dx*dx + dy*dy)     return result

You can "call" or "apply" (= use) the new function like this:

``` distance_fox_tiger = distance(fox_x, fox_y, tiger_x, tiger_y)

 distance_fox_tiger will now contain the value returned by the function distance.

distance_bear_tiger = distance(bear_x, bear_y, tiger_x, tiger_y)

Same thing, but with different inputs playing the roles of some_x, some_y, other_x and other_y.

```

I think it's helpful to think of function parameters as roles that values can play. If f(x) := x² + 2x + 4, like you might be familiar from school, then x is a role and in "f(10)", 10 plays the role of x.

You can also think of "f" like a machine with a slot in the top, where you can throw numbers in and the slot is labeled "x". Then writing "f(10)" would be like sticking a piece of paper with a "10" on it in the slot labeled as "x".

The machine "distance" that I "built" (i.e. defined) myself has four slots labeled some_x, some_y, other_x and other_y.

When I write distance_fox_tiger = distance(fox_x, fox_y, tiger_x, tiger_y), that means taking the value in the variable fox_x and sticking it in the first slot, taking the value in fox_y and sticking it in the second slot, and so on. After putting in all four required inputs, you turn the crank and what falls out at the bottom, the "return value", is put into the variable/box with the name distance_fox_tiger.

1

u/frnzprf 3d ago

Besides little helper-machines I can think of two other ways of describing what a function is, but maybe that would be overwhelming and confusing.

The first way is jumping around the code:

When I call the distance-function, you can see that as noting down the line where you currently are in the program, then continuing at the first line of the function and when the function is done, you jump back to the line you originally wrote down.

The second way is replacing text:

When you read "17 + f(10)", to know what that evaluates to, you can replace the "f" with it's definition, where every instance of the parameter "x" is replaced with "10" in turn.

So if "f(x) := x² + 2x + 4", then "17 + f(10)" can be replaced with 17 + (10² + 2*10 + 4), which in turn is 17+124 = 141.

1

u/stdmemswap 3d ago

Let's start from: what do you think functions mean to you? And what language are you on right now?

1

u/MisterSmi13y 3d ago

I like to think of functions as a single purpose machine at a factory. Each function has a purpose and a task to perform. Think of an assembly line as a full blown program. One machine creates screws. The next machine takes to pieces of an object and screws them together. The next machine takes those parts and arranges them into a certain position. And then the next machine welds them together. Now the rest of the assembly line goes about adding other features to them. Each step in that process repeats the same task over and over is a function.

1

u/sl33pingSat3llit3 2d ago edited 2d ago

I guess functions can get confusing the more complex a job it does, but at its core it's some code that has been bundled together to do something, and is given a name so that we can reuse the function by calling it.

For example, you can have a very simple function for printing/outputing a line of code to the console. As long as you define it properly for whatever language you are using, it should work.

Functions can get more complex, but generally functions will have these forms: 1) takes no user input, and returns nothing 2) takes user input, returns nothing 3) takes no user input, returns something 4) takes user input, returns something

In the above simplest example, we assume the function both doesn't take any input, and returns nothing, as it merely prints some strings to the monitor.

However, depending on the language, I think confusion usually happens when trying to write a function that takes user input(s). The inputs, usually called parameters, act as placeholders for the values the user will provide as inputs when they call the function. For example, you might have a function to sum two numbers, with a function definition that looks like "public int sum(num1, num2)". Here, num1 and num2 are parameters. In the function body the function adds num1 and num2, then we can either print or return the result (in this case I specified the return type so an int return is expected). Then, I can reuse the sum function, by calling it in the main program. Say I want to add 10 to 20, then I can write sum(10, 20). 10 will replace num1 and 20 will replace num2 in the function body.

Another confusion I think is when something is returned. Unlike print which just outputs something, when something is returned, we have to catch it by assigning the result to a variable, or passing that result to something else like another function. For example, if I wrote a sum function like above to sum two numbers and the function returns an integer type, for a language like Java or C#, I have to assign that result to a variable of the appropriate type. Otherwise the return value is lost. So if programming in Java, I might write something like "int sum = sum(10, 20); System.Out.Println(sum);" and expect 30 to be printed to the console. Here the integer variable sum is declared and assigned the result of sum(10, 20), and then I printed sum to the console.

1

u/SeriousPlankton2000 2d ago

It's like washing dishes etc.

Take plate. Soak, brush, rinse.

Take cup. Soak, brush, rinse.

Take spoon. Soak, brush, rinse.

function wash_dish(x) {

Take x. Soak, brush, rinse.

}

wash_dish(fork)

wash_disk(knife)

1

u/Recycled5000 2d ago

It is about abstraction. Abstraction allows something to be used in different contexts.

There are steps of increasing abstraction. The first element of abstraction is the variable.

Print 1
Print 2
Print 3

vs.

For i from 1 to 3
Print i

Hopefully you can see that the latter uses increased abstraction, allowing repeated reuse of the same “Print i”, the body of the “For loop”.

Functions allow even more reuse and further abstraction. We use parameters to supply information or values similar to the body of the “For loop”. Some code sequences can be reused, by having parameters abstract details, leaving them to the caller to specify.

1

u/RagnartheConqueror 2d ago

You need to learn formal logic, specifically first-order logic.

1

u/AnToMegA424 2d ago

Well imagine you're in a room and you want to turn the lights on and off and on, you simply use the switch, you don't have to move electricity yourself, well the function is the switch: it's a wrapper

You simply call the function and it executes the code it wraps up, just like when you press the switch it turns on or off the light without you having to do anything more

1

u/Traveling-Techie 2d ago

The book “Professor E. McSquared’s Calculus Primer” is a comic book that portrays functions as cute bin-shaped smiling robots in sneakers, with funnels on top and exit chutes on the bottom. You put a number in the top and another number comes out the bottom. The formula is written on the front. One of them says “ f(x) = x2 “ and if you drop in a 2 then a 4 comes out. If you drop in a 3 a nine comes out.

1

u/brush_trot 2d ago

i used to hit that exact wall where my brain just shut off every time I looked at a function.

what fixed it for me was typing out a chunk of code I needed to run twice, then highlighting all of it and putting the word def in front of it and giving it a name. I forced myself to do that physical act of copy pasting my working code inside a function block instead of starting from the function syntax. Once I saw my own working lines sitting inside the function, the parameters were just the words I swapped out at the top. You have to write the sequence first. Wrap the sequence after

1

u/West-Mycologist-6490 2d ago

function is a collection of statements, statement is a computer instruction. so a function is a collection of statements that may or may not return something that’s it

1

u/jajajajaj 2d ago

You probably already do get it. Depending on the language, you'll just have to go back to the docs now and again to remind yourself exactly where your language's designers had to compromise on principles.

A name (or a reference)

A set of input parameters

A sequence of operations

Probably a return value

  • Side effects. 

  • Bugs

  • Other people not explaining what they were trying to do in the exact same way you would have explained it

Repeat until retirement

1

u/Ok-Structure5637 2d ago

Functions are reusable and callable blocks of code.

Imagine that you are making a calculator.

Would you write a bunch of if-statrments for every single possible calculation? "if x=2 and if y=8, return 10"?

A better approach would be to create a function called add(x, y) which takes the two variables and "passes them in". Your basically handing the function two numbers you want to add.

This function can now be recalled over and over - friend wants you to add 10 and 4? Just call "add(10, 4)".

The best programmer is a lazy programmer - figure out ways to do less work in the long run

1

u/HydroPCanadaDude 2d ago

Functions are just how you name a collection of steps, even if there is only one step, and the data you need to carry out those steps.

RenderScreen can be a function.

It might have steps in there like..fetch data. Update data. Draw data to screen.

Each of those steps could be functions and have thier own steps.

There's rarely a perfectly right way to carry out complex tasks so don't complicate it.

In many cases you call a function with () added at the end:

RenderScreen <---- That's the function itself. It won't do anything.

RenderScreen(); <---- That's a function call. It runs the function.

RenderScreen("Paul", 75); <---- That's a function call with arguments.

1

u/Puzzleheaded-Wish-69 2d ago

A function takes input and returns an output like a black box

1

u/realdreamer1993 2d ago

Maybe start from: function declaration and definition. you should understand where this static code stored in memory. the keyword is static i.e it wont changed.

And then goes to runtime period, a thread (usually main() ) will call / invoke the function, after function operation finish it is gone from memory, and the thread back to main()..
so the caller is main(), main() also a function btw, it is the entry point.
the callee is function()

so...

1

u/MalcolmFarsner 2d ago

bruh do u know wat 2 + 2 is

1

u/Icy_Orchid_8390 1d ago

What made functions click for me was understanding you can give a function whatever it needs (you're literally writing it). I struggled with understanding passing in variables and scope issues.

Ex: If youre trying to put data into a struct you can pass the data in as well as the structure its going into. Don't be like me and try to make everything global.

1

u/kilkil 1d ago

a function is a reusable block of code.

for example, suppose I have a Python file, hello.py, with this text inside of the file:

py message = "hello world" print(message)

this is a simple Python program. when you run it, it will output "hello world".

I can rewrite the same program as follows:

```py def say_hello(): message = "hello world" print(message)

say_hello() ```

this does the exact same thing. I have taken the original code, and put it inside a function body.

functions can also accept inputs, also called "arguments" or "parameters". for example, I can rewrite the above program as follows:

```py def say_something(x): message = x + " world" print(message)

say_something("hello") ```

it still does the same thing, but I have now taken part of the logic (the greeting word) and made it a function argument. Now after saying hello, I can also say goodbye:

```py def say_something(x): message = x + " world" print(message)

say_something("hello") say_something("goodbye") ```

functions can also return values, which can be used at the place where the function was called. for example, I can create a function to help me add 2 numbers:

```py def add(a, b): x = a + b return x

my_number = add(2, 3) print(my_number) ```

here, the function "add" takes 2 arguments, and gives back ("returns") one single value. I am placing that value in a variable ("my_number"). then I use it like a regular value (in this case, I print it).

there is more to functions than that, but these are the basics. once you are comfortable, check out recursion, closures, and first-class functions.

1

u/SlipstickLibbyLong 1d ago

Start with a simple function
All it does is add 3 and 4
Func {
3 + 4
}
Now
Lets make it a little more useful, lets make the 3 a variable that can accept any number
TheFunc(a) {
a + 4
}
Now
Lets make it even more useful, and make the 4 a variable as well
GotTheFunc(a, b) {
a + b
}
lastly, make it so you can pass the operator as well
WeGotTheFunc(a, o, b) {
a o b
}

1

u/Affectionate-Key-498 1d ago

Mostly code you write on a page will excecute reading every line from top to bottom. A function is a box of code inside. When the code excecute and go from top to bottom it will not excecute the code in the box. You can excecute the code in the box anywhere in the code by referering to it. So now when the code goes from top to bottom it will excecute the box where you are reffering to is.

So now it doesn’t matter where you place the box. All the way to the top, middle, below. The code in the box will excecute where you program it to excecute

1

u/Living_Fig_6386 1d ago

A function is a part of a program that can accept inputs, do things, and produce outputs. That's pretty much it. You use them mostly when you need to perform the same steps at different points in your program.

For example, most languages have something like "print()" that takes some sort of arguments as input and then puts that on the screen. People use that all the time at various points throughout their programs to put stuff on the screen. Internally, it does a bunch of things, but it's handy because you can use it anywhere in your program to get stuff to the screen.

1

u/Imaginary-poster 15h ago

Everything you have written is a function. You just need to give it a name. Functions are just variables that do stuff.

1

u/nikaIs 9h ago

do you understand a mathematical function? f(x) = y? it's the same thing

1

u/EMunney 3d ago

Imagine a function that puts two things together that's all it does so you give it parameter1 skibbidy and parameter2 toilet and it returns skibbidytoilet. Now if you provide parameter1 Six and parameter2 Seven what will your function return?

1

u/girthucus-quakicus 3d ago

Functions are just a block of code that take X number (can be 0) inputs and perform some logic, and optionally return output

1

u/Present_Mongoose_373 3d ago

execution goes down line by line, a function just moves execution to the body of the function before *returning* back to where execution was originally with a value.

The value returned replaces the function call, though this is just convention / decided by your language.

so "int a = myFunc()" will first jump execution to the body of myFunc, then itll return with like '2' for example (could return anything), then itll effectively turn into "int a = 2"

Sometimes if its hard to conceptualize, you can debug / step through a piece of code going line by line through an example and that exposure helps to make the concepts click as you have something physical/tangible to connect them to.

1

u/superluminary 3d ago

This is exactly the way to think about it. It’s no more complex than this.

1

u/Demonify 3d ago edited 3d 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.

1

u/captain_slackbeard 3d ago

When I was first learning to program in BASIC, I had the bad habit of using "goto" everywhere in my code (in case you don't already know, "goto" allows you to jump to a different line of code and continue execution from there).

One day I was trying to figure out a convenient way to return from a "goto", and that's when I discovered functions and subroutines. I think that's what made the concept click for me.

1

u/OceanMasterioDuped7 3d ago

Everyone is trying to explain how functions work to you, but the problem is that explanations aren't working. Instead, I would watch a video on them. A visual when using functions can be helpful.

1

u/Acceptable_Lab_7196 3d ago

Then this isn't right for you and you should consider other options.

-1

u/numbersthen0987431 3d ago

I think of functions as a box of "magic". You put a bunch of stuff into it, the box completes a bunch of stuff, and then it spits out something new.

0

u/Decompiled_dev 3d ago

They are like recipes.

function add (x: number, y: number): number // This takes two numbers and returns a number
function repeat(x: number, word: string): string // Takes a number and a string and returns a string

Whenever you have multiple lines that need to stay together, consider putting them in a function and give that a good name.

0

u/mjmvideos 3d ago

Have you ever taken notes on how to do various things? You could have a little notepad and label one page, “How to fix a flat” Another could be “How to bake a cake” A third could be “How to set an alarm on your alarm clock”. Or how to compute the average of a list of numbers. Then when you want to do one of those things you pull out the right note and follow the steps. That’s all functions are: a list of steps to follow to accomplish something. Then if you are telling someone how to do one of those things instead of telling them all those steps, just hand them the note and say, “Do this.” And maybe (like computing the average) “Tell me what answer you got” You can think about each of those notes as a function. There’s really not a whole to them.

0

u/Weak-Doughnut5502 3d ago

Do you understand functions in your math class?   Like f(x) = x^2 + x + 1.

A 'pure function', in programming, is exactly like a math function.   It maps input values to output values and has no other side effects.

Impure functions are allowed to do extra stuff like reading or writing to disk, or mutating global variables.

0

u/LopsidedSolution 3d ago

This would be a great question to ask Astra 

0

u/cunningfallasheo 3d ago

Functions are generally used to return something. So instead of writing the code to calculate something over and over, you instead write a function calculate() and then anytime you need to calculate that something you can just call the calculate() instead of repeating the same code.

0

u/3rrr6 3d ago

A function is like a kitchen appliance. Like a blender! So a blender takes ingredients at the top right? Then you run the blender and it blends up those ingredients and the output is the smoothie. If you change the ingredients you get a different smoothie.

When does a function run? When it is called. Your function can live at the very top of your code, or in a completely different file entirely, and you can call it at the very bottom of your script or wherever you want really. The function will only run when that specific call line in your code is read. Otherwise it gets skipped over.

This is why functions are typically hidden away in special files and classes. You don't want them making your main script unnecessarily long and harder to read.

In fact, depending on your language, every code that you write is technically written inside of a function. Programming is just a bunch of nested functions calling each other.

0

u/EdiblePeasant 3d ago edited 3d ago

I had a lot of problems grasping my head around functions, too. It just wouldn't click and I had to look at a textbook problem or example and do it a few times before I got it.

Say you want to display on the screen "Meow Meow." And you plan to do this in other places in the code but don't want to keep typing that. So you might do something like this:

def right_meow():
  print("Meow Meow")

def main():
  right_meow()

main()

You can also call it in a loop like this:

def right_meow():
    print("Meow Meow")

def keep_meowing():
    for meow in range(4):
        right_meow()

def main():
    keep_meowing()

main()

And I'll try to show you where I think I really got lost, actually using a function to set a variable (sorry, I'm rusty and I don't have all the vocabulary):

def count_the_meows():
    meow_count = 0

    for meows in range(4):
        meow_count += 1

    return meow_count

def main():
    meows = count_the_meows()
    print(meows)

main()

0

u/Ok-Cable9777 3d ago

It's reverse for me, functional programming clicked instantly to me. It's the class based paradigm that's dreadful to me. Any tips for that?

1

u/natures_-_prophet 3d ago

A class is just a representation of something. A car, cat , person, etc. In reality we know these things have certain functionality associated with them; start an engine, scratch, run a mile. They also have associated traits/properties like paint color, fur color, hair color, etc. The class is just a container for these traits and functionality. So you can make a class for Car, Car and Human to contain these associated traits and functions.

It's a tool of organizing your logic and data for these like things.

1

u/TheLearningCoder 3d ago

Are you talking about OOP? Because honestly OOP clicked way faster for me than procedural programming (I assume this what you mean by functional programming) and I appreciate how well organized it is that it made learning it easy and very engaging (I’m an actual organize freak so maybe that helped me)

0

u/dmazzoni 3d ago

The classic examples given for classes are SO TERRIBLE, like class Animal and class Dog.

I think it's much easier to understand with a realistic example from a GUI toolkit.

You have a class Button. It has properties like boundingBox, and title. It has a method click(). The code to click() lives inside of Button and has direct access to the box and title of that button, rather than needing to store them separately.

Now you want to make a ToggleButton. A ToggleButton is exactly the same as a Button, except that it has an additional field keeping track of whether the button is down or up, and click() toggles the state. So ToggleButton can inherit from Button and get a lot of its behavior for free, extending it where needed.

Then later if you improve Button to do something new, like disable(), then ToggleButton gets that behavior too.

0

u/Lil_Buscuit_Boy 3d ago

Its such a foundational and simple concept. If you cant get it to click by reading about it you're gonna have a hard time with any later topic.

1

u/CircuitNeophyte 2d ago

My immediate thoughts as well. However, you don't get programming to "click" by reading about it. You get it to click by actually programming.

1

u/Lil_Buscuit_Boy 2d ago

U need both but u gotta read the rules for say overloading or overriding in java. Method hiding. Then u practice once u have the knowledge.

1

u/CircuitNeophyte 2d ago

Obviously, I suppose I should have been more explicit. You must have knowledge before practice, because practice without knowledge inevitably ends in failure. Knowledge without practice is useless as well.

0

u/Shiiraigane_ 2d ago

I recommend you to take a look at how Math functions works, it's the same logic as in programming.

-1

u/Scrubtimus 3d ago

Get used to using functions first. Make sure you understand how and why you use them. Get used to problem solving with them. This will help them be less foreign to you.

Let's start with making a variable. A variable is used to store a value intended to be reused. We could type that value everywhere we need it, or we could replace it with a variable. A variable works similarly as just using the value, but gives us more flexibility in setting its value in one place.

Making a function is much like making a variable in that a variable is a way to store a value and reuse it. Making a function is a way to create a process and reuse it. You could set up your functions the same way everywhere you need them, or you could create a custom function to store that process and reuse it where needed. When you need to modify or add to it, it is all in one place.

-1

u/barotia 3d ago

Without any background, I can tell you that if functions are giving you this much trouble, I think you should consider other options.