Python Unit 2.Pptx
Python Unit 2.Pptx
Unit 2: For Loop, While Loop & Nested Loops, String Manipulation, List, Tuple, Sets and Dictionary, Understanding Iterators,
Generators, Comprehensions Loops in Python, Basic Operations, Slicing & Functions and Methods, User Defined Functions, Lambda
Function, Importing Modules, Math Module.
Unit 3: Reading and writing text files, appending to files, writing Binary Files, Using Pickle to write binary files. Regular expressions,
match function, search function, matching V/S searching, search and replace, Regular Expressions, Wildcard.
Unit 4: Basics of Object-Oriented Programming, Creating Class and Object, Constructors in Python Parameterized and
Non-parameterized, Inheritance in Python, Inbuilt class methods and attributes, Multi-Level and Multiple Inheritance, Method
Overriding and Data Abstraction, Encapsulation and Polymorphism.
Unit 5: NumPy-Introduction, creating arrays, using arrays and scalars, Indexing Arrays, Array Transposition, Array Processing, Array
Input and Output. Pandas: Introduction, uses of Panda, Series in pandas, Index objects, Reindex, Drop Entry, Selecting Entries, Data
Alignment, Rank and Sort Summary Statics, Missing Data, Index Hierarchy. Matplotlib: Introduction, uses of Matplotlib, Data
Visualization: Scikit introduction, Introduction to Machine Learning in Python.
UNIT-2
Break Statement:
The break statement is used to exit the current loop prematurely, regardless of whether the
loop's condition has been satisfied or not.
Purpose of Break Statement:
● It is used to terminate the loop early if a certain condition is met.
● It allows for immediate termination of the loop's execution.
Continue Statement:
The continue statement is used to skip the current iteration of a loop and proceed to the next
iteration.
Purpose of Continue Statement:
● It is used to bypass certain iterations based on a specific condition.
● It allows for the skipping of specific operations within a loop without terminating the
loop entirely.
# Example of continue statement
numbers = [1, 2, 3, 4, 5]
for number in numbers:
if number == 3:
continue
print(number)
In this example, the value of number is not printed when it equals 3, and the loop continues
with the next iteration.
Faculty Name: Vimal Singh Department: SCSE
Course Code:R1UC405C Course Name: Programming in Python
Purpose and Working of While Loop:
The while loop in Python is used to repeatedly execute a block of code as long as a specified condition is true. It is ideal
when you don't know the number of iterations beforehand and need to continue looping until a certain condition is met.
List
List
Definition and Characteristics:
List
Creation:
List
Accessing Elements:
You can access individual elements of a list using square brackets [] and the
index of the element. Python uses zero-based indexing, meaning the first
element has an index of 0, the second element has an index of 1, and so on.
my_list = [1, 2, 3, 'a', 'b', 'c']
print(my_list[0]) # Output: 1
print(my_list[3]) # Output: 'a'
Faculty Name: Vimal Singh Department: SCSE
Course Code:R1UC405C Course Name: Programming in Python
List
Accessing Elements:
You can also use negative indices to access elements from the
end of the list:
my_list = [1, 2, 3, 'a', 'b', 'c']
print(my_list[-1]) # Output: 'c' (last element)
List
Slicing:
You can also extract a sublist (slice) from a list using the slice operator
:. This allows you to specify a range of indices to retrieve a portion of
the list.
List
Slicing:
You can also extract a sublist (slice) from a list using the slice operator
:. This allows you to specify a range of indices to retrieve a portion of
the list.
my_list = [1, 2, 3, 'a', 'b', 'c']
List Operations:
● Concatenation: You can concatenate two lists using the “+”
operator.
● Repetition: You can repeat a list using the “*” operator.
● Membership: You can check if an element is present in a list
using the “in” operator.
List Methods:
Python lists come with several built-in methods for common operations
such as adding, removing, and manipulating elements. Some of the
commonly used methods include
append(), extend(), insert(),
remove(), pop(), index(),
count(), sort(), and reverse().
# List comprehension
squared_numbers = [x ** 2 for x in my_list if isinstance(x, int)]
Tuple
Tuples in Python are similar to lists, but they have some key
differences. Here's a detailed explanation of tuples in Python:
Tuples in Python are similar to lists, but they have some key
differences. Here's a detailed explanation of tuples in Python:
Definition and Characteristics:
● Ordered Collection: Like lists, tuples are ordered collections of
elements. This means the order of elements in a tuple is preserved.
● Immutable: Unlike lists, tuples are immutable, meaning once they are
created, their elements cannot be changed, added, or removed.
● Heterogeneous: Tuples can contain elements of different data types, just
like lists.
● Hashable: Tuples are hashable, which means they can be used as keys in
dictionaries and elements of sets.
Faculty Name: Vimal Singh Department: SCSE
Course Code:R1UC405C Course Name: Programming in Python
Creation:
You can create a tuple in Python using parentheses () or the built-in tuple()
function. Here's how you can create a tuple:
Creation:
You can create a tuple in Python using parentheses () or the built-in tuple()
function. Here's how you can create a tuple:
Accessing Elements:
You can access individual elements of a tuple using square brackets [] and
the index of the element, just like lists.
print(my_tuple[0]) # Output: 1
print(my_tuple[3]) # Output: 'a'
Faculty Name: Vimal Singh Department: SCSE
Course Code:R1UC405C Course Name: Programming in Python
Tuple packing is the process of packing multiple values into a tuple. Tuple
unpacking is the process of extracting values from a tuple into individual
variables.
# Tuple packing
my_tuple = 1, 2, 3
# Tuple unpacking
a, b, c = my_tuple
print(a, b, c) # Output: 1 2 3
Operations:
Since tuples are immutable, they support fewer operations compared to lists.
You can concatenate tuples, repeat them, and check for membership using
the same operators used for lists (+, *, in).
List and Syntax Defined using square brackets [] Defined using parentheses ()
Tuple: Modification Elements can be added, removed, or modified
Elements cannot be added, removed,
or modified
Operations on List
Initialization Create an empty list or initialize a list with elements my_list = []<br>my_list = [1, 2, 3]
Extend Extend the list by appending elements from another iterable my_list.extend(another_list)
Index Return the index of the first occurrence of a specific element index = my_list.index(element)
Length Find the number of elements in the list using len() length = len(my_list)
Course Code:R1UC405C Course Name: Programming in Python
Operations on
Tuple
Faculty Name: Vimal Singh Department: SCSE
Operation Description Example
Create an empty tuple or
Initialization my_tuple = ( ) my_tuple = (1, 2, 3)
initialize a tuple with elements
Access elements in a tuple
Access element = my_tuple[index]
using indexing
Extract a subset of elements
Slicing subset = my_tuple[start:end:step]
from a tuple
Concatenate two tuples into a
Concatenation new_tuple = tuple1 + tuple2
new tuple
Repeat a tuple for a specified
Repetition repeated_tuple = my_tuple * n
number of times
Check if an element is present
Membership if element in my_tuple:
in the tuple using in
Find the number of elements in
Length length = len(my_tuple)
the tuple using len()
Course Code:R1UC405C Course Name: Programming in Python
Set in Python
Set:
A set in Python is an unordered collection of unique elements. It is defined by a
comma-separated sequence of elements within curly braces {}. Sets are mutable,
meaning you can add or remove elements, but the elements themselves must be
immutable (e.g., integers, strings, tuples).
Set Characteristics:
● Uniqueness: Sets do not allow duplicate elements. When you add duplicate
elements to a set, only one instance of each unique element is retained.
● Unordered: Elements in a set are not stored in any particular order. Thus, you
cannot access elements by index or slice a set like you would with a list or tuple.
● Mutable: You can modify a set by adding or removing elements after it has been
created.
● Operations: Sets support various mathematical operations such as union,
intersection, difference, and symmetric difference.
Set Creation:
Sets can be created using curly braces {} or the set() constructor.
my_set = {1, 2, 3}
another_set = set([4, 5, 6])
Output:
my_set is {1, 2, 3}
another_set is {4, 5, 6}
Set Operations:
● Adding Elements:
● You can add elements to a set using the add() method.
● Removing Elements:
● Set Operations:
● Membership Test:
● Length and Clear:
Descripti Removes the specified element from Removes the specified element from the set if it
on the set. is present.
Raises a KeyError if the element is Does not raise any error if the element is not
Behavior not found in the set. found in the set.
Use when you want to ensure the Use when you want to remove the element if it's
Usage element is present in the set before present without handling the case where it's not
removing it. in the set.
my_set = set()
Initialization Create an empty set or initialize a set with elements
my_set = {1, 2, 3}
Adding Elements Add elements to the set using the add() method my_set.add(4)
my_set.discard(3)
intersection_set = set1.intersection(set2)
difference_set = set1.difference(set2)
symmetric_difference_set = set1.symmetric_difference(set2)
Dictionary in Python
Dictionary:
A dictionary in Python is an unordered collection of key-value pairs. It is a highly flexible and
powerful data structure used to store and retrieve data efficiently.
Dictionary:
A dictionary in Python is an unordered collection of key-value pairs. It is a highly flexible and
powerful data structure used to store and retrieve data efficiently.
● Unordered Collection: Dictionaries do not maintain any order among their elements. The elements
are stored based on their hash values, which allows for fast retrieval.
Dictionary:
A dictionary in Python is an unordered collection of key-value pairs. It is a highly flexible and
powerful data structure used to store and retrieve data efficiently.
● Unordered Collection: Dictionaries do not maintain any order among their elements. The elements
are stored based on their hash values, which allows for fast retrieval.
● Mutable: Dictionaries are mutable, meaning you can add, remove, and modify key-value pairs after
the dictionary has been created.
Dictionary:
A dictionary in Python is an unordered collection of key-value pairs. It is a highly flexible and
powerful data structure used to store and retrieve data efficiently.
● Unordered Collection: Dictionaries do not maintain any order among their elements. The elements
are stored based on their hash values, which allows for fast retrieval.
● Mutable: Dictionaries are mutable, meaning you can add, remove, and modify key-value pairs after
the dictionary has been created.
● Keys and Values: Each element in a dictionary consists of a key and its corresponding value. Keys
must be unique and immutable (e.g., strings, numbers, tuples), while values can be of any data type
and can be mutable.
Dictionary:
A dictionary in Python is an unordered collection of key-value pairs. It is a highly flexible and
powerful data structure used to store and retrieve data efficiently.
● Unordered Collection: Dictionaries do not maintain any order among their elements. The elements
are stored based on their hash values, which allows for fast retrieval.
● Mutable: Dictionaries are mutable, meaning you can add, remove, and modify key-value pairs after
the dictionary has been created.
● Keys and Values: Each element in a dictionary consists of a key and its corresponding value. Keys
must be unique and immutable (e.g., strings, numbers, tuples), while values can be of any data type
and can be mutable.
● Hash Table: Internally, Python dictionaries use a hash table to store key-value pairs, which enables
fast access to elements.
Creating a Dictionary:
Dictionaries are defined using curly braces {} and key-value pairs separated by colons :
Accessing Elements:
● You can access the value associated with a key by specifying the key in square brackets [].
Modifying Elements:
● You can modify the value associated with a key by assigning a new value to that key.
my_dict['age'] = 35
Faculty Name: Vimal Singh Department: SCSE
Course Code:R1UC405C Course Name: Programming in Python
Used to store structured Stores parameters and settings for Transforms data from one format to
Definition
data with key-value pairs applications another
Organizing and
Controlling the behavior of an Restructuring data to meet specific
Use Case retrieving data
application or system requirements
efficiently
Storing user
Database connection settings, Converting data fetched from a
Example information, product
logging levels, etc. database into a dictionary format
details, etc.
2. Set Comprehensions:
List Set comprehensions are similar to list comprehensions but produce sets instead of lists.
They follow the syntax:
2. Set Comprehensions:
List Set comprehensions are similar to list comprehensions but produce sets instead of lists.
They follow the syntax:
2. Set Comprehensions:
List Set comprehensions are similar to list comprehensions but produce sets instead of lists.
They follow the syntax:
3. Dictionary Comprehensions:
Dictionary comprehensions allow you to create dictionaries in a concise manner. They
follow the syntax:
3. Dictionary Comprehensions:
Dictionary comprehensions allow you to create dictionaries in a concise manner. They
follow the syntax:
● key_expression: The expression to evaluate for each key in the new dictionary.
● value_expression: The expression to evaluate for each value in the new dictionary.
● item: The variable representing the current item in the iteration.
● iterable: The iterable object to iterate over.
● condition (optional): A condition that filters which items to include in the new
dictionary.
3. Dictionary Comprehensions:
Dictionary comprehensions allow you to create dictionaries in a concise manner. They
follow the syntax:
● key_expression: The expression to evaluate for each key in the new dictionary.
● value_expression: The expression to evaluate for each value in the new dictionary.
● item: The variable representing the current item in the iteration.
● iterable: The iterable object to iterate over.
● condition (optional): A condition that filters which items to include in the new
dictionary.
# Dictionary comprehension to create a dictionary of squares of numbers from 0 to 4
squares_dict = {x: x ** 2 for x in range(5)}
print(squares_dict) # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
Function Definition:
○ Functions are standalone blocks of code that can be defined anywhere in the program.
○ They are defined using the def keyword followed by the function name and parameters (if
any).
● Scope:
○ Functions can be defined at the global level or within other functions.
○ They are not associated with any specific object or class.
● Parameters:
○ Functions can have zero or more parameters.
○ Parameters are variables that hold the values passed to the function when it is called.
● Call Syntax:
○ Functions are called using their name followed by parentheses containing the arguments (if
any) you want to pass to the function.
○ Example: result = add(3, 5)
Method Definition:
○ Methods are functions that are associated with objects or classes.
○ They are defined within the scope of a class using the def keyword.
● Scope:
○ Methods belong to a specific class and operate on objects of that class.
○ They are accessed using dot notation (object.method()).
● Parameters:
○ Methods have at least one parameter, self, which refers to the instance of the
class on which the method is called.
○ They can also have additional parameters as needed.
● Call Syntax:
○ Methods are called on objects of the class using dot notation (object.method()).
○ Example: my_circle.area()
# Function call
result = add(3, 5)
print(result) # Output: 8
# Method call
my_object = MyClass()
my_object.my_method() # Output: This is a method
Faculty Name: Vimal Singh Department: SCSE
Aspect Course Code:R1UC405C Course Name:
Functions Programming in Python
Methods
Defined within the scope of a class using def
Definition Defined using def keyword.
keyword.
Can be defined anywhere in the Belong to a specific class and operate on objects of
Scope
program. that class.
Lambda Function
Lambda Function:
A lambda function is a small, unnamed function defined using a compact syntax. It
typically takes one or more arguments, performs a single expression, and returns the
result of that expression. Lambda functions are often used when you need a simple
function for a short period of time and don't want to define a formal function using the
def keyword.
Syntax (in Python):
In Python, the syntax for a lambda function is as follows:
lambda arguments: expression
● Conciseness: Lambda functions allow you to define simple functions in a single line of code,
making your code more concise and readable.
● No Need for Defining Names: Lambda functions are anonymous, meaning you don't need to
define a formal name for them, which can be useful for short-lived functions.
● Functional Style: Lambda functions encourage a functional programming style, which can
lead to cleaner and more modular code.
● Flexibility: Lambda functions can be used in situations where you need a small function but
don't want to clutter your code with unnecessary function definitions.
import mymodule
mymodule.greet("Alice") # Output: Hello, Alice!
import math
# Constants
● print(math.pi) # Output: 3.141592653589793
● print(math.e) # Output: 2.718281828459045
● print(math.inf) # Output: inf
● print(math.nan) # Output: nan
import math
# Constants
● print(math.pi) # Output: 3.141592653589793
● print(math.e) # Output: 2.718281828459045
● print(math.inf) # Output: inf
● print(math.nan) # Output: nan
# Trigonometric functions
● print(math.sin(math.pi / 2)) # Output: 1.0
● print(math.degrees(math.pi)) # Output: 180.0
import math
# Constants
● print(math.pi) # Output: 3.141592653589793
● print(math.e) # Output: 2.718281828459045
● print(math.inf) # Output: inf
● print(math.nan) # Output: nan
# Trigonometric functions
● print(math.sin(math.pi / 2)) # Output: 1.0
● print(math.degrees(math.pi)) # Output: 180.0
import math
# Constants # Power and Root functions
● print(math.pi) # Output: 3.141592653589793 ● print(math.pow(2, 3)) # Output: 8.0
● print(math.e) # Output: 2.718281828459045
● print(math.inf) # Output: inf
● print(math.sqrt(16)) # Output: 4.0
● print(math.nan) # Output: nan ● print(math.ceil(3.7)) # Output: 4
● print(math.floor(3.7)) # Output: 3
# Trigonometric functions
● print(math.sin(math.pi / 2)) # Output: 1.0
● print(math.degrees(math.pi)) # Output: 180.0
import math
# Constants # Power and Root functions
● print(math.pi) # Output: 3.141592653589793 ● print(math.pow(2, 3)) # Output: 8.0
● print(math.e) # Output: 2.718281828459045
● print(math.inf) # Output: inf
● print(math.sqrt(16)) # Output: 4.0
● print(math.nan) # Output: nan ● print(math.ceil(3.7)) # Output: 4
● print(math.floor(3.7)) # Output: 3
# Trigonometric functions
● print(math.sin(math.pi / 2)) # Output: 1.0 # Miscellaneous functions
● print(math.degrees(math.pi)) # Output: 180.0
● print(math.factorial(5)) # Output: 120
● print(math.gcd(12, 8)) # Output: 4
# Exponential and Logarithmic functions ● print(math.isclose(0.1 + 0.2, 0.3)) # Output: True
● print(math.exp(1)) # Output:
● print(math.trunc(3.9)) # Output: 3
2.718281828459045
● print(math.log(math.e)) # Output: 1.0
Q.2 : Explain how to use the math module to perform numerical computations
involving constants such as π (pi) and e (Euler's number). Provide examples
demonstrating their usage in mathematical calculations.
String:
Python strings are one of the fundamental data types in Python, used to represent
sequences of characters. They are immutable, meaning once created, their contents
cannot be changed.
String:
Python strings are one of the fundamental data types in Python, used to represent
sequences of characters. They are immutable, meaning once created, their contents
cannot be changed.
1. Creation: Strings can be created using single quotes (' '), double quotes (" "), or
triple quotes (''' ''' or """ """). For example:
String='Hello, World!'
String="Hello, World!"
String="""Hello, World!"""
string3 = '''This is a
multiline
string.'''
String:
Python strings are one of the fundamental data types in Python, used to represent
sequences of characters. They are immutable, meaning once created, their contents
cannot be changed.
2. Accessing Characters: You can access individual characters or slices of strings
using indexing and slicing.
my_string='Hello, World!'
print(my_string[0]) # Output: 'H'
print(my_string[1:5]) # Output: 'ello'
String:
Python strings are one of the fundamental data types in Python, used to represent
sequences of characters. They are immutable, meaning once created, their contents
cannot be changed.
3. Concatenation: Strings can be concatenated using the + operator.
str1 = "Hello"
str2 = "World"
result = str1 + " " + str2
print(result) # Output: 'Hello World'
String:
Python strings are one of the fundamental data types in Python, used to represent
sequences of characters. They are immutable, meaning once created, their contents
cannot be changed.
4. Length: You can find the length of a string using the len() function.
my_string='Hello, World!'
print(len(my_string)) # Output: 13
String:
Python strings are one of the fundamental data types in Python, used to represent
sequences of characters. They are immutable, meaning once created, their contents
cannot be changed.
5. Iterating Through Strings: Strings can be iterated through using loops.
my_string='Hello, World!'
for char in my_string:
print(char)
String:
Python strings are one of the fundamental data types in Python, used to represent
sequences of characters. They are immutable, meaning once created, their contents
cannot be changed.
6. String Methods: Python provides many built-in methods to manipulate strings,
such as split(), strip(), lower(), upper(), replace(), etc.
String:
Python strings are one of the fundamental data types in Python, used to represent
sequences of characters. They are immutable, meaning once created, their contents
cannot be changed.
7. String Formatting: Python supports various methods for string formatting,
including old-style % formatting and newer str.format() method. The latest is
f-strings.
name = "Alice"
age = 30
print("Name: %s, Age: %d" % (name, age)) # Output: 'Name: Alice, Age: 30'
print("Name: {}, Age: {}".format(name, age)) # Output: 'Name: Alice, Age: 30'
print(f"Name: {name}, Age: {age}") # Output: 'Name: Alice, Age: 30'
String:
Python strings are one of the fundamental data types in Python, used to represent
sequences of characters. They are immutable, meaning once created, their contents
cannot be changed.
8. Escape Characters: Python supports escape characters like \n for newline, \t for
tab, etc.
print("Hello\nWorld") print("Hello\tWorld")
Output:Hello Output:Hello World
World
String:
Python strings are one of the fundamental data types in Python, used to represent
sequences of characters. They are immutable, meaning once created, their contents
cannot be changed.
9. String Operations: Python supports various operations on strings, such as
checking containment using in operator, repetition using * operator, etc.
String:
Python strings are one of the fundamental data types in Python, used to represent
sequences of characters. They are immutable, meaning once created, their contents
cannot be changed.
10. String Slicing: Strings can be sliced to extract substrings efficiently.
s = "Python Programming"
print(s[2:6]) # Output: 'thon'
Question on String
# Example paragraph
paragraph = "This is a sample paragraph. It contains some words."
# Example paragraph
paragraph = "This is a sample paragraph. It contains some words."
Q. 2: Explain the difference between single-quoted (''), double-quoted (" "), and triple-quoted (''' ''' or """ """) strings in
Python. Discuss scenarios where each type of string is commonly used.
Q. 3: Discuss various string manipulation techniques available in Python, such as string concatenation, slicing, indexing, and
repetition. Provide examples demonstrating how these operations are performed and their practical applications.
Q. 4: Describe the significance of string methods in Python, such as lower(), upper(), strip(), replace(), split(), and join().
Explain how these methods are used to modify and manipulate strings effectively.
Q. 5: Explain the concept of string formatting in Python, including the use of the format() method, f-strings (formatted string
literals), and the % operator. Provide examples illustrating different formatting options and their advantages.
Q. Define a function that prints a dictionary where the keys are number
between 1 to 4 (both number included) and the values are cubes of the keys.
Q. Define a function that prints a dictionary where the keys are number
between 1 to 4 (both number included) and the values are cubes of the keys.
def print_cubes():
cube_dict = {}
for num in range(1, 5):
cube_dict[num] = num ** 3
print(cube_dict)
print("Word frequencies:")
for word, freq in word_freq.items():
print(f"{word}: {freq}")
print("Word frequencies:")
for word, freq in word_freq.items():
print(f"{word}: {freq}")
Word frequencies:
This: 1
is: 2
a: 1
sample: 2
paragraph.: 1
It: 1
contains: 1
some: 1
words,: 1
and: 1
it: 1
just: 1
for: 1
demonstration: 1
purposes.: 1
re.sub() function is used to substitute all non-word characters ([^\w\s]) with an empty
string in the paragraph. This pattern removes any character that is not a word
character (alphanumeric or underscore) or whitespace.
Word count in Course
paragraph (without specialCourse
Code:R1UC405C characters):
Name: Programming in Python
import re
# Input paragraph
paragraph = "This is a sample paragraph. It contains some sample words, and it is just
for demonstration purposes."
# Remove special characters from the paragraph using regular expressions
paragraph = re.sub(r '[^\w\s]', '', paragraph)
# Initialize an empty dictionary to store word frequencies
word_freq = {}
# Split paragraph into words and count frequencies
words = paragraph.split()
for word in words:
word_freq[word] = word_freq.get(word, 0) + 1
# Find the word with maximum frequency
max_freq_word = max(word_freq, key=word_freq.get)
max_freq = word_freq[max_freq_word]
print("Word frequencies:" )
for word, freq in word_freq.items():
print(f"{word}: {freq}")
print(f"\nWord with maximum frequency: {max_freq_word} (Frequency: {max_freq})")
OUTPUT:
Word frequencies:
This: 1
is: 2
a: 1
sample: 2
paragraph: 1
It: 1
contains: 1
some: 1
words: 1
and: 1
it: 1
just: 1
for: 1
demonstration: 1
purposes: 1