A function is a collection of statements that accept input, perform some specific computation, and return output. The idea is to combine some frequently or repeatedly performed tasks into a function so that instead of writing the same code for different inputs, we can call the function.
All functions written by the user fall into the category of user-defined functions. It contains the following components:
Syntax:
def function_name (parameter_one, parameter_two, parameter_n):
# logic here
return
Example 1: simple function
def fun():
print("Inside function")
fun()
Output:
Inside function
Example 2: parameterized function
def add(x, y):
print(x+y)
add(3,9)
Output:
12
Example 3: default function
A default argument is a parameter that takes on a default value if no value is specified for it in the function call.
def add(x, y=10):
print(x+y)
add(3,9)
add(3)
Output:
12
13
A return statement terminates the function call’s execution and “returns” the result (the value of the expression following the return keyword) to the caller. The statements following the return statements are ignored. If there is no expression in the return statement, the special value None is returned. In order to make a function return a certain value, put an expression in front of the return statement. The value of this expression may be assigned to some variable for subsequent processing.
Syntax:
def fun():
#statements
return [expression]
Example:
def add(a, b):
# returning sum of a and b
return a + b
ans = add(12, 39)
print("Result of add function is {}".format(ans))
Output:
Result of add function is 51
An alias is the second name given to a piece of data in Python programming. Because variables are just names that store references to actual values, aliasing occurs when the value of one variable is assigned to another variable.
Example:
def add(a, b):
# returning sum of a and b
return a + b
xyz=add
ans = xyz(12, 39)
print("Result of add function is {}".format(ans))
Output:
Result of add function is 51
Note: also read about Loops in Python
Please follow me to read my latest post on programming and technology if you like my post.
https://www.instagram.com/coderz.py/
https://www.facebook.com/coderz.py
Staying up to the mark is what defines me. Hi all! I’m Rabecca Fatima a keen learner, great enthusiast, ready to take new challenges as stepping stones towards flying colors.
Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…
Given an integer A. Compute and return the square root of A. If A is…
Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…
A heap is a specialized tree-based data structure that satisfies the heap property. It is…
What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…