A function is a block of code which only runs when it is called. A function can be called as a section of a program that is written once and can be executed whenever required in the program, that making code reusability.
Types of Functions:
User-defined Functions
Built-in Functions
Recursive Functions
Lambda Functions
1.User-Defined Function:
In Python function, you’d have to use the ‘def’ keyword and then the name of your function and add parentheses to its end, followed by a colon(:).Function_name are meaningful and descriptive use lowercase or uppercase letter or underscore.
*Indentation is important following statements will belong to the function.
Syntax:
def function_name():
return value
#calling a function
function_name()
Example1: Function without Parameters
def my_function():
print("Hello Python")
my_function() # calling a function
Example2: Function with parameters
#Single parameter
def my_functions(name):
print(name)
my_functions("Mike")
Example3: Function with Return values
def get_function(name):
return f"Hi {name}" # return the value and f is format string
message = get_function("Mike") # variable assigned 'message'
print(message) # print the data in console
Example4: Function with Default Parameters
def user(name="firstname"):
print(f"Hi,{name}")
user("John")
Example5: Function with NO Returns value
def msg():
print("Hello Python")
res=msg() #print "Hello Python"
print(res) #print "None"
Parameter is the input that you define for your function.
Arguments is the actual value for a given parameter.
Types of Arguments:
Positional arguments
Keyword arguments
Default argument
Variable list of arguments (*args)
Variable list of keyword arguments (**kwargs)
Positional Arguments
Postional arguments means when calling the function, values passed to the arguments by their position.All the arguments that need to be passed in correct positional order.
Example of Positional Arguments:
def user_data(firstname, lastname):
print(firstname)
print(lastname)
# Arguments in the order
user_data("Jake", "Smith") # Positional Argument
Keyword Arguments
Keyword arguments means when calling the function, values passed get assigned to the parameters according to their position. The keyword arguments is a key and value pair.Key is the parameter name and value is the argument passed to that parameter.
Example of Keyword Arguments:
def user_info(firstname , lastname):
print(firstname , lastname)
user_info(firstname="Micheal",lastname="Jakeson")
Default Arguments:
Parameters that assume a default value if a value is not provided in the function call.
Example:
def emp_details(name, age=30):
print("My name is:", name)
print("My age is:", age)
emp_details(name="Mike")
Variable list of arguments (*args) and(**kwargs):
Arbitrary Positional Arguments (*args): Allows you to pass a variable number of positional arguments.All the arguments passed into tuple.
Arbitrary Keyword Arguments (**kwargs): Allows for a variable number of keyword arguments.All the arguments passed into dictionary.
Example:
def arg_example(a=1, b=2, args, *kwargs):
print(a, b)
print(*args)
print(**kwargs)
print(type(args))
arg_example(1, 2, 'Hi', 'Everyone')
In this program I used user input() function
def addition(a, b):
return a + b
number1 = int(input("Enter the First Number:"))
number2 = int(input("Enter the Second number:"))
sum_num = addition(number1, number2)
print("sum_num {0} and {1} is {2}".format(number1, number2, sum_num))
Output of this Addition Program:
2.Built-in Function
Some Built in Python Function :
Built in Function | Purpose |
abs(x) | Returns the absolute value of number x(converts negative numbers to positive). |
bin(x) | Returns a string representing the value of x converted to binary. |
float(x) | converts a string or number x to a float data type. |
str(x) | Converts number x to the string data type. |
int(x) | Converts x to the integer data type. |
round(x,y) | Rounds the number x to y number of decimal plates. |
type(x) | Returns a string indicating the data type of x. |
oct(x) | Converts x to an octal number,prefixed with 0o to indicate octal. |
hex(x) | Returns a string containing x converted to hexadecimal. |
min(x,y,z) | Takes any number argument and returns whichever one is smallest. |
max(x,y,z) | Takes any number argument and returns whichever one is largest. |
input() | Returns the user input in form of a string. |
format(x,y) | Returns x formatted as directed by format string y. |
Example for Built in function:
Some functions from the Python Math Module:
In python,built in math function you can import the math module.To use a function from a module,you have to import the module and function name with module name and dot. The math module offers a lot trigonometric,hyperbolic functions,power,constants like pi.
Built in function | Purpose |
math.acos(x) | Returns the arc cosine of x in radians |
math.radians(x) | Converts angle x from degree to radians. |
math.pow(x,y) | Returns x is raised to the power y |
math.sqrt(x) | Takes any number of numeric argument and returns whichever one is smallest. |
math.floor(x) | returns the floor of x,the largest integer less then or equals to x. |
math.factorial(x) | Returns the factorial of x |
math.degrees(x) | Converts angle x from radians to degrees. |
math.log(x,y) | Returns the natural logarithm of x to base y. |
math.e | Returns the Mathematical constant e. |
Recursive Function:
A function that calls itself is said to be recursive, and the technique of employing a recursive function is called recursion.A recursion is widely used for tasks that can be divided into identical subtasks.Recursion can reduce the length of the code since the repetitive tasks are handled through repeated function calls.
Example of Recursive Function:
Lambda Function:
Lambda Function is single line function that can take number of arguments.A lambda function supports all the different ways of passing arguments.
Syntax:
lambda parameters: expression
Example of def function:
def mul(x, y, z):
return x y z
print(mul(1, 3, 5))
Example of Lambda Function:
mul = lambda x, y,z: x*y*z
print(mul(2, 5,6))