Functions are used to group a piece of code together. Function can have a return value or it may not return anything. Function are essential to make code more readable. If your program has thousand of line of code( most of application will have more than 1 thousand line of code), it is always good practice to break them in to function.
def keyword is used to create the function. The Naming convention of function follows the same convention as that of identifiers .
Syntax without params:
def function_name(): body_of_function
Syntax with params:
def function_name(param1, param2, param3,...) function_body
param1, param2, param3, etc are called parameters and these are value we pass in a function to perform various operation based on these value.
Calling a function:
Calling a function refers to executing a code inside it’s body. a function by itself does not execute code. It need to be called to execute it’s code. To call a function we just write function name and small bracket open and close and pass parameter it the function signature has it. For example in above definition we simply do
calling function with parameter:
Best practices for writing function in python
It is not a rule but a good practice while creating function is not to make it too large. Most developers would keep it under 30 lines, if a function starts getting bigger they break them into further smaller functions.example 1 of function with parameter value:
# function to calculate area def calculate_triangle_area(base, height): area = (height * base) / 2 return area # call function area1 = calculate_triangle_area(5, 10) print("triangle with base 5 and height 10, area = ", area1)
triangle with base 5 and height 10, area = 25.0
As you can see we had 2 parameters( base and height) so while calling a function we passed two values. We can also have a function that has no parameter and return no value.
Another example without parameter and return value.
def print_message(): print("message from inside function") # calling the print_message() function print_message()
message from inside function