0% found this document useful (0 votes)
1 views

Python Unit 2.Pptx

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Python Unit 2.Pptx

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 128

Course Code:R1UC405C Course Name: Programming in Python

Syllabus for Programming in Python


Unit 1: Introduction to Python, Features of Python, Python versions, Install Python and Environment Setup, Python Identifiers,
Keywords and Indentation, Python Data Types, Variables, Operators in Python, Assignment, Logical, Arithmetic, etc. Taking User
Inputs, Conditional Statements If else and Nested If else and Elif.

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.

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

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.

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

Purpose and Working of For Loop:


The for loop in Python is used to iterate over a sequence (such as a list, tuple, dictionary, or
string) and execute a block of code for each item in the sequence.

Working of For Loop:


The for loop iterates over each item in the sequence.
For each iteration, the current item in the sequence is assigned to the variable specified after
the for keyword (item in the above syntax).
The block of code within the for loop is executed once for each item in the sequence.
Example of For Loop:

# Example of for loop


fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Faculty Name: Vimal Singh Department: SCSE
Course Code:R1UC405C Course Name: Programming in Python

Nested For Loop:


A nested for loop is a loop inside another loop. It allows for multiple
iterations over sequences within sequences.

for item1 in sequence1:


for item2 in sequence2:
# Execute this block of code for each combination of items from
sequence1 and sequence2
statement(s)

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

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.

# Example of break statement


numbers = [1, 2, 3, 4, 5]

for number in numbers:


if number == 3:
break
print(number)

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

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.

Working of While Loop:


The condition specified after the while keyword is evaluated.
If the condition is true, the block of code within the while loop is executed.
After executing the block of code, the condition is evaluated again.
If the condition is still true, the block of code is executed again. This process continues until the condition becomes false.
When the condition becomes false, the program exits the while loop and continues executing the subsequent code.

# Example of while loop


count = 0

while count < 5:


print("Count is:", count)
count += 1

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

Python Data Types


Data types are the classification or categorization of data items. It represents the
kind of value that tells what operations can be performed on a particular data.
Since everything is an object in Python programming, data types are classes and
variables are instances (objects) of these classes. The following are the standard
or built-in data types in Python:
● Numeric
● Sequence Type
● Boolean
● Set
● Dictionary
● Binary Types

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

List

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

List
Definition and Characteristics:

● Ordered Collection: Lists maintain the order of elements as they are


inserted.
● Mutable: Lists are mutable, meaning you can change, add, or remove
elements after the list is created.
● Heterogeneous: Lists can contain elements of different data types, including
integers, floats, strings, other lists, dictionaries, etc.
● Dynamic: Lists can grow or shrink in size dynamically as elements are added
or removed.
Faculty Name: Vimal Singh Department: SCSE
Course Code:R1UC405C Course Name: Programming in Python

List
Creation:

You can create a list in Python using square brackets [] or the


built-in list() function. Here's how you can create a list:

my_list = [1, 2, 3, 'a', 'b', 'c']

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

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)

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

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.

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

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']

print(my_list[2:5]) # Output: [3, 'a', 'b'] (from index 2 to 4)


print(my_list[:3]) # Output: [1, 2, 3] (from beginning to index 2)
print(my_list[3:]) # Output: ['a', 'b', 'c'] (from index 3 to end)
Faculty Name: Vimal Singh Department: SCSE
Course Code:R1UC405C Course Name: Programming in Python

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.

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

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().

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

Iterating Over a List:


You can iterate over the elements of a list using a for loop or list
comprehension.
my_list = [1, 2, 3, 'a', 'b', 'c']
for item in my_list:
print(item)

# List comprehension
squared_numbers = [x ** 2 for x in my_list if isinstance(x, int)]

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

Tuple

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

Tuples in Python are similar to lists, but they have some key
differences. Here's a detailed explanation of tuples in Python:

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming 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:

my_tuple = (1, 2, 3, 'a', 'b', 'c')

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:

my_tuple = (1, 2, 3, 'a', 'b', 'c')

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 and Unpacking:

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

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

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

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

Difference Feature List Tuple


between Mutability Mutable Immutable

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

Performance Slightly slower due to mutability Slightly faster due to immutability

When the data should remain constant


Use Cases When the data needs to be modified frequently
after creation
Lists support more operations like append, Tuples support fewer operations due to
Operations
extend, insert, remove, etc. immutability

Hashability Lists are not hashable Tuples are hashable

Tuples consume less memory due to


Memory Lists consume more memory due to mutability
immutability

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

Operations on List

Faculty Name: Vimal Singh Department: SCSE


Operation Description Example

Initialization Create an empty list or initialize a list with elements my_list = []<br>my_list = [1, 2, 3]

Access Access elements in a list using indexing element = my_list[index]

Slicing Extract a subset of elements from a list subset = my_list[start:end:step]

Append Add an element to the end of the list my_list.append(element)

Extend Extend the list by appending elements from another iterable my_list.extend(another_list)

Insert Insert an element at a specific index my_list.insert(index, element)

Remove Remove the first occurrence of a specific element my_list.remove(element)

Remove and return an element at a specific index (or the last


Pop element = my_list.pop(index)
element)

Index Return the index of the first occurrence of a specific element index = my_list.index(element)

Count Count the number of occurrences of a specific element count = my_list.count(element)

Sort Sort the elements of the list in place my_list.sort()<br>my_list.sort(reverse=True)

Reverse Reverse the order of elements in the list my_list.reverse()

Clear Remove all elements from the list my_list.clear()

Membership Check if an element is present in the list using in if element in my_list:

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

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming 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).

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

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.

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

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}

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

Set Operations:
● Adding Elements:
● You can add elements to a set using the add() method.
● Removing Elements:
● Set Operations:
● Membership Test:
● Length and Clear:

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

another_set = set([4, 5, 6])


print ("my_set is", my_set) Output:
print ("another_set is", another_set)
my_set is {1, 2, 3}
my_set.add(4) another_set is {4, 5, 6}
print ("my_set is", my_set)
my_set.remove(2) my_set is {1, 2, 3, 4}
print ("my_set is", my_set) my_set is {1, 3, 4}
my_set.discard(3)
print ("my_set is", my_set) my_set is {1, 4}
2
if 3 in my_set:
print("3 is in the set") my_set is set()
print(len(my_set))
my_set.clear()
print ("my_set is", my_set)

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

Feature remove() Method discard() Method

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.

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python
Operation Description Example

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)

Remove elements from the set using the remove()


Removing Elements my_set.remove(2)
method

my_set.discard(3)

Set Operations Perform various mathematical operations on sets union_set = set1.union(set2)

intersection_set = set1.intersection(set2)

difference_set = set1.difference(set2)

symmetric_difference_set = set1.symmetric_difference(set2)

Check if an element is present in the set using the in


Membership Testing if 3 in my_set:
keyword

Find the number of elements in the set using the len()


Length length = len(my_set)
function

Clear Faculty Name: Vimal


Remove Singh
all elements from the set using the clear()
my_set.clear() Department: SCSE
Course Code:R1UC405C Course Name: Programming in Python

Dictionary in Python

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming 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.

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming 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.
● 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.

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming 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.
● 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.

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming 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.
● 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.

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming 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.
● 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.

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

Creating a Dictionary:
Dictionaries are defined using curly braces {} and key-value pairs separated by colons :

my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}

Accessing Elements:
● You can access the value associated with a key by specifying the key in square brackets [].

print(my_dict['name']) # Output: 'John'

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

Dictionary Use Cases:


● Data Storage: Dictionaries are useful for storing structured data where each
piece of data is associated with a unique identifier (the key).
● Configuration Settings: Dictionaries are often used to store configuration
settings for applications.
● Data Transformation: Dictionaries can be used to transform data from one
format to another.

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

Dictionary Use Cases:


Aspect Data Storage Configuration Settings Data Transformation

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.

python my_dict = python config = {'db': {'host': python transformed_data =


Syntax {'key1': value1, 'key2': 'localhost', 'port': 3306}, 'logging': {item['id']: item['name'] for item in
value2} {'level': 'DEBUG'}} database_data}

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

Difference between List , Tuple, Set


and Dictionary

Faculty Name: Vimal Singh Department: SCSE


Aspect List Tuple Set Dictionary
Mutable: Key-value
Mutable: Elements can Mutable: Elements can
Immutable: Elements cannot pairs can be added,
Mutability be added, removed, or be added or removed,
be modified after creation removed, or modified
modified after creation but not modified
after creation
[element1, element2, {element1, element2, {'key1': value1, 'key2':
Syntax (element1, element2, ...)
...] ...} value2, ...}

Ordered: Elements are Unordered: Elements Unordered: Elements are


Ordered: Elements are stored
Order stored in the order they are not stored in any not stored in any
in the order they were added
were added particular order particular order

Allows duplicate keys,


Allows duplicate Does not allow
Duplication Allows duplicate elements but not duplicate
elements duplicate elements
key-value pairs

Supports indexing and Does not support Does not support


Indexing Supports indexing and slicing
slicing indexing or slicing indexing or slicing

When immutability and


When the sequence of When uniqueness of When key-value pairs
sequence of elements matter,
Use Cases elements matters and elements and set are needed to store data
such as for returning multiple
needs to be changed operations are needed with associated keys
values from a function
Course Code:R1UC405C Course Name: Programming in Python

Comprehensions Loops in Python

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

Comprehensions Loops in Python:

Comprehensions in Python provide a concise and expressive way to create lists,


dictionaries, and sets without explicitly writing traditional loops.
Comprehensions are often favored for their readability and brevity.

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

Comprehensions Loops in Python:

Comprehensions in Python provide a concise and expressive way to create lists,


dictionaries, and sets without explicitly writing traditional loops.
Comprehensions are often favored for their readability and brevity.

There are mainly three types of comprehensions in Python:


1. List comprehensions
2. Set comprehensions
3. Dictionary comprehensions

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

Comprehensions Loops in Python:


1. List Comprehensions:
List comprehensions allow you to create lists based on existing lists or iterables. They follow
the syntax:

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

Comprehensions Loops in Python:


1. List Comprehensions:
List comprehensions allow you to create lists based on existing lists or iterables. They follow
the syntax:

● expression: The expression to evaluate and include in the new list.


● item: The variable representing the current item in the iteration.
● iterable: The iterable object (e.g., list, tuple, range) to iterate over.
● condition (optional): A condition that filters which items to include in the new list.

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

Comprehensions Loops in Python:


1. List Comprehensions:
List comprehensions allow you to create lists based on existing lists or iterables. They follow
the syntax:

# List comprehension to create a list of squares of numbers from 0 to 9


squares = [x ** 2 for x in range(10)]
print(squares) # Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

2. Set Comprehensions:
List Set comprehensions are similar to list comprehensions but produce sets instead of lists.
They follow the syntax:

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

2. Set Comprehensions:
List Set comprehensions are similar to list comprehensions but produce sets instead of lists.
They follow the syntax:

● expression: The expression to evaluate and include in the new set.


● 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 set.

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

2. Set Comprehensions:
List Set comprehensions are similar to list comprehensions but produce sets instead of lists.
They follow the syntax:

● expression: The expression to evaluate and include in the new set.


● 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 set.

# Set comprehension to create a set of vowels in a string


vowels = {char for char in 'hello' if char in 'aeiou'}
print(vowels) # Output: {'e', 'o'}

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

3. Dictionary Comprehensions:
Dictionary comprehensions allow you to create dictionaries in a concise manner. They
follow the syntax:

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

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.

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

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}

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

Functions and Methods in Python

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

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)

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

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()

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

Example # Function definition


def add(x, y):
of return x + y

Function # Method definition within a class


and class MyClass:
def my_method(self):
Method: print("This is a method")

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

Have at least one parameter, self, referring to the


Can have zero or more
Parameters instance of the class. Can have additional parameters
parameters.
as needed.

Called using their name


Called on objects of the class using dot notation
Call Syntax followed by parentheses
(object.method()).
containing arguments.

python class MyClass: def my_method(self):


python def add(x, y): return x +
Example print("This is a method") my_object = MyClass()
y resultVimal
Faculty Name: = add(3, 5)
Singh my_object.my_method() Department: SCSE
Course Code:R1UC405C Course Name: Programming in Python

Lambda Function

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

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

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

Lambda Function Example:

● Add two Numbers


add = lambda x, y: x + y
print(add(3, 5)) # Output: 8

● Filtering a list of numbers to get only even numbers:


numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # Output: [2, 4, 6, 8, 10]

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

Lambda Function Example:


● Mapping a list of strings to their lengths:
words = ["apple", "banana", "orange", "kiwi"]
word_lengths = list(map(lambda x: len(x), words))
print(word_lengths) # Output: [5, 6, 6, 4]

● Computing the square of each number in a list:


numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda x: x ** 2, numbers))
print(squared_numbers) # Output: [1, 4, 9, 16, 25]

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

Lambda Function Example:

● Combining two lists element-wise:


list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined = list(map(lambda x, y: x + y, list1, list2))
print(combined) # Output: [5, 7, 9]

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

Why use lambda functions:

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

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

Limitations of lambda functions:


● They are limited to a single expression, which means they cannot contain
multiple statements or complex logic.
● They can sometimes make code harder to understand if overused or used
inappropriately.

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

Module in Python Programming

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

Module in Python Programming:

● In programming, a module is a file containing Python definitions and statements.


● The file name is the module name with the suffix .py appended.
● Within a module, you can define functions, classes, and variables, and you can access these
from other Python files using the import statement.
● Provide proper organization
● Code reusability
● Namespace management
● Encapsulations

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python
Creating Modules:
To create a module, you simply write Python code in a .py file. For example, you can create a
module named mymodule.py containing the following code:
# mymodule.py
def greet(name):
print(f"Hello, {name}!")

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python
Creating Modules:
To create a module, you simply write Python code in a .py file. For example, you can create a
module named mymodule.py containing the following code:
# mymodule.py
def greet(name):
print(f"Hello, {name}!")
Importing Modules:
To use the functions, classes, and variables defined in a module, you import the module into your
Python script using the import statement. For example:

import mymodule
mymodule.greet("Alice") # Output: Hello, Alice!

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

The Math Module:


● The math module in Python provides access to various mathematical functions and
constants.
● These functions and constants enable you to perform mathematical operations more
efficiently and accurately than using regular arithmetic operators.
● The math module is part of the Python Standard Library, which means it's available in
any Python installation without requiring any additional installations.

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

Different functionalities provided by Math Module:


1. Constants:
The math module provides several mathematical constants:
● math.pi: This constant represents the mathematical constant π (pi), which is the ratio of the circumference
of a circle to its diameter (approximately 3.14159).
● math.e: This constant represents the mathematical constant e, the base of natural logarithms (approximately
2.71828).
● math.inf: This constant represents positive infinity.
● math.nan: This constant represents a floating-point "not a number" value.

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

Different functionalities provided by Math Module:


1. Constants:
The math module provides several mathematical constants:
● math.pi: This constant represents the mathematical constant π (pi), which is the ratio of the circumference
of a circle to its diameter (approximately 3.14159).
● math.e: This constant represents the mathematical constant e, the base of natural logarithms (approximately
2.71828).
● math.inf: This constant represents positive infinity.
● math.nan: This constant represents a floating-point "not a number" value.
2. Trigonometric Functions:
● math.sin(x), math.cos(x), math.tan(x): These functions compute the sine, cosine, and tangent of the angle x
(in radians), respectively.
● math.asin(x), math.acos(x), math.atan(x): These functions compute the inverse sine, inverse cosine, and
inverse tangent of x, returning the result in radians.
● math.degrees(x), math.radians(x): These functions convert angles between degrees and radians.

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

Different functionalities provided by Math Module:


3. Exponential and Logarithmic Functions:
● math.exp(x): Returns the exponential of x, which is e raised to the power of x.
● math.log(x, base): Returns the natural logarithm of x (to the given base, default is e).
● math.log10(x): Returns the base-10 logarithm of x.
● math.log2(x): Returns the base-2 logarithm of x.

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

Different functionalities provided by Math Module:


3. Exponential and Logarithmic Functions:
● math.exp(x): Returns the exponential of x, which is e raised to the power of x.
● math.log(x, base): Returns the natural logarithm of x (to the given base, default is e).
● math.log10(x): Returns the base-10 logarithm of x.
● math.log2(x): Returns the base-2 logarithm of x.
4. Power and Root Functions:
● math.pow(x, y): Returns x raised to the power of y.
● math.sqrt(x): Returns the square root of x.
● math.ceil(x): Returns the ceiling of x, which is the smallest integer greater than or equal to x.
● math.floor(x): Returns the floor of x, which is the largest integer less than or equal to x.

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

Different functionalities provided by Math Module:


5. Miscellaneous Functions:
● math.factorial(x): Returns the factorial of x.
● math.gcd(a, b): Returns the greatest common divisor of the integers a and b.
● math.isclose(a, b, rel_tol=1e-09, abs_tol=0.0): Returns True if the values a and b are close to each
other within the specified tolerances.
● math.trunc(x): Returns the truncated integer value of x, i.e., the integer part of x without the
decimal fraction.

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

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

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

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

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

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

# Exponential and Logarithmic functions


● print(math.exp(1)) # Output:
2.718281828459045
● print(math.log(math.e)) # Output: 1.0

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

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

# Exponential and Logarithmic functions


● print(math.exp(1)) # Output:
2.718281828459045
● print(math.log(math.e)) # Output: 1.0

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

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

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

Some important questions from Math Module:


Q. 1: Describe the purpose and functionality of the math module in Python. Explain
why and when it is useful in scientific computing and mathematical operations.

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.

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

String in Python Programming

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

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.

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

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!"""

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

● Single-quoted strings (''):


Single-quoted strings are enclosed within a pair of single quotes. They are useful
for representing string literals that do not contain single quotes within them. For
example:
string1 = 'Hello, World!'

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

● Single-quoted strings (''):


Single-quoted strings are enclosed within a pair of single quotes. They are useful
for representing string literals that do not contain single quotes within them. For
example:
string1 = 'Hello, World!'

● Double-quoted strings (" "):


Double-quoted strings are enclosed within a pair of double quotes. Like
single-quoted strings, they are also used to represent string literals. Double-quoted
strings are useful when the string contains single quotes or apostrophes. For
example:
string2 = "She said, 'Python is awesome!'"

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

● Triple-quoted strings (''' ''' or """ """):


Triple-quoted strings are enclosed within a pair of triple quotes, either single or
double. They are used for creating multiline strings or strings that span multiple
lines. Triple-quoted strings preserve the newline characters (\n) and any indentation
within them. They are particularly useful for docstrings, multiline comments, or
formatting text. For example:

string3 = '''This is a
multiline
string.'''

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

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'

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

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'

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

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

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

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)

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

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.

my_string = " Hello, World! "


print(my_string.strip()) # Output: 'Hello, World!'
print(my_string.lower()) # Output: ' hello, world! '
print(my_string.replace('Hello', 'Hi')) # Output: ' Hi, World! '

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

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'

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

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

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

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.

print('Hello' in 'Hello, World!') # Output: True


print('abc'*3) # Output: 'abcabcabc'

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

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'

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

Question on String

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python
# Define a sample string
sample_string = "Hello, World!"

# Calculate the length of the string


length_of_string = len(sample_string)
print("Length of the string:" , length_of_string)

# Accessing string characters using index


print("First character:" , sample_string[ 0])
print("Last character:" , sample_string[ -1])

# Accessing substring using slicing


print("Substring from index 1 to 4:" , sample_string[ 1:5])
print("Substring from index 7 to end:" , sample_string[ 7:])
print("Substring from beginning to index 5:" , sample_string[: 6])

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python
# Define a sample string
sample_string = "Hello, World!"

# Calculate the length of the string


length_of_string = len(sample_string)
print("Length of the string:" , length_of_string) Length of the string: 13
First character: H
# Accessing string characters using index
print("First character:" , sample_string[ 0]) Last character: !
print("Last character:" , sample_string[ -1]) Substring from index 1 to 4: ello
# Accessing substring using slicing
Substring from index 7 to end: World!
print("Substring from index 1 to 4:" , sample_string[ 1:5]) Substring from beginning to index 5: Hello,
print("Substring from index 7 to end:" , sample_string[ 7:])
print("Substring from beginning to index 5:" , sample_string[: 6])

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

Split and Join of string:


# Define a sample string
sample_string = "Hello, World!"

# Split the string based on whitespace


split_string = sample_string.split()
print("Split string:", split_string)

# Join the split string using a hyphen


joined_string = "-".join(split_string)
print("Joined string:", joined_string)

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

Split and Join of string:


# Define a sample string
sample_string = "Hello, World!"
Split string: ['Hello,', 'World!']
Joined string: Hello,-World!
# Split the string based on whitespace
split_string = sample_string.split()
print("Split string:", split_string)

# Join the split string using a hyphen


joined_string = "-".join(split_string)
print("Joined string:", joined_string)

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

Split string with specific character.

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

Split string with specific character.


# Example string
my_string = "apple,banana,orange,grape"

# Split the string using a comma as the delimiter


split_string = my_string.split(',')

# Print the result


print(split_string)

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

Split string with specific character.


# Example string
my_string = "apple,banana,orange,grape"

# Split the string using a comma as the delimiter


split_string = my_string.split(',')

# Print the result


print(split_string)

Output: ['apple', 'banana', 'orange', 'grape']

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

Question. Write a python to count the number of words in a paragraph.

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

Write a python to count the number of words in a paragraph.


def count_words(paragraph):
# Split the paragraph into words using whitespace as a delimiter
words = paragraph.split()
# Count the number of words
num_words = len(words)
return num_words

# Example paragraph
paragraph = "This is a sample paragraph. It contains some words."

# Count the number of words in the paragraph


word_count = count_words(paragraph)
print("Number of words in the paragraph:", word_count)

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

Write a python to count the number of words in a paragraph.


def count_words(paragraph):
# Split the paragraph into words using whitespace as a delimiter
words = paragraph.split()
# Count the number of words
num_words = len(words)
return num_words

# Example paragraph
paragraph = "This is a sample paragraph. It contains some words."

# Count the number of words in the paragraph


word_count = count_words(paragraph)
print("Number of words in the paragraph:", word_count)

Output: Number of words in the paragraph: 9


Faculty Name: Vimal Singh Department: SCSE
Course Code:R1UC405C Course Name: Programming in Python

Some important questions from string data type:


Q. 1: Describe Describe the concept of strings in Python and explain their significance in programming. Discuss the
immutable nature of strings and their representation as sequences of characters.

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.

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python
Student Grade Calculation:
# Dictionary containing student names as keys and their exam scores as values
student_scores = {
"Alice": 85,
"Bob": 92,
"Charlie": 78,
"David": 88,
"Eve": 95
}

# Calculate average score


total_score = ……………………………………………………………………)
average_score = …………………………………………………………………………)

print("Average score of all students:", average_score)


Course Code:R1UC405C Course Name: Programming in Python
Student Grade Calculation:
# Dictionary containing student names as keys and their exam scores as values
student_scores = {
"Alice": 85,
"Bob": 92,
"Charlie": 78,
"David": 88,
"Eve": 95
}

# Calculate average score


total_score = sum(student_scores.values())
average_score = total_score / len(student_scores)

print("Average score of all students:", average_score)

OUTPUT: Average score of all students: 87.6


Course Code:R1UC405C Course Name: Programming in Python

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.

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

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)

# Call the function to print the dictionary


print_cubes()

Faculty Name: Vimal Singh Department: SCSE


Word count in paragraph also print the maximum
Course Code:R1UC405C count using
Course Name: dictionary:in Python
Programming
# Input paragraph
paragraph = "This is a sample paragraph. It contains some sample words, and it is just for
demonstration purposes."

# Initialize an empty dictionary to store word frequencies


word_freq = {}

# Split paragraph into words and count frequencies


words = ……………………………………………………
for word in words:
word_freq[word] = ………………………………………………………

# Find the word with maximum frequency


max_freq_word = max(..........................)
max_freq = word_freq[.........................]

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


Word count in paragraph:
Course Code:R1UC405C Course Name: Programming in Python
# Input paragraph
paragraph = "This is a sample paragraph. It contains some sample words, and it is just for
demonstration purposes."

# 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

Word with maximum frequency: is (Frequency: 2)


Word count inCourse
paragraph (without special
Code:R1UC405C Coursecharacters):
Name: Programming in Python

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

Word with maximum frequency: is


(Frequency: 2)
Thanks You

You might also like