function
What is a function?
A function is a group of related statements that perform a specific task.
The function helps break our program into smaller and modular chunks. As our program grows larger and larger, functions make it more organized and manageable. It avoids repetition and makes code reusable.
👉How to define function -
In Python, we can define a function using the ‘def’ keyword, followed by the function name, any input arguments in parentheses, and a colon. The code inside the function should be indented.
Example 👇
def add_numbers(a, b):
return a + b
Function Call -
Once we have defined a function, we can call it from anywhere -
To call this function, you would simply write its name followed by the arguments you want to pass in parentheses:
result = add_numbers(3, 4)
print(result) # Output: 7
2.1 TYPE OF FUNCTION IN PYTHON
Built-in function - Python has many built-in functions that are available without having to import any additional modules or libraries. Some examples of built-in functions in Python include:
Example 👉
print()
- prints the specified message to the console.input()
- accepts input from the user via the console.len()
- returns the length of a string, list, tuple, dictionary or set.range()
- generates a sequence of numbers.type()
- returns the data type of a variable.max()
- returns the largest item in an iterable.min()
- returns the smallest item in an iterable.sum()
- returns the sum of all items in an iterable.abs()
- returns the absolute value of a number.round()
- rounds a number to a specified number of decimal places.
These are just a few examples of the many built-in functions available in Python. You can find more information about built-in functions in the Python documentation.
User-define function - In Python, a user-defined function is a function that is created by the programmer to perform a specific task or set of tasks.
Example 👉 def square(num):
return num*num
The given code defines a user-defined function called square
that takes one parameter num
and returns the square of that number.
Therefore, this is an example of a simple user-defined function in Python that performs a specific task of calculating the square of a given number. The function takes a numeric value as input and calculates its square using the arithmetic operator *
, and returns the result to the caller.