Types of Functions in Python
Python has three main types of functions:
1. Built-in Functions
2. Functions defined in a Module
3. User-defined Functions
1. Built-in Functions
These are functions that Python provides by default.
Examples: print(), len(), max(), sum(), type(), etc.
Example:
# Using built-in functions
numbers = [10, 20, 30, 40]
print("Total numbers:", len(numbers)) # len() gives the number of elements
print("Maximum number:", max(numbers)) # max() returns the largest value
print("Sum of numbers:", sum(numbers)) # sum() adds all the values
Output:
Total numbers: 4
Maximum number: 40
Sum of numbers: 100
2. Functions Defined in a Module
These are functions that come from external modules (Python files or libraries). You need to import them.
Common modules: math, random, datetime, os, etc.
Example:
# Importing math module
import math
print("Square root of 25:", [Link](25))
print("Value of pi:", [Link])
print("2 raised to the power 3:", [Link](2, 3))
Output:
Square root of 25: 5.0
Value of pi: 3.141592653589793
2 raised to the power 3: 8.0
3. User-defined Functions
These are functions that you create to perform a specific task.
Syntax:
def function_name(parameters):
# code block
return result
Step-by-step Example:
Let’s write a function to add two numbers:
# Step 1: Define the function
def add_numbers(a, b):
result = a + b
return result
# Step 2: Call the function
sum_result = add_numbers(10, 20)
# Step 3: Print the result
print("Sum:", sum_result)
Output:
Sum: 30
More Examples of User-defined Functions
Function with no parameters
def greet():
print("Hello! Welcome to Python.")
greet()
Output:
Hello! Welcome to Python.
Function with parameters and return
def multiply(x, y):
return x * y
result = multiply(5, 6)
print("Product:", result)
Output:
Product: 30
Summary Table
Function Type Example Description
Built-in Function print(), len() Already available in Python
Module Function [Link](), [Link]() You import from libraries
User-defined Function def my_function() You write your own logic
What is a User-defined Function?
A user-defined function is a function that you create to perform a specific task.
Syntax of a Function
def function_name(parameters):
# block of code
return result
• def: keyword to define a function
• function_name: the name you give to your function
• parameters: optional input values (inside parentheses)
• return: optional; sends the result back to the caller
Step-by-Step Examples
1. Function with No Parameters and No Return
def say_hello():
print("Hello! Have a great day.")
# Call the function
say_hello()
Output:
Hello! Have a great day.
2. Function with Parameters (No Return)
def greet(name):
print("Hello,", name)
# Call the function with an argument
greet("Anjali")
Output:
Hello, Anjali
3. Function with Parameters and Return Value
def add(a, b):
result = a + b
return result
# Call the function and store the result
sum_result = add(10, 20)
print("Sum is:", sum_result)
Output:
Sum is: 30
4. Function to Check Even or Odd
def check_even_odd(number):
if number % 2 == 0:
return "Even"
else:
return "Odd"
# Call the function
result = check_even_odd(7)
print("The number is:", result)
Output:
The number is: Odd
5. Function to Calculate Factorial
def factorial(n):
result = 1
for i in range(1, n + 1):
result *= i
return result
# Call the function
print("Factorial of 5 is:", factorial(5))
Output:
Factorial of 5 is: 120
Summary
Function Type Return? Parameters? Example Use
No parameters No No say_hello()
With parameters No Yes greet("Anjali")
With parameters Yes Yes add(10, 20)
1. Arguments vs Parameters
Parameters:
• Variables defined in the function definition.
• Placeholders for actual values.
def greet(name): # name is a parameter
print("Hello", name)
Arguments:
• Actual values passed to the function when it is called.
greet("Anjali") # "Anjali" is an argument
Summary:
• Parameter: name used inside the function
• Argument: actual value passed to the function
2. Default Parameters
A parameter can have a default value. If no argument is passed, the default is used.
def greet(name="Guest"):
print("Hello", name)
greet() # Uses default
greet("Ravi") # Overrides default
Output:
Hello Guest
Hello Ravi
3. Positional Parameters
Arguments passed in the order of parameters.
def display_info(name, age):
print(name, "is", age, "years old.")
display_info("Anjali", 32) # name = Anjali, age = 32
Output:
Anjali is 32 years old.
4. Function Returning Value(s)
Functions can return one or more values using the return keyword.
a. Single Return Value
def add(a, b):
return a + b
result = add(10, 20)
print("Sum:", result)
b. Multiple Return Values
def calculate(a, b):
return a + b, a * b
sum_val, product = calculate(4, 5)
print("Sum:", sum_val)
print("Product:", product)
Output:
Sum: 9
Product: 20
5. Flow of Execution
• Python starts executing from the first line.
• Function definitions are skipped until the function is called.
• Once called, the function code runs.
• After it finishes, Python continues from where it left off.
Example:
print("Start")
def greet():
print("Hello!")
greet()
print("End")
Output:
Start
Hello!
End
6. Scope of a Variable
Scope means where a variable is accessible.
Local Scope:
• Variable defined inside a function.
• Exists only within the function.
def example():
x = 10 # local variable
print("Inside function:", x)
example()
# print(x) # Error: x is not defined outside
Global Scope:
• Variable defined outside all functions.
• Can be used anywhere in the code.
x = 100 # global variable
def show():
print("Inside function:", x)
show()
print("Outside function:", x)
Modifying Global Variable in Function
Use global keyword if you want to modify global variable inside a function.
x = 5
def change():
global x
x = 10
change()
print("New x:", x) # Output: New x: 10
Summary Table
Concept Description Example
Parameter Placeholder variable in function definition def greet(name)
Argument Actual value passed to function greet("Anjali")
Default Parameter Parameter with a default value def greet(name="Guest")
Positional Arguments matched in order def info(n, a) → info("A",
Parameter 30)
Return Value(s) Values returned using return return x + y
Flow of Execution Top to bottom, function only runs when
called
Local Scope Variable inside a function x = 10 inside a function
Global Scope Variable outside all functions x = 100 at the top level
Docstring
The first string after the function is called the Document string or Docstring in short. This is
used to describe the functionality of the function. The use of docstring in functions is optional
but it is considered a good practice.
The below syntax can be used to print out the docstring of a function.
Syntax: print(function_name.__doc__)
Example: Adding Docstring to the function
# A simple Python function to check
# whether x is even or odd
def evenOdd(x):
"""Function to check if the number is even or odd"""
if (x % 2 == 0):
print("even")
else:
print("odd")
# Driver code to call the function
print(evenOdd.__doc__)