0% found this document useful (0 votes)
6 views25 pages

Unit - Iii

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)
6 views25 pages

Unit - Iii

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
You are on page 1/ 25

UNIT – III

Functions: Function Definition – Function Call – Variable Scope and its Lifetime-
Return Statement. Function Arguments: Required Arguments, Keyword Arguments,
Default Arguments and Variable Length ArgumentsRecursion. Python Strings: String
operations- Immutable Strings - Built-in String Methods and Functions - String
Comparison. Modules: import statementThe Python module – dir() function –
Modules and Namespace – Defining our own modules.

Introduction to Functions

▪ Definition: A function is a block of reusable code that performs a specific task.


▪ Purpose: Helps in breaking the program into smaller and modular chunks.

Basic Syntax

To define a function in Python, you use the def keyword followed by the function
name, parentheses, and a colon. The body of the function is indented.

def function_name(parameters):

"""Docstring explaining the function."""

# Function body

# Code to be executed

return result

Components of a Function

1. Function Name: Should be descriptive of the task it performs.


2. Parameters: Variables that the function can accept as input. These are
optional.
3. Docstring: A string literal that explains what the function does. This is also
optional but recommended.
4. Function Body: The code block that contains the logic of the function.
5. Return Statement: Used to return a value from the function. This is optional.
Types of Functions
▪ Built-in Functions: Functions that are pre-defined in Python (e.g., print(),
len(), type())
▪ User-defined Functions: Functions created by the user to perform specific
tasks.
Creating a Function
▪ Defining a Function:
def greet(name):
"""This function greets the person passed in as a parameter"""
print(f"Hello, {name}!")
▪ Calling a Function:
greet("Alice")
Variable Scope in Python
In Python, the scope of a variable refers to the context within which a variable is
defined and can be accessed. Python uses a system called LEGB, which stands for
Local, Enclosing, Global, and Built-in scopes. Understanding these scopes is crucial
for writing clear and bug-free code.
LEGB Rule
1. Local Scope (L)
2. Enclosing Scope (E)
3. Global Scope (G)
4. Built-in Scope (B)
Local Scope
▪ Definition: Variables defined inside a function.
▪ Access: Only within the function where they are defined.
▪ Lifetime: Exists only during the execution of the function.
def my_function():
x = 10 # Local variable
print(x)
my_function()
Output: 10
# print(x) # Error: NameError: name 'x' is not defined
Enclosing Scope
▪ Definition: Variables in the local scope of enclosing functions, particularly in
nested functions.
▪ Access: Inner functions can access variables from their enclosing functions.
▪ Lifetime: Exists as long as the enclosing function exists.
def outer_function():
x = 20 # Enclosing variable
def inner_function():
print(x) # Accessing enclosing variable
inner_function()
outer_function()
Output: 20
Global Scope
▪ Definition: Variables defined at the top-level of a module or script, or explicitly
declared as global using the global keyword.
▪ Access: Anywhere in the module after their definition.
▪ Lifetime: Exists as long as the program runs.
x = 30 # Global variable

def my_function():
print(x) # Accessing global variable

my_function() # Output: 30
print(x)
Output: 30

Built-in Scope

▪ Definition: Contains built-in functions and names that are always available in
Python.
▪ Access: Anywhere in the code.

print(len([1, 2, 3])) # Output: 3


Variable Destruction and Garbage Collection
▪ Automatic Memory Management: Python uses an automatic memory
management system.
▪ Garbage Collection:
o Unused objects (those no longer referenced) are automatically
destroyed.
o Python’s garbage collector helps in reclaiming the memory.
o Can be manually invoked using gc.collect().
▪ Example:
import gc

def create_variable():
x = [1, 2, 3] # Local variable, will be garbage collected after function exits
print(x)
create_variable()
gc.collect() # Manually invoking garbage collection
Static and Dynamic Lifetime
▪ Static Lifetime:
o Variables with a static lifetime exist for the duration of the program.
o Examples: Global variables, constants.
▪ Dynamic Lifetime:
o Variables with a dynamic lifetime exist only during specific periods of
execution.
o Examples: Local variables, temporary objects.
Lifetime in Context of Classes and Objects
▪ Instance Variables:
o Variables defined inside a class constructor (__init__ method).
o Lifetime: Exist as long as the instance (object) exists.
• Class Variables:
o Variables defined inside a class but outside any method.
o Lifetime: Exist as long as the class is in memory.
• Example:
class MyClass:
class_variable = "I am a class variable" # Class variable

def __init__(self, value):


self.instance_variable = value # Instance variable

obj1 = MyClass("I am instance variable of obj1")


obj2 = MyClass("I am instance variable of obj2")

print(MyClass.class_variable) # Accessible via class


print(obj1.instance_variable) # Accessible via instance
print(obj2.instance_variable) # Accessible via instance
Example 1: Simple Function Without Parameters
def greet():
"""Prints a greeting message."""
print("Hello, World!")

# Calling the function


greet()
OUTPUT
Hello, World!
Example 2: Function With Parameters
def greet(name):
"""Prints a greeting message to the person with the given name."""
print(f"Hello, {name}!")

# Calling the function


greet("SKS")
OUTPUT
Hello, SKS!
Example 3: Function With a Return Value
def add(a, b):
"""Returns the sum of two numbers."""
return a + b

# Calling the function and using the return value


result = add(3, 5)
print(result)
OUTPUT
8
Example 4: Function With Default Parameters
def greet(name="World"):
"""Prints a greeting message. Defaults to 'World' if no name is provided."""
print(f"Hello, {name}!")

# Calling the function with and without arguments


greet() # Output: Hello, World!
greet("SKS") # Output: Hello, SKS!
OUTPUT
Hello, World!
Hello, SKS!
Example 5: Function With Variable Number of Arguments
def greet(*names):
"""Prints a greeting message to multiple people."""
for name in names:
print(f"Hello, {name}!")

# Calling the function with multiple arguments


greet("SKS", "CS", "BCA")
OUTPUT
Hello, SKS!
Hello, CS!
Hello, BCA!
Example 6: Keyword Arguments
def greet(**kwargs):
"""Prints a greeting message using keyword arguments."""
for key, value in kwargs.items():
print(f"{key}: {value}")
# Calling the function with keyword arguments
greet(name="SKS", age=40, location="TIRUPATTUR")
OUTPUT
name: SKS

age: 40

location: TIRUPATTUR

Return Statement in Python


▪ Definition: The return statement is used to exit a function and optionally pass
an expression back to the caller.
▪ Purpose: To return a result from a function to the calling code.
Syntax:
def function_name(parameters):
# code
return expression
Example:
def add(a, b):
return a + b

result = add(5, 3)
print(result)
Output: 8
Returning Multiple Values
▪ Tuple Packing and Unpacking:
o Python allows functions to return multiple values as a tuple.
o These values can be unpacked into separate variables.
• Example:
def get_name_and_age():
name = "SKS"
age = 40
return name, age

name, age = get_name_and_age()


print(name)
print(age)
Output:
SKS
40
Returning Nothing
▪ Implicit Return Value:
o If no return statement is used, the function returns None by default.
▪ Explicit Return of None:
o You can explicitly return None using return without an expression.
▪ Example:
def no_return():
print("This function does not return anything.")

result = no_return()
print(result)
Output: None
Function Arguments
Introduction
▪ Function Arguments: Values passed to a function when it is called.
▪ Parameters: Variables listed in the function definition.
Required Arguments
▪ Definition: Arguments that must be provided to the function in the correct
positional order.
▪ Usage: Used when a function needs specific values to operate.
Example:
def add(a, b):
return a + b

result = add(3, 5)
print(result)
Output: 8
# add(3) # This will raise an error because the second argument is missing
Keyword Arguments
▪ Definition: Arguments passed to a function by explicitly specifying the
parameter names.
▪ Usage: Improves readability and allows changing the order of arguments.
Example:
def greet(name, message):
print(f"Hello, {name}! {message}")

greet(name="Alice", message="Good morning!")


greet(message="How are you?", name="Bob")
Default Arguments
▪ Definition: Parameters that assume a default value if no argument is provided.
▪ Usage: Useful for providing default behavior while still allowing flexibility.
Example:
def greet(name, message="Hello!"):
print(f"Hello, {name}! {message}")

greet("Alice") # Output: Hello, Alice! Hello!


greet("Bob", "Good morning!") # Output: Hello, Bob! Good morning!
Variable-Length Arguments
• Definition: Functions that accept an arbitrary number of arguments.
• Types:
o Arbitrary Positional Arguments: Use *args to pass a variable number
of positional arguments.
o Arbitrary Keyword Arguments: Use **kwargs to pass a variable
number of keyword arguments.
a. Arbitrary Positional Arguments (*args)
• Usage: Allows a function to accept any number of positional arguments.
Example:
def sum_all(*args):
return sum(args)

print(sum_all(1, 2, 3)) # Output: 6


print(sum_all(4, 5, 6, 7, 8))
Output: 30
b. Arbitrary Keyword Arguments (**kwargs)
▪ Usage: Allows a function to accept any number of keyword arguments.
Example:
def print_details(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")

print_details(name="SKS", age=30, city="New York")


Output:
name: SKS
age: 30
city: New York
Combining Different Types of Arguments
▪ Order: The order of parameters should be:
1. Required arguments
2. Default arguments
3. *args
4. **kwargs
• Example:
def mixed_function(a, b=2, *args, **kwargs):
print(f"a: {a}")
print(f"b: {b}")
print(f"args: {args}")
print(f"kwargs: {kwargs}")

mixed_function(1, 3, 4, 5, name="Alice", age=30)


Output:
a: 1
b: 3
args: (4, 5)
kwargs: {'name': 'Alice', 'age': 30}
Recursion
Introduction to Recursion
▪ Definition: Recursion is a programming technique where a function calls itself
to solve smaller instances of the same problem.
▪ Use Cases: Often used for problems that can be divided into similar
subproblems (e.g., factorial, Fibonacci series, tree traversal).
Key Components of a Recursive Function
▪ Base Case: The condition under which the function stops calling itself. This
prevents infinite recursion.
▪ Recursive Case: The part of the function where it calls itself with modified
arguments.
Basic Structure of a Recursive Function
Syntax:
def recursive_function(parameters):
if base_case_condition:
return base_case_value
else:
return recursive_function(modified_parameters)
Advantages of Recursion
▪ Simplicity: Often leads to simpler and more readable code, especially for
problems that have a natural recursive structure.
▪ Suitability: Ideal for problems that can be broken down into similar
subproblems.
Drawbacks of Recursion
▪ Performance: Recursive calls can be expensive in terms of memory and time
due to function call overhead.
▪ Depth Limit: Python has a recursion depth limit (default is 1000), which can
lead to a RecursionError for deep recursion.
Program using Recursion.
def factorial(n):
if n==0:
return 1
else:
return n*factorial(n-1)

num = int(input("Enter a number: "))


print("The factorial of a {0} is: ".format(num), factorial(num))
Output:
Enter a number: 5
The factorial of a 5 is: 120
Python Strings
Definition: A string in Python is a sequence of characters enclosed in single
quotes (' ') or double quotes (" ").
Examples:
string1 = 'Hello, World!'
string2 = "Python is fun!"
Creating Strings
Single Quotes:
string1 = 'Hello'
Double Quotes:
string2 = "World"
Triple Quotes: For multi-line strings.
string3 = '''This is a
multi-line string.'''
or
string4 = """This is also a
multi-line string."""
Basic String Operations
▪ Concatenation: Combining strings using the + operator.
str1 = "Hello"
str2 = "World"
result = str1 + " " + str2
OUTPUT: "Hello World"
▪ Repetition: Repeating strings using the * operator.
str1 = "Hello"
result = str1 * 3
OUTPUT: "HelloHelloHello"
▪ Length: Finding the number of characters in a string using len().
str1 = "Hello"
length = len(str1)
OUTPUT: 5
Indexing and Slicing
▪ Indexing: Accessing individual characters using their position.
str1 = "Hello"
first_char = str1[0] OUTPUT: 'H'
last_char = str1[-1] OUTPUT: 'o'
▪ Slicing: Extracting a substring using the [start:stop:step] syntax.
str1 = "Hello, World!"
substr1 = str1[0:5] # 'Hello'
substr2 = str1[7:] # 'World!'
substr3 = str1[::2]
OUTPUT: 'Hlo ol!'
String Methods
▪ Changing Case:
str1 = "Hello"
upper_str = str1.upper() # 'HELLO'
lower_str = str1.lower() # 'hello'
title_str = str1.title()
OUTPUT: 'Hello'
▪ Stripping Whitespace:
str1 = " Hello "
stripped_str = str1.strip() OUTPUT: 'Hello'
lstripped_str = str1.lstrip() OUTPUT: 'Hello '
rstripped_str = str1.rstrip() OUTPUT: ' Hello'
▪ Replacing Substrings:
str1 = "Hello, World!"
replaced_str = str1.replace("World", "Python")
OUTPUT: 'Hello, Python!'
▪ Splitting and Joining:
str1 = "Hello, World!"
split_str = str1.split(",")
OUTPUT: ['Hello', ' World!']
list1 = ['Hello', 'World']
joined_str = " ".join(list1)
OUTPUT: 'Hello World'
String Search Methods
▪ Finding Substrings:
str1 = "Hello, World!"
index = str1.find("World")
OUTPUT: 7
rindex = str1.rfind("l")
OUTPUT: 10
▪ Checking Start and End:
str1 = "Hello, World!"
starts = str1.startswith("Hello") OUTPUT: True
ends = str1.endswith("World!") OUTPUT: True
String Formatting
▪ Old Style (%):
name = "John"
age = 30
formatted_str = "My name is %s and I am %d years old." % (name, age)
▪ str.format():
name = "John"
age = 30
formatted_str = "My name is {} and I am {} years old.".format(name, age)
▪ f-Strings (Python 3.6+):
name = "John"
age = 30
formatted_str = f"My name is {name} and I am {age} years old."
Escape Characters
▪ Common Escape Characters:
newline = "Hello\nWorld" # Newline
tab = "Hello\tWorld" # Tab
backslash = "Hello\\World" # Backslash
single_quote = 'It\'s a test' # Single quote
double_quote = "He said \"Hello\"" # Double quote
Raw Strings
▪ Usage: Useful for regular expressions and file paths.
raw_str = r"C:\Users\Name" # 'C:\\Users\\Name'
Unicode Strings
▪ Handling Unicode:
unicode_str = "你好, 世界" # 'Hello, World' in Chinese
String Check Methods
▪ isalpha(), isdigit(), isalnum(), isspace():
str1 = "Hello"
is_alpha = str1.isalpha() # True

str2 = "12345"
is_digit = str2.isdigit() # True

str3 = "Hello123"
is_alnum = str3.isalnum() # True

str4 = " "


is_space = str4.isspace() # True
Best Practices
▪ Use join() for Efficient Concatenation:
words = ["Efficient", "string", "concatenation"]
result = " ".join(words) # 'Efficient string concatenation'
▪ Avoid Repeated String Concatenation in Loops:
# Inefficient
result = ""
for word in words:
result += word # Creates a new string each time

# Efficient
result = "".join(words)
Example: String Operations
▪ Basic Example:
str1 = "Hello, World!"
print(str1.upper()) # 'HELLO, WORLD!'
print(str1.lower()) # 'hello, world!'
print(str1.replace("World", "Python")) # 'Hello, Python!'
print(str1.split(",")) # ['Hello', ' World!']
print(" ".join(["Hello", "Python"])) # 'Hello Python'
Immutable Strings
▪ Definition: Immutability means that once a string is created, it cannot be
changed. Any operation that appears to modify a string will actually create a
new string.
▪ Example:
str1 = "Hello"
# Attempting to change a character will result in an error
# str1[0] = 'J' # Raises TypeError: 'str' object does not support item
assignment
Implications of Immutability
▪ Memory Efficiency: Reusing the same string object reduces memory usage.
▪ Thread Safety: Immutable objects are inherently thread-safe since they cannot
be modified after creation.
Creating New Strings from Existing Ones
▪ Concatenation: Results in a new string.
str1 = "Hello"
str2 = str1 + " World" # New string "Hello World"
▪ Replacement: Results in a new string.
str1 = "Hello"
str2 = str1.replace("H", "J") # New string "Jello"
Common Operations Creating New Strings
▪ Slicing:
str1 = "Hello"
substr1 = str1[:2] # New string "He"
▪ Case Conversion:
str1 = "Hello"
upper_str = str1.upper() # New string "HELLO"
lower_str = str1.lower() # New string "hello"
▪ Trimming Whitespace:
str1 = " Hello "
stripped_str = str1.strip() # New string "Hello"
In-Place Modifications (Not Allowed)
▪ Since strings are immutable, there are no in-place modification methods. Any
"modification" results in the creation of a new string.
str1 = "Hello"
# Attempting in-place modification
# str1[0] = 'J' # Raises TypeError: 'str' object does not support item
assignment
Performance Considerations
▪ Efficient Concatenation: Use the join() method for concatenating multiple
strings to avoid performance issues.
words = ["Efficient", "string", "concatenation"]
result = " ".join(words) # New string "Efficient string concatenation"
▪ Avoiding Repeated Concatenation: Repeated concatenation in loops is
inefficient due to the creation of multiple intermediate strings.
# Inefficient
result = ""
for word in words:
result += word # Each concatenation creates a new string

# Efficient
result = "".join(words)
Copy-on-Write Optimization
▪ Python optimizes memory usage by using the same memory location for
identical immutable objects, a concept known as interning.
str1 = "Hello"
str2 = "Hello"
is_same_object = str1 is str2 # True, both refer to the same memory
location
Immutability and Data Structures
▪ Tuple Containing Strings: Tuples are immutable, and thus, any string within a
tuple remains immutable.
tup = ("Hello", "World")
# tup[0] = "Hi" # Raises TypeError: 'tuple' object does not support item
assignment
Built-in String Methods and Functions

Python has a set of built-in methods that you can use on strings

Python includes the following built-in methods to manipulate strings −

Sr.No Function & Description

capitalize()
1
Capitalizes first letter of string

center(width, fillchar)
2 Returns a space-padded string with the original string centered to a
total of width columns.

count(str, beg= 0,end=len(string))


3 Counts how many times str occurs in string or in a substring of string
if starting index beg and ending index end are given.

decode(encoding='UTF-8',errors='strict')
4 Decodes the string using the codec registered for encoding.
encoding defaults to the default string encoding.

encode(encoding='UTF-8',errors='strict')
5 Returns encoded string version of string; on error, default is to raise
a ValueError unless errors is given with 'ignore' or 'replace'.

endswith(suffix, beg=0, end=len(string))


Determines if string or a substring of string (if starting index beg and
6
ending index end are given) ends with suffix; returns true if so and
false otherwise.
Sr.No Function & Description

expandtabs(tabsize=8)
7 Expands tabs in string to multiple spaces; defaults to 8 spaces per
tab if tabsize not provided.

find(str, beg=0 end=len(string))


Determine if str occurs in string or in a substring of string if starting
8
index beg and ending index end are given returns index if found and
-1 otherwise.

index(str, beg=0, end=len(string))


9
Same as find(), but raises an exception if str not found.

isalnum()
10 Returns true if string has at least 1 character and all characters are
alphanumeric and false otherwise.

isalpha()
11 Returns true if string has at least 1 character and all characters are
alphabetic and false otherwise.

isdigit()
12
Returns true if string contains only digits and false otherwise.

islower()
13 Returns true if string has at least 1 cased character and all cased
characters are in lowercase and false otherwise.

isnumeric()
14 Returns true if a unicode string contains only numeric characters
and false otherwise.

isspace()
15 Returns true if string contains only whitespace characters and false
otherwise.

istitle()
16
Returns true if string is properly "titlecased" and false otherwise.

isupper()
17 Returns true if string has at least one cased character and all cased
characters are in uppercase and false otherwise.

join(seq)
18 Merges (concatenates) the string representations of elements in
sequence seq into a string, with separator string.
Sr.No Function & Description

len(string)
19
Returns the length of the string

ljust(width[, fillchar])
20 Returns a space-padded string with the original string left-justified
to a total of width columns.

lower()
21
Converts all uppercase letters in string to lowercase.

lstrip()
22
Removes all leading whitespace in string.

maketrans()
23
Returns a translation table to be used in translate function.

max(str)
24
Returns the max alphabetical character from the string str.

min(str)
25
Returns the min alphabetical character from the string str.

replace(old, new [, max])


26 Replaces all occurrences of old in string with new or at most max
occurrences if max given.

rfind(str, beg=0,end=len(string))
27
Same as find(), but search backwards in string.

rindex( str, beg=0, end=len(string))


28
Same as index(), but search backwards in string.

rjust(width,[, fillchar])
29 Returns a space-padded string with the original string right-justified
to a total of width columns.

rstrip()
30
Removes all trailing whitespace of string.

split(str="", num=string.count(str))
31 Splits string according to delimiter str (space if not provided) and
returns list of substrings; split into at most num substrings if given.

splitlines( num=string.count('\n'))
32 Splits string at all (or num) NEWLINEs and returns a list of each line
with NEWLINEs removed.p>
Sr.No Function & Description

startswith(str, beg=0,end=len(string))
Determines if string or a substring of string (if starting index beg and
33
ending index end are given) starts with substring str; returns true if
so and false otherwise.

strip([chars])
34
Performs both lstrip() and rstrip() on string.

swapcase()
35
Inverts case for all letters in string.

title()
36 Returns "titlecased" version of string, that is, all words begin with
uppercase and the rest are lowercase.

translate(table, deletechars="")
37 Translates string according to translation table str(256 chars),
removing those in the del string.

upper()
38
Converts lowercase letters in string to uppercase.

zfill (width)
Returns original string leftpadded with zeros to a total of width
39
characters; intended for numbers, zfill() retains any sign given (less
one zero).

isdecimal()
40 Returns true if a unicode string contains only decimal characters
and false otherwise.

string comparison
String comparison is the process of comparing two strings. These two strings
act as operands or parameters that participate to check their differences. Mostly, the
comparison process uses the ASCII value or Unicode value to compare two strings.
There are three different programming approaches we can use to compare two
strings in Python.
Method 1: Using Relational Operator
Relational operators are mostly used to compare two constants. Since, it comes
under the category of binary operator, it helps in comparing strings in Python also.
After using a relational operator on both operands, it either returns True or False
depending on the condition. These type of operators in Python are also called
the comparison operators. There are 6 different types of comparison operators in
Python.

== (Equal
operator) Checks whether both operands are equal or not
Checks whether the left-hand side operand is greater
> (Greater than) than the right-hand side operand

Checks whether the right-hand side operand is greater


< (Less than) than the left-hand side operand

>= (Greater than Checks whether the left-hand side operand is greater
or equals) than or equal to the right-hand side operand

<= (Less than or Checks whether the right-hand side operand is greater
equals) than or equals to the left-hand side operand

!= (Not equals) Checks whether both operands are not equal or not

Example:
print("Karlos" == "Karlos")
print("Karlos" < "karlos")
print("Karlos" > "karlos")
print("Karlos" != "Karlos")
Output:
True
True
False
False
Method 2: Using is and is not (Identity) operator
In Python, the == operator is used for comparing the values for both the
operands while checking for equality. But the Python's 'is' operator (which is an
identity operator) helps in checking whether both its operands are referring to the
same object or not. This also happens in the case of != and 'is not' operators of
Python.
Program:
val1 = "Karlos"
val2 = "Karlos"
val3 = val1
valn = "karlos"

print(" The ID of val1 is: ", hex(id (val1)))


print(" The ID of val2 is: ", hex(id (val2)))
print(" The ID of val3 is: ", hex(id (val3)))
print(" The ID of valn is: ", hex(id (valn)))
print(val1 is val1)
print(val1 is val2)
print(val1 is val3)
print(valn is val1)
Output:
The ID of val1 is: 0x78a6b3d56870
The ID of val2 is: 0x78a6b3d56870
The ID of val3 is: 0x78a6b3d56870
The ID of valn is: 0x78a6b3d56970
True
True
True
False
Explanation:
Here we are using the identity operator to check & compare the two strings. Here
we have declared four variables that will hold some string values. The variable val1
& val2 will hold “Karlos” and val3 will hold the value of val1. The final valn will hold
a string “karlos”. Now, each of them is different objects and hence the object ID might
vary. Therefore, we are using the hex(id()) functions in combination to fetch and
display the object ID for each variable created.
Method 3: String Insensitive comparison
In the previous topics, we discussed how we have to match the exact string. But, to
perform case-insensitive comparisons, we have to use
the lower() and upper() methods. We can find both these methods under Python's
string objects. The upper() method is used for converting the entire string into
uppercase, whereas the lower() is used to convert all the strings to their lowercase
letters.
Program:
listOfCities = ["Mumbai", "Bangaluru", "Noida"]
currCity = "noiDa"
for loc in listOfCities:
print (" Case-Insensitive Comparison: %s with %s: %s" % (loc, currCity,
loc.lower() == currCity.lower()))
Output:
Case-Insensitive Comparison: Mumbai with noiDa: False
Case-Insensitive Comparison: Bangaluru with noiDa: False
Case-Insensitive Comparison: Noida with noiDa: True
Method 4: Using user-defined function
Apart from all the above techniques, we can also create our own user-defined
function using the 'def' keyword and take each character from both strings and
compare them using the relational operator. This function will allow two string
parameters that need to be compared. If the string matches irrespective of upper or
lower case, it will show matching by returning a TRUE value.
Program:
def strcmpr(strg, strgg):
cnt1 = 0
cnt2 = 0
for i in range(len(strg)):
if strg[i] >= "0" and strg[i] <= "9":
cnt1 += 1
for i in range(len(strgg)):
if strgg[i] >= "0" and strgg[i] <= "9":
cnt2 += 1
return cnt1 == cnt2

print('Compare String 246 and 2468: ', strcmpr("246", "2468"))


print('Compare String KARLOS and karlos:', strcmpr("KARLOS", "karlos"))
Output:
Compare String 246 and 2468: False
Compare String KARLOS and karlos: True
Method 5: Using Regular Expression
A regex or regular expression defines a specific pattern in a programming
element. Here also, we will be using regular expressions to find patterns in
characters of the compared string. To implement the concept of regular expression
in Python, we will use the re module. This time we will use the compile() method
of the re module to check the pattern.
Program:
import re
stateList = ["Madhya Pradesh", "Tamil Nadu", "Uttar Pradesh", "Punjab"]
pattern = re.compile("[Pp]radesh")
for loc in stateList:
if pattern.search(loc):
print ("%s is matching with the search pattern" % loc)
Output:
Madhya Pradesh is matching with the search pattern
Uttar Pradesh is matching with the search pattern

Python Module
A Python module is a file containing Python definitions and statements. A
module can define functions, classes, and variables. A module can also include
runnable code.
Grouping related code into a module makes the code easier to understand and
use. It also makes the code logically organized.
Create a Python Module
To create a Python module, write the desired code and save that in a file
with .py extension. Let’s understand it better with an example:
Example:
Let’s create a simple calc.py in which we define two functions, one add and
another subtract.
# A simple module, calc.py
def add(x, y):
return (x+y)

def subtract(x, y):


return (x-y)
Import module in Python
We can import the functions, and classes defined in a module to another
module using the import statement in some other Python source file.
When the interpreter encounters an import statement, it imports the module
if the module is present in the search path.
Syntax to Import Module in Python
import module
Importing modules in Python Example
# importing module calc.py
import calc
print(calc.add(10, 2))

Output:
12
Python Import From Module
Python’s from statement lets you import specific attributes from a module without
importing the module as a whole.
# importing sqrt() and factorial from the module math
from math import sqrt, factorial
# if we simply do "import math", then math.sqrt(16) and math.factorial()
are required.
print(sqrt(16))
print(factorial(6))
Output:
4.0
720
Built-in Modules
There are several built-in modules in Python, which you can import whenever you
like.
Example
Import and use the platform module:
import platform
x = platform.system()
print(x)
Output:
Windows
datetime: Provides classes for manipulating dates and times.
import datetime
now = datetime.datetime.now()
print(now) # Current date and time
Using the dir() Function
There is a built-in function to list all the function names (or variable names) in a
module. The dir() function:
Example
List all the defined names belonging to the platform module:
import platform
x = dir(platform)
print(x)
Output:
['_Processor', '_WIN32_CLIENT_RELEASES', '_WIN32_SERVER_RELEASES',
'__builtins__', '__cached__', '__copyright__', '__doc__', '__file__', '__loader__', '__name__',
'__package__', '__spec__', '__version__', '_comparable_version', '_default_architecture',
'_follow_symlinks', '_get_machine_win32', '_java_getprop', '_mac_ver_xml', '_node',
'_norm_version', '_os_release_cache', '_os_release_candidates', '_parse_os_release',
'_platform', '_platform_cache', '_sys_version', '_sys_version_cache', '_syscmd_file',
'_syscmd_ver', '_uname_cache', '_unknown_as_blank', '_ver_stages', '_win32_ver',
'_wmi', '_wmi_query', 'architecture', 'collections', 'freedesktop_os_release',
'functools', 'itertools', 'java_ver', 'libc_ver', 'mac_ver', 'machine', 'node', 'os',
'platform', 'processor', 'python_branch', 'python_build', 'python_compiler',
'python_implementation', 'python_revision', 'python_version',
'python_version_tuple', 're', 'release', 'sys', 'system', 'system_alias', 'uname',
'uname_result', 'version', 'win32_edition', 'win32_is_iot', 'win32_ver']
Namespaces
A namespace is a container that holds a set of identifiers (variable names) and
their corresponding objects. It helps in avoiding name conflicts and managing the
scope of variables.
❖ Built-in Namespace: Contains built-in functions and exceptions.
print(len("hello")) # 5
❖ Global Namespace: Contains global variables and functions defined in a
module.
x = 10 # Global variable
def func():
print(x) # Accesses global variable
❖ Local Namespace: Contains local variables defined inside a function.

def func(): Output:


x = 5 # Local variable 5
print(x)
func()
Scope of Variables
❖ Global Scope: Variables declared outside any function or block have a global
scope and can be accessed anywhere in the module.

x = 10 Output:
def func():
10
print(x)
func() # 10 10
print(x) # 10

❖ Local Scope: Variables declared inside a function have a local scope and can
only be accessed within that function.

def func(): Output:


x=5 5
print(x)
func() # 5
# print(x) # Error: x is not
defined

❖ Enclosing Scope: Variables in the enclosing scope (in nested functions) can be
accessed using the nonlocal keyword.

def outer(): Output:


x = "outer" inner
def inner():
nonlocal x
x = "inner"
inner()
print(x) # "inner"
outer()

❖ The global Keyword


The global keyword allows modification of a global variable inside a function.

x = 10 Output:
def func(): 20
global x
x = 20
func()
print(x) # 20

Defining our own modules


Example Module
Let's create a module named mymodule.py:
# mymodule.py
def greet(name):
return f"Hello, {name}!"
def add(a, b):
return a + b
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def display(self):
return f"Person(name={self.name}, age={self.age})"
PI = 3.14159
Using a Module
Once you have created your module, you can use it in other Python scripts by
importing it.
Basic Import
Import the entire module and use its functions, classes, and variables:
import mymodule
print(mymodule.greet("SKS"))
print(mymodule.add(5, 3)) #8
p = mymodule.Person("CS", 30)
print(p.display())
print(mymodule.PI) # 3.14159
Output:
Hello, SKS!
8
Person(name=CS, age=30)
3.14159
Importing Specific Items
You can import specific functions, classes, or variables from a module:
from mymodule import greet, add, Person, PI
print(greet("Alice")) # "Hello, Alice!"
print(add(5, 3)) #8
p = Person("Bob", 30)
print(p.display()) # "Person(name=Bob, age=30)"
print(PI) # 3.14159

You might also like