Python Functions

   

A function is a block of code that performs a specific task whenever it is called. In bigger programs, where we have large amounts of code, it is advisable to create or use existing functions that make the program flow organized and neat.


There are two types of functions: 
  1. Built-in functions 
  2. User-defined functions

Built-in functions:

These functions are defined and pre-coded in python. Some examples of built-in functions are as follows:

min(), max(), len(), sum(), type(), range(), dict(), list(), tuple(), set(), print(), etc.


User-defined functions: 


We can create functions to perform specific tasks as per our needs. Such functions are called user-defined functions.


Syntax:


  def function_name(parameters):
  pass
  # Code and Statements
  
  • Create a function using the def keyword, followed by a function name, followed by a paranthesis (()) and a colon(:). 
  • Any parameters and arguments should be placed within the parentheses. Rules to naming functions are similar to that of naming variables. 
  • Any statements and other code within the function should be indented.

Calling a function:


We call a function by giving the function name, followed by parameters (if any) in the parenthesis.

Example:


def name(fname, lname):
    print("Hello,", fname, lname)

   name("Sam", "Wilson")

Output:


Hello, Sam Wilson


Sample code by me:-



#I am Vaibhav Manaji  
#this sample code is for creating user defind function
def multinum(a,b):    # I used multinum as name for funtion you can take any name
  multi=a*b           #  what isfuntion will do. I have created this for multiplicaion
  print("Multiplication of given numbers is:",multi)   #it will print the result

def isGreater(a,b): #Creating another function to check aur to tell which number is greater 
  if (a>=b):    #checking a is greter or not
    print("First number is greater") #if yes then print this 
  else:  
    print("second number is greater") #if not then print this

#now appling funtions

a=int(input("Enter first number:")) #taking input value for a 
b=int(input("Enter second number:")) #taking input value for b
isGreater(a,b) #appling function to check which number is greater
multinum(a,b)  #appling function to multiply the input value

#for one more opration

c=int(input("Enter another first number:"))#taking input value for c
d=int(input("Enter second number:"))#taking input value for d
isGreater(c,d)
multinum(c,d)

''' Now every time if you want to multiply two numbers you can use just multinum funtion
Hope this sample code helped you to create user defind function
By Vaibhav Manaji '''
Tap/click on image for full view

Download the python file of the above code👆