- OK, a function is a piece of code.
- A function may/may not accept input(s).
- A function may/may not return an output(s).
- Well, the Reusability of the code in a program is made possible through functions.
- The program can call these so-called functions, n - number of times.
- This showcases the best practice in a program called DRY.
- A code is said to be DRY if any given code does not repeat certain tasks.
- A function implements this just by writing once and using it whenever necessary.
- To create a function we use the keyword
must be followed by the function name.
- followed by a parenthesis filled with formal parameters(parameters).
- The statements that follow up makes the body of the function.
- Note: Any code written inside a function must be indented.
- Let's see an example where I thank every one of my readers:
Calling a function:
- To call a function we use the function name followed by parenthesis filled with actual parameter(arguments).
- This is when the code inside the function actually gets executed.
- Let's see the same example and its output:
Hello there John Doe Thank you for taking your time to read my post ;) Hello there Jane Doe Thank you for taking your time to read my post ;)
Passing values to a function:
- Didn't you notice passing values to a function already?
- We can pass values to a function through the function call.
- We do this by writing the values inside the parenthesis of a function call.
- Consider the above example:
reader("John Doe") reader("Jane Doe")
- The function call
passes the values "John Doe" and "Jane Doe" as arguments to the function.
As we have seen the power of functions, pass statements inside a function can be really helpful whenever we feel lazy to do something and decide to do later ;)
Note: The body of any statement containing pass statements are ignored by the python interpreter, just like it ignores comments.
There you go, now you can create your own functions and play with it.
Code along and fave fun.
Also published at https://dev.to/aswin2001barath/functions-in-python-3i4h
Create your free account to unlock your custom reading experience.