Defining functions | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Defining functions

I'm having a hard time understanding the reason for defining a function in python... It just seems like it makes a simple problem much more complicated for no reason. Isnt the same in the end as just printing out the function? Just with more steps.

28th Sep 2017, 2:52 AM
${Levi}
${Levi} - avatar
4 Answers
+ 13
In large projects, we may not want the whole calculation process to be within a single function. Different functions handle different parts of a calculation process and in such cases, you will want your function to return the final product back to where it is called, in order for the rest of the calculation to take place. Take for example def f(x), which may be used multiple times over different values of x, in most cases we will want to slot f(x) somewhere in an equation instead of just having the print statement written in the function definition. This is when you have to return the value to the caller.
28th Sep 2017, 4:30 AM
Hatsy Rei
Hatsy Rei - avatar
+ 4
@Levi, the examples given in the course are indeed seemingly an overhead, but in more difficult cases where the works involve more than just printing words, functions are useful, besides, repetition works can be simplified by functions, so instead of writing the same instructions inline 5 times you can wrap the repetition instructions into a function and use loops to call the function any number of times, and of course there's recursion, something you can't avoid the use of function upon. This is my point of view on functions, I'm sure others have their thoughts on the matter. Hth, cmiiw
28th Sep 2017, 4:33 AM
Ipang
+ 1
@hatsy Rei and @Ipang... Thank you for your answers, I understand it a little better now, and also realize that I have a LO N G way to go to be any good at it. Oh well, practice makes prefect, right?
28th Sep 2017, 7:57 AM
${Levi}
${Levi} - avatar
+ 1
Click The help button
4th Nov 2017, 5:03 PM
Eloise Joni
Eloise Joni - avatar