0% found this document useful (0 votes)
10 views23 pages

PPS Unit 3 Notes

Unit III covers the concepts of functions and strings in programming, emphasizing the need for functions to improve code readability, modularity, and reusability. It explains variable scope and lifetime, the return statement, and the importance of good programming practices, along with the introduction of modules, packages, and standard library modules. Additionally, it discusses string operations, including concatenation, appending, multiplication, and slicing, highlighting their significance in data processing.

Uploaded by

ko4510kk
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views23 pages

PPS Unit 3 Notes

Unit III covers the concepts of functions and strings in programming, emphasizing the need for functions to improve code readability, modularity, and reusability. It explains variable scope and lifetime, the return statement, and the importance of good programming practices, along with the introduction of modules, packages, and standard library modules. Additionally, it discusses string operations, including concatenation, appending, multiplication, and slicing, highlighting their significance in data processing.

Uploaded by

ko4510kk
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Programming and Problem Solving

Unit - 3 Notes
Unit III : Functions and Strings

❖ Need for Functions :-


🔹 Definition
Functions are used to divide a big program into small, manageable parts so that code becomes easy to
understand and reuse.
🔹 Importance :-
• Avoids repetition of code
• Makes program modular (divided into parts)
• Improves readability
• Easier debugging and maintenance
• Code can be reused multiple times
🔹 Explanation :-
Imagine writing the same code again and again. Instead of repeating it, we write it once inside
a function and call it whenever needed.
🔹 Example :-
def greet():
print("Hello Student!")
greet()
greet()
Output :-
Hello Student!
Hello Student!
👉 Here, the function is reused instead of writing print() again.

❖ 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.

🔹 Types of Scope :- 1. Local Variable Scope


2. Global Variable Scope

1. Local Scope :- Variable declared inside a function


Can be used only inside that function
Example :-
def test():
x = 10 # local variable
print("Inside function:", x)
test()
Output :- Inside function: 10
👉 x cannot be used outside the function.

2. Global Scope :- Variable declared outside the function


Can be used anywhere in the program
🔹 Importance :- Prevents data conflicts
Improves security and control of variables

Example :-
x = 20 # global variable
def test():
print("Inside function:", x)
test()
print("Outside function:", x)
Output :- Inside function: 20
Outside function: 20

❖ Variable Lifetime :- Lifetime means how long a variable exists in memory.


🔹 Types :- 1. Local Variable Lifetime
2. Global Variable Lifetime

1. Local Variable Lifetime :- Exists only while function is running


Destroyed after function ends
2. Global Variable Lifetime :- Exists throughout the program execution
🔹 Importance :- Helps in memory management
Avoids unnecessary memory usage
🔹 Example :-
def demo():
y = 50 # local variable
print("Inside function:", y)
demo()
# print(y) # This will give error
Output : Inside function: 50
👉 After function ends, y is deleted from memory.

Basis Variable Scope Variable Lifetime


Definition Scope defines where a variable can be Lifetime defines how long a variable exists
accessed in memory
Focus Accessibility of variable Duration of existence
Related To Area/region of program Time period during execution
Types Local, Global Local, Global
Control Determined by where variable is declared Determined by program execution
Example A local variable is used only inside a A local variable is destroyed after function
function execution
Error Case Accessing variable outside its scope → Using variable after it is destroyed → Error
Error
❖ Return Statement :-
The return statement is used to send a value from a function back to the place where it was called
✅ Importance :
• Allows a function to give output/result
• Makes functions useful and reusable
• Helps in storing result in variables
• Ends the function execution immediately
✅ Explanation :
When a function executes a return statement:
1. It stops execution of the function
2. It returns the value to the caller
3. The returned value can be stored or printed
👉 If no return is written, Python returns None by default

✅ 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.

✅ Example 2: Return with Parameters


def add(a, b):
return a + b
print(add(4, 6))
Output : 10

🔹 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.

❖ Lambda Function (Anonymous Function) :-


A lambda function is a small, anonymous (nameless) function defined using the lambda keyword.

✅ 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

Basis Normal Function Lambda Function


Definition Defined using def keyword Defined using lambda keyword
Name Has a function name Anonymous (no name)
Complexity Can handle complex logic Only simple expressions
Statements Multiple statements allowed Only one expression
Return Uses return keyword Returns automatically
Usage General purpose Short, quick operations

❖ Documentation String (Docstring) :-


A documentation string (docstring) is a string written inside a function, class, or module to explain
what it does.

✅ 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.

❖ Good Programming Practices :-


Good programming practices are rules and techniques used to write clean, efficient, and
understandable code.

✅ Importance :-
• Makes code easy to read and understand
• Helps in debugging and maintenance
• Reduces errors and confusion
• Improves code quality

1. Meaningful Variable Names :-


Use clear names instead of short or confusing ones.
# Bad
x = 10
# Good
marks = 10

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

4. Avoid Code Repetition


Use functions instead of writing same code again.

5. Keep Functions Small


Each function should do one specific task.

6. Follow Naming Conventions


• Functions → lowercase (add_numbers)
• Variables → meaningful names

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

✅ Example with Output


File: [Link]
def add(a, b):
return a + b

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

❖ Introduction to Standard Library Modules :-


Standard library modules are pre-built modules provided by Python, which we can use directly
without installing.
✅ Importance :-
• Saves time and effort
• No need to write code from scratch
• Provides ready-made functions
✅ Explanation :-
Python already gives many modules like:
math → calculations
random → random numbers
datetime → date and time

✅ Examples :-
Example 1: math module
import math
print([Link](25))
Output : 5

Example 2: random module


import random
print([Link](1, 5))
Output : 3

Example 3: datetime module


import datetime
print([Link]())
Output (example) : 2026-04-15 16:00:00

🔹 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

Operation Symbol Purpose Example Output


Concatenation + Join strings Hello World
Appending + Add at end Hello Students
Multiplication * Repeat string Hi Hi Hi
Slicing [] Extract part of string Pyt

❖ Slice Operation in Strings :-


o Slicing means extracting a part (substring) of a string using index positions.
o Taking a piece of a string
🔸 Syntax :-
string[start : end : step]
• start → starting index (included)
• end → ending index (excluded)
• step → jump value (optional)

🔸 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

4. Negative Index Slicing


👉 Negative index starts from end
String: P y t h o n
Index: -6 -5 -4 -3 -2 -1

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

Type Example Output


Normal slicing text[1:4] yth
From start text[:4] Pyth
Till end text[2:] thon
Negative slicing text[-3:] hon
Step slicing text[::2] Pto
Reverse text[::-1] nohtyP

❖ Strings are Immutable :-

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

📌 Example 1: Trying to Change a String


str1 = "hello"
str1[0] = "H" # ❌ Error
❗ Output: TypeError: 'str' object does not support item assignment
👉 Because strings cannot be modified directly

📌 Example 2: Correct Way (Create New String)


str1 = "hello"
str2 = "H" + str1[1:]
print(str2)
✅ Output : Hello
👉 Here, a new string is created, original remains unchanged

✔ Strings cannot be changed after creation


✔ Any operation creates a new string

❖ String Formatting Operator :-


f-string is used to insert variables or values inside a string using {} brackets by writing f before the
string.

✅ 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")

✅ Output:- My name is Vrushali and I am 20 years old

❖ Built-in String Methods and Functions :-


Built-in string methods and functions are predefined operations in Python that help us manipulate
and work with strings easily without writing extra code.

✓ 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.

✓ Common String Methods with Example :-

1. lower() :- Converts string into lowercase


Example:
s = "HELLO"
print([Link]())
Output: hello

2. upper() :- Converts string into uppercase


Example:
s = "hello"
print([Link]())
Output: HELLO

3. strip() :- Removes spaces from beginning and end


Example:
s = " hello "
print([Link]())
Output: hello

4. replace() :-Replaces one string with another


Example:
s = "I like Java"
print([Link]("Java", "Python"))
Output: I like Python

5. split() :-Splits string into list


Example:
s = "apple banana mango"
print([Link]())
Output: ['apple', 'banana', 'mango']
6. find() :- Finds position of substring
Example:
s = "hello"
print([Link]("e"))
Output: 1

7. count() :- Counts occurrences


Example:
s = "banana"
print([Link]("a"))
Output: 3

❖ Built-in String Functions :-

1. len() :- Returns length of string


Example:
s = "hello"
print(len(s))
Output: 5

2. max() :- Returns highest character (ASCII value)


Example:
print(max("abc"))
Output: c

3. min() :- Returns smallest character


Example:
print(min("abc"))
Output : a

❖ 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 and not in Operators :-


in → checks if a value exists in a sequence
not in → checks if a value does NOT exist
✅ Importance :-
• Used for searching in strings, lists, tuples
• Makes conditions simple and readable

🔸 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

🔹 Difference between in and not in :

Point in Operator not in Operator


Definition Checks whether an element is Checks whether an element is NOT
present in a sequence present in a sequence
Result Returns True if element is found Returns True if element is not found
Condition Type Positive condition Negative condition
Usage Used to search elements in Used to ensure absence of elements
strings, lists, tuples
Example 'a' in "apple" → True 'z' not in "apple" → True
Opposite Relation Opposite of not in Opposite of in

❖ 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

👉 Comparison is done based on ASCII values (dictionary order):


Uppercase letters have different values than lowercase
Comparison happens character by character
✓ Example :
a = "apple"
b = "banana"
print(a == b)
print(a != b)
print(a < b)
print(a > b)
Output :
False
True
True
False

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

1. Using for loop


Example :
name = "Python"
for ch in name:
print(ch)
Output :
P
y
t
h
o
n

Explanation :-
for ch in name → takes each character one by one
Prints each character in a new line

2. Using while loop


Example :
name = "Python"
i=0
while i < len(name):
print(name[i])
i=i+1
Output :
P
y
t
h
o
n
Explanation :
len(name) gives length of string
Index starts from 0
Loop runs until last character

❖ 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 :-

Constant Description Example Output


string.ascii_lowercase all small letters abcdefghijklmnopqrstuvwxyz
string.ascii_uppercase all capital letters ABCDEFGHIJKLMNOPQRSTUVWXYZ
string.ascii_letters both upper + lower abc...XYZ
[Link] numbers 0–9 0123456789
[Link] special characters !"#$%&'()*+,-./:;<=>?@[]^_`{ }~
[Link] space, tab, newline (invisible characters)

✓ Example :-
import string
print(string.ascii_lowercase)
print(string.ascii_uppercase)
print([Link])

Output : abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ
0123456789

You might also like