Python Functions
Function Definition and Call:
A function is a block of reusable code that performs a specific task.
Syntax:
def function_name(parameters):
# block of code
return value # optional
Defining a function:
Step1: First, we have to use def keyword to declare the function followed by function name.
Step 2: Write parameters inside the opening and closing parenthesis ( ) of the function, and end the declaration
with a colon(:).
Step 3: Add the program statements to be executed.
Step 4: End the function with / without return statement.
By default, parameters have a positional behaviour and you need to inform them in the same order that they were
defined. For Example-
def greet(name):
print("Hello,", name)
Calling the function
greet("SYIT")
Returning Results from a Function:
In python, function can send results back to where they were called by using the return statement.
When the function finishes its work, return gives a value ( or more than one value) back to the caller. This lets the
program save and use the result later. Without return, the function returns None by default.
For Example-
def add(a, b): #Function
return a + b
result = add(10, 5) # Main program
print(result)
OUTPUT- 15
Returning Multiple Values from a Function
Python allows functions to return multiple values as a tuple. For Example:-
def calculate(a, b):
return a+b, a-b, a*b
Sum_, diff, prod = calculate (12,4)
Print (“Sum:”, Sum_, “Difference:”, diff, “Product:”, prod)
OUTPUT:
16, 8, 48
Write a function that returns area and perimeter of a rectangle using function
Explanation:
•length * width → calculates area
•2 * (length + width) → calculates perimeter
•Both values are returned as a tuple and stored in a and p
Create a function to return the largest of three numbers.
Explanation:
•Uses if-elif-else to compare all three numbers
•Returns the one with the greatest value
Python Function: Return Area and Perimeter
def rectangle_properties(length, width):
area = length * width
perimeter = 2 * (length + width)
return area, perimeter
# Example call
a, p = rectangle_properties(10, 5)
print("Area:", a)
print("Perimeter:", p)
Python Function: Return Largest of Three Numbers
def find_largest(a, b, c):
if a >= b and a >= c:
return a
elif b >= a and b >= c:
return b
else:
return c
# Example call
largest = find_largest(25, 10, 42)
print("The largest number is:", largest)
Buit-in Functions:
Python comes with many built-in functions. These are ready to use functions and need not write code for the function.
Few are listed here.
Function What it does Example
Print() Displays output on the device Print(“Hello”)
Input() Takes input from the user Name=input(“Enter Name”)
Len() Give length of s string, list etc. Len(“apple”) => 5
Type() Shows the type of a value or variable. Type(6) => <class ‘int’>
Int(), str() Converts between data types Int(“10”) => 10
Sum() Adds up items in a list or tuple. sum([1,2,3,4]) => 10
Max(), min() Finds the largest or the smallest value max(7,8,9) => 9
Difference between Function and a method:
Function(): A block of code that operates on data and may or may not belong to an object.
Method(): A function that is associated with an object.
Ex: def square ( num):
return num*num
print(square(4)) # Function call
#Method Example
Text=“Hello”
Print(text.upper()) # Method Call
Pass value by object reference :
In Python, arguments are passed by reference, meaning the function receives a reference to the original object. For Ex:
Def modify_list(list1):
list1.append(9)
My_list=[4,5,6,7]
Modify_list(My_list)
Print (“Modified List”, My_list) # OUTPUT [4,5,6,7,9]
Parameters and Arguments:
• Parameters are the names we put when we define a function. They act like empty slots inside the function, ready to
hold a value. Foe Example-
def healthy_fruit(fruit_name):
print(fruit_name, “ is very healthy”)
• Arguments are the actual fruit names (values) we pass when we call the function. For Ex-
healthy_fruit(“Apple”) # ‘Apple’ is the argument => OUTPUT: Apple is very healthy
Healthy_fruit(“Guava”) # ‘Guava is the argument => OUTPUT: Guava is very healthy
Recursive Functions:
In Python, a recursive function is a function that calls itself, one or more times in its body to solve a problem. It is returning
the return value of this function call. Python stops calling recursive function after 1000 calls by default. This technique is
particularly useful for problems that can be broken down into smaller, similar subproblems. Ex- 3!= 3*2*1
How recursive function works:
1.Recursive function is called by some external code.
2.If the base condition is met then the program does something meaningful and exits.
3.Otherwise, function does some required processing and then calls itself to continue recursion.
For example, 5! = 5 * 4 * 3 * 2 * 1 = 120. The base case for factorial is 0! = 1.
# Program to calculate factorial using recursive function. For Ex- 3!= 3*2*1 =6 . The base case for factorial is 0!=1
def fact(n):
if n==0:
return 1
else:
return n* fact(n-1)
print(fact(3))
OUTPUT: 6
How it works :
When fact(3) is called:
3*fact(2)
3* (2* fact(1))
3*(2* (1 *fact(0)))
3*(2*(1*1)) (Base case fact(0) returns 1
And Result will be 6.
Anonymous or Lambda Functions:
• A lambda function is a small, anonymous function meaning it has no name.
• While normal functions are defined using the def keyword in Python, anonymous functions are defined
using the lambda keyword.
• Therefore, anonymous functions are also called lambda functions.
Syntax : lambda arguments: expression
Example :
# Lambda to square a number
square = lambda x: x * x
print(square(5)) # Output: 25
A = lambda x, y : x + y
print(A(10, 4)) # Output: 14
Why to use Lambda Function?
• The power of lambda is better shown when you use them as an
anonymous function inside another function.
• Say you have a function definition that takes one argument, and
that argument will be multiplied with an unknown number:
def myfunc(n):
return lambda a : a * n
Example :
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
print(mydoubler(11))
Questions –
1.Write a Python program to create a lambda function that subtracts 25 to a
given number passed in as an argument.
2.Create a lambda function that multiplies argument p with argument q and print
the result.
Program 1:
s = lambda a : a - 25
print(s(40))
# Result : 15
Program 2:
m = lambda p, q : p * q
print(m(13, 5))
#Result: 65
Write a Python program to create a function that takes one
argument, and that argument will be multiplied with an unknown
given number.
def func_compute(n):
return lambda x : x * n
result = func_compute(2)
print("Double the number of 10 =", result(10))
result = func_compute(3)
print("Triple the number of 10 =", result(10))
# Result- 20
30
Modules in Python:
A module is a file containing Python definitions and statements. It allows code to be
organized, reused, and shared across multiple programs.
We can import a module into another Python program to use its code.
Why use modules?
• Avoid code repetition
• Organize code better
• Reuse functions and classes
• Collaborate in teams easily
Types of Modules
1.Built-in modules
•Already provided with Python
•Examples: math, random, os, datetime
2.User-defined modules
•Written by users to organize their own code
•Usually stored as .py files
3.External modules
Installed via pip
• Examples: numpy, pandas, matplotlib
• Made by others , you need to install them using pip
How to use Module
1. Import full module -> Brings in the Whole Module.
import math
print(math.sqrt(25))
2.Import with alias -> Gives the module a short nickname
import math as m
print(m.pi)
3.Import specific parts -> brings in only selected functions or variables
from math import sqrt, pi
print(sqrt(64),pi)
4. Import all -> Brings everything from the module into your program.
from math import *
print(sin(0))
Create a Calculator module. Use the module functionalities in another file –
main.py
# calculator.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def square(n):
return n * n
# main.py
import calculator
print("Addition:", calculator.add(10, 5)) # Output: 15
print("Subtraction:", calculator.subtract(10, 5)) # Output: 5
print("Square:", calculator.square(4)) # Output: 16
Dir() function- It is used to list the functions inside the built-in modules
import math
dir(math)
Random module is used for random number generations. Foe security purpose
when we use this module it generates random password.
import random
dir(random)
Time module
import time
dir(time)
time.time()
time.ctime()
Strings: Definition-
String is one of the most commonly used data types in Python and is used to store and
manipulate text. A string is a collection of characters.
Creating Strings: A string is a sequence of characters enclosed in single ('), double ("), or
triple quotes (''' or """).
name = "Python"
message = 'Hello, World!'
paragraph = '''This is a
multi-line string.’‘’
•Important-
•Strings are immutable (you can't change them directly)
•They support indexing, slicing, and many built-in functions
•Python treats text enclosed in quotes as a string
Functions of Strings:
.Python provides built-in string functions (methods) to manipulate and analyze strings
Function Description
len(s) Returns the length of string
s.upper() Converts to uppercase
s.lower() Converts to lowercase
s.capitalize() Capitalizes the first character
s.title() Capitalizes the first letter of each word
s.strip() Removes whitespace from both ends
s.replace(a, b) Replaces all occurrences of a with b
s.split() Split into list
s1.join(s2) Join list into string(s1 is string and s2 is a list)
Startwith(), endswith() Check start and end(Ex-print(“hello”.startswith(“he”)) -> OUTPUT : True
S1.count(s2) Count occurrences. Print(“banana”.count(”na”)) -> OUTPUT: 2
S1.find(s2) Find index of substring. Print(“banana”.find(“na”))-> OUTPUT: 2
s.strip() Remove whitespace . Print( “ hello “.strip()) -> OUTPUT: hello
Working with Strings: Strings are immutable, meaning you can’t change them directly, but
you can manipulate and assign new values.
Operation Description Example Output
Concatenation Joining two strings using + "Hello" + " World" 'Hello World'
Repetition Repeating a string using * "Hi " * 3 'Hi Hi Hi '
Accessing a character by
Indexing "Python"[0] 'P'
position
Slicing Extracting substring "Python"[1:4] 'yth'
Length Count characters using len() len("Hello") 5
Membership Test Check if substring exists "Py" in "Python" True
Compare strings
Comparison "apple" < "banana" True
lexicographically
Iteration Loop through each character for c in "Hi": print(c) Hi
upper() Convert to uppercase "hi".upper() 'HI'
lower() Convert to lowercase "HI".lower() 'hi'
strip() Remove spaces from both ends " hi ".strip() 'hi'
replace(a, b) Replace a substring "bat".replace("b", "c") 'cat'
split() Split into list by delimiter "a,b,c".split(",") ['a', 'b', 'c']
join() Join list into string " ".join(['a', 'b']) 'a b'
find() Find index of substring "hello".find("e") 1
Formatting Strings in Python
String formatting means inserting values into strings in a clean, readable,
and efficient way.
1. Using f-strings (Recommended – Python 3.6+)
2. Using .format() Method
3. Using % Operator (Older Style)
Example-
name = “Radha"
age = 40
print(f"My name is {name} and I am {age} years old.")
print("My name is {} and I am {} years old.".format(name, age))
print("My name is %s and I am %d years old." % (name, age))
OUTPUT-
My name is Radha and I am 23 years old.
My name is Radha and I am 23 years old.
My name is Radha and I am 23 years old.
Finding the Number of Characters and Words in Python-
• Count the Number of Characters(including spaces): Ex-
text = "Python is user friendly language“
Print(len(text))
#OUTPUT:32
• Count the Number of Words.
You can split the string into words using .split() and then use len() to count the
number of words. EX-
text = "Python is user friendly language“
words=text.split()
Print(len(words))
#OUTPUT:5
• Count specific characters or words. Ex-
print(text.count(‘e’)) #OUTPUT :3
Print(text.count(‘user’)) #OUTPUT :1
Inserting Substrings into a String in Python -
Python strings are immutable, which means we can’t directly insert into them like a
list. Instead, we create a new string using slicing and concatenation.
Example- Insert "really " into the string "I love Python" after "I ".
text= “I love Python”
new_text = text[:2] + "really " + text[2:]
print(new_text)
#OUTPUT: I really love Python
Practice Program-
text = "Python programming"
# Insert "is fun " after "Python "
new_text = text[:7] + "is fun " + text[7:]
print(new_text)
#OUTPUT: Python is fun programming