PPS Unit 3 Notes
PPS Unit 3 Notes
Unit - 3 Notes
Unit III : Functions and Strings
❖ Function :- A function is a block of code that performs a specific task and runs only when it is called.
🔹 Importance :-
• Breaks large problems into small tasks
• Helps in code reuse
• Makes logic clear and structured
🔹 Explanation :- We define a function using def keyword. It contains code and executes only when called.
🔹 Example :-
def add():
a=5
b=3
print("Sum =", a + b)
add()
Output :- Sum = 8
❖ Function Call :-
Function call means executing the function by writing its name followed by parentheses ().
🔹 Importance :-
• Executes the function when needed
• Allows multiple execution without rewriting code
🔹 Explanation : When we call a function, control goes to the function body, executes it, and comes back.
🔹 Example :
def message():
print("Welcome!")
message() # Function call
Output: Welcome!
❖ Variable Scope :- Scope means the area where a variable can be accessed.
Example :-
x = 20 # global variable
def test():
print("Inside function:", x)
test()
print("Outside function:", x)
Output :- Inside function: 20
Outside function: 20
✅ Syntax :-
def function_name():
return value
✅ Example 1 :-
def add():
return 5 + 3
result = add()
print(result)
Output :- 8
👉 The function returns 8, which is stored in result.
🔹 Key Points :
• return sends value back to caller
• It terminates function execution
• Can return single or multiple values
• If not used → function returns None
👉 The return statement is used to exit a function and send a value back to the calling program.
❖ Functions :-
Defining a function means creating a function using the def keyword so that it can perform a specific
task when called.
✅ Importance :-
• Helps in code reuse
• Makes program modular and organized
• Reduces code repetition
• Improves readability
✅ Explanation :-
A function is defined using def followed by:
• Function name
• Parentheses () (can contain parameters)
• Colon :
• Function body (code inside function)
✅ Syntax :-
def function_name(parameters):
# body of function
✅ Example :-
def greet(name):
print("Hello", name)
greet("OM")
Output : Hello OM
👉 Here, the function is defined and then called with an argument.
✅ Importance :-
• Used for short and simple operations
• No need to write full function using def
• Saves time and code length
• Often used with functions like map(), filter(), etc.
✅ Explanation :-
• Lambda functions have no name
• They contain only one expression
• Automatically return the result (no return keyword needed)
✅ Syntax :- lambda arguments: expression
✅ Example :
add = lambda a, b: a + b
print(add(3, 4))
Output : 7
✅ Importance :-
• Helps others understand the code easily
• Used for documentation and help() function
• Improves code readability
• Useful for teaching and debugging
✅ Explanation :-
• Written using triple quotes (''' ''' or """ """)
• Placed just below the function definition
• Describes:
o Purpose of function
o Parameters
o Return values
✅ Example :-
def add(a, b):
"""This function returns the sum of two numbers"""
return a + b
print(add(3, 5))
print(add.__doc__)
Output :
8
This function returns the sum of two numbers
👉 __doc__ is used to access the docstring.
✅ Importance :-
• Makes code easy to read and understand
• Helps in debugging and maintenance
• Reduces errors and confusion
• Improves code quality
2. Proper Indentation
Python uses indentation to define blocks of code.
def test():
print("Correct Indentation")
3. Use Comments
Explain complex logic using comments.
# This function adds two numbers
def add(a, b):
return a + b
7. Error Handling
Handle errors using try-except.
try:
x = int("abc")
except:
print("Error occurred")
❖ Introduction to Modules :-
A module is a single Python file that contains functions, variables, or classes, which can be reused in
another program.
✅ Importance :-
• Avoids repeating code
• Makes program organized
• Easy to maintain and debug
• Promotes code reuse
✅ Explanation :-
Instead of writing all code in one file, we create separate files (modules) for different tasks and use
them with import.
✅ Real-Life Example :-
👉 Think of a calculator app
One file for addition
One file for subtraction
Each file = module
Main Program
import mymodule
print([Link](2, 3))
Output :- 5
❖ Introduction to Packages in Python :-
A package is a folder (directory) that contains multiple modules.
✅ Importance :-
• Organizes large projects
• Groups related modules together
• Makes project clean and structured
✅ Explanation :- When project becomes big, we group related modules into a folder called a package.
✅ Real-Life Example :-
👉 Think of a college library
Different sections: Science, Math, Computer
Each section has many books
👉 Library = Package
👉 Books = Modules
✅ Example :-
Folder Structure:
mathpackage/
[Link]
[Link]
[Link]
def add(a, b):
return a + b
Main Program
from mathpackage import add
print([Link](4, 6))
Output :- 10
✅ Examples :-
Example 1: math module
import math
print([Link](25))
Output : 5
🔹 Short Definitions :-
👉 Module: A file containing reusable Python code.
👉 Package: A collection of modules stored in a folder.
👉 Standard Library: Predefined modules provided by Python.
❖ String :- A string is a sequence of characters written inside quotes (' ' or " ").
🔹 Importance of Strings :-
Strings are very important because:
• Used to store text data (name, address, messages)
• Used in user input/output
• Used in file handling
• Used in data processing (like searching, formatting)
👉 Real-life example:
• WhatsApp message → String
• Student name in database → String
• Email content → String
🔹 String Operations
1. Concatenation (Joining Strings) :- Concatenation means joining two or more strings using + operator.
🔸 Importance:
• Helps combine multiple text values
• Useful in displaying messages
Example :
a = "Hello"
b = "World"
c=a+""+b
print(c)
Output : Hello World
2. Appending (Adding to String) :- Appending means adding new content at the end of a string.
⚠️ Note: Strings are immutable → we create a new string
🔸 Importance:
• Used to update messages
• Useful in loops and data building
🔸 Example:
text = "Hello"
text = text + " Students"
print(text)
🔸 Output : Hello Students
👉 Real-life example:
• Adding new line in chat message
• Building sentence step by step
3. Multiplication (Repeating String) :- Multiplication means repeating a string multiple times using * operator.
🔸 Importance:
• Useful for patterns
• Helpful in formatting output
🔸 Example:
a = "Hi "
print(a * 3)
Output : Hi Hi Hi
4. Slicing (Extracting Part of String) :- Slicing means getting a part (substring) of a string using index.
🔸 Syntax :
string[start : end]
👉 start = included
👉 end = excluded
🔸 Importance:
• Used to extract specific data
• Useful in data processing and analysis
🔸 Example 1:
text = "Python"
print(text[0:3])
print(text[2:5])
🔸 Output:
Pyt
tho
🔸 Example 2:
text = "Engineering"
print(text[:4]) # from start
print(text[5:]) # till end
print(text[-3:]) # from end
🔸 Output:
Engi
eering
ing
🔸 Example 3:
String: P y t h o n
Index: 0 1 2 3 4 5
Slice: text[1:4]
Result → y t h
🔸 Importance :-
Slicing is important because:
• Helps to extract required data
• Used in data processing
• Useful in password masking, name formatting
• Helps in reversing strings
👉 Real-life example:
• Extract first name from full name
• Get last 4 digits of phone number
• Read specific part of file data
🔸 Example :-
text = "Python"
print(text[0:3])
Output : Pyt
👉 Explanation:
Index 0 to 2 (3 is excluded)
🔸 Index Understanding :-
String: P y t h o n
Index: 0 1 2 3 4 5
1. Normal Slicing
text = "Python"
print(text[1:4])
Output : yth
2. From Start
print(text[:4])
Output: Pyth
3. Till End
print(text[2:])
Output: thon
print(text[-3:])
Output: hon
5. Step Slicing
text = "Python"
print(text[0:6:2])
Output: Pto
👉 Explanation: jump 2 steps
6. Reverse String
text = "Python"
print(text[::-1])
Output: nohtyP
A string is immutable means once a string is created, its value cannot be changed.
When you create a string, Python stores it in memory.
After that, you cannot modify individual characters of that string.
👉 Instead of changing the original string, Python creates a new string.
🎯 Why is it Important?
Makes strings safe and secure (no accidental changes)
Helps in better memory management
Improves program reliability
✅ Importance :
• Easy and simple to use
• Improves readability
• Modern method in Python
• Used to display formatted output
✅ Example :
name = "Vrushali"
age = 20
print(f"My name is {name} and I am {age} years old")
✓ Importance :-
• Makes string handling easy and fast
• Saves time and effort
• Improves code readability
• Useful in real-world applications like data processing, form validation, etc.
❖ ord() Function :- ord() function is used to get the ASCII (Unicode) value of a character.
✅ Importance :-
• Helps to convert character into numeric value
• Useful in string comparison and encoding
• Used in encryption and validation logic
✅ Syntax : ord(character)
✅ Example :-
print(ord('A'))
print(ord('a'))
✅ Output : 65
97
✅ Explanation :
'A' → ASCII value is 65
'a' → ASCII value is 97
❖ chr() Function :-
chr() function is used to convert an ASCII (Unicode) value into its corresponding character.
✅ Importance :
• Converts numbers into characters
• Used in decoding, pattern generation
• Helpful in looping alphabets
✅ Syntax :- chr(number)
✅ Example :-
print(chr(65))
print(chr(97))
✅ Output :- A
A
✅ Explanation :
65 → 'A'
97 → 'a'
Point ord() Function chr() Function
Definition Converts a character into its Converts ASCII/Unicode value into
ASCII/Unicode value character
Input Type Takes a single character as input Takes an integer (ASCII value) as input
Output Type Returns an integer value Returns a character
Purpose Used for encoding or getting Used for decoding or getting
numeric value of character character from number
Usage Area String comparison, validation, Pattern printing, character generation
encryption
Example ord('A') = 65 chr(65) = 'A'
🔸 in Operator :-
✅ Example :
text = "apple"
print('a' in text)
print('z' in text)
✅ Output :
True
False
✅ Explanation :
'a' is present → True
'z' is not present → False
🔸 not in Operator :-
✅ Example :
text = "apple"
print('z' not in text)
print('a' not in text)
✅ Output : True
False
✅ Explanation :
'z' is not present → True
'a' is present → False
❖ comparing strings :-
String comparison means checking whether two strings are equal or determining their order using
comparison operators.
✓ Importance :
• Helps in decision making (like login systems)
• Used in searching and sorting data
• Useful in validation (checking user input)
✓ Explanation :
In Python, strings are compared using:
== → Equal
!= → Not equal
> → Greater than
< → Less than
>= → Greater than or equal
<= → Less than or equal
Explanation of Example :-
"apple" == "banana" → False (both are different)
"apple" < "banana" → True
👉 because 'a' comes before 'b' in ASCII
❖ Iterating Strings :-
Iterating a string means accessing each character of the string one by one using loops.
Importance :-
• Helps to process each character individually
• Used in searching, counting, and modifying strings
• Useful in real-life tasks like password checking, text analysis, etc.
Explanation :-
A string is a sequence of characters, so we can traverse (loop through) it using:
for loop (most common)
while loop
Explanation :-
for ch in name → takes each character one by one
Prints each character in a new line
❖ String Module :-
The string module in Python is a built-in module that provides useful constants and functions for
working with strings.
👉 It contains predefined values like alphabets, digits, punctuation, etc.
✓ Importance :
• Saves time (no need to manually write alphabets or digits)
• Makes code clean and readable
• Useful in validation, password checking, text processing
• Helps beginners understand string handling easily
✓ How to Use :
First, you need to import the module:
Python
import string
👉 import means you are bringing the module into your program so you can use it.
✓ Important Constants in string module :-
✓ Example :-
import string
print(string.ascii_lowercase)
print(string.ascii_uppercase)
print([Link])
Output : abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ
0123456789