Functions in Python
What are Functions
Functions are ways to write codes that you always use to be able to use it again.
They make codes easier to read and understand.
When writing large programs, it is always advisable to use Functions as it makes the program more arranged and organized.
A function is defined using def followed by the function name, then parenthesis with a colon(:) to mark the end of the function head.
As seen below;
def function_name(): "write your codes here"
Important Things to note about Functions
The def marks the beginning of a function definition.
The function_name is any name you chose to give to your function, it should be unique and follow the standard python naming convention.
A function should always be defined before calling it.
A colon: marks the end of the function header.
Statement and codes in a function must have the same indentation level else an indentation error will be displayed.
A function can have a return [expression] statement to return an expression or value from a function but it is optional.
A function can have an optional arguments inside the parenthesis.
Creating a function
A function can be created either with parameters(arguments) or without any parameters(arguments).
Creating Functions without Parameters
def info(): print("The food is ready.")
Creating Functions with Parameters
def info(name): print("Hello", name, "the food is ready.")
One important thing about functions is that after defining the function and writing the codes, the function will have to be called for it to work. And a function can be called from another function or program.
To call a function, we just type in the function name followed by parenthesis. If a parameter is given in the function, the value for the parameter will be placed inside the parenthesis.
From our Examples above;
def info(): print("The food is ready.") info()
With a parameter
def info(name): print("Hello", name, "the food is ready.") info("John")
Using return statement
A return statement can be used in a function to either end the function or go back to where it was called.
If the return statement is not written inside a function, it returns none.
def info(x): square=x**x return print(info(2))
If the return statement is written, it returns it's expression.
def info(x): square=x**x return square print(info(2))
There are basically two types of functions in-built functions and the user-defined functions.
Yay! That's all on functions for now.
Bye for now.