Shubh Py
Shubh Py
INDORE
INSTITUTE OF ENGINEERING & SCIENCE
COMPUTER SCIENCE & INFORMATION
TECHNOLOGY DEPARTMENT
LAB MANUAL
(2023-24)
(PCC CI02)Programming in PYTHON
Name…..shubh rathore
Class rollno…..98
1
CONTENTS
2
Vision of the Institute
To be the fountain head of novel ideas & innovations in science & technology &
persist to be a foundation of pride for all Indians.
3
to pursue higher studies.
4
societal, and environmental considerations.
PO5. Modern tool usage: Create, select, and apply appropriate techniques,
resources, and modern engineering and IT tools including prediction and modeling
to complex engineering activities with an understanding of the limitations.
PO6. The engineer and society: Apply reasoning informed by the contextual
knowledge to assess societal, health, safety, legal and cultural issues and the
consequent responsibilities relevant to the professional engineering practice.
PO8. Ethics: Apply ethical principles and commit to professional ethics and
responsibilities and norms of the engineering practice.
PO12. Life-long learning: Recognize the need for, and have the preparation and
ability to engage in independent and life-long learning in the broadest context of
technological change
5
⦁ Apply Software Engineering principal and practices to provide software
solutions.
6
INDEX
S.
Experiment Name Date Grade Signature
No.
1. Introduction to python programming and python
datatypes. (CO1)
2. Python program to find the union of two lists.(CO1)
3 Python program to find the intersection of two
lists.(CO1)
4 Python program to remove the“N”the occurrence
of the given word in a list where words repeat.
(CO2)
5 Python program to count the occurrences of each word
in a given string sentence. . (CO2)
6 Pythonprogramtocheckifasubstringispresentina
given string. (CO2)
7 Python program to map two lists into a
dictionary. .(CO3
8 Python program to count the frequency of words
appearing in a string using a dictionary. (CO3)
7
9 Python program to create a dictionary with key as
first
characterandvalueaswordsstartingWiththatcharacter.
.(CO3)
10 Python program to find the length of a list using
recursion.
.(CO4)
11 Python program to read a file and capitalize the first
letter of every word in the file. .(CO5)
12 Python program to read the contents of a file in reverse
order. (CO5)
Experiment 1
⦁ Simple and Easy to Learn: The syntax is clean and the language is
easy to understand.
⦁ Interpreted Language: Python code is executed line
by line, which makes debugging easier.
8
⦁ High-Level Language: You don't need to manage memory and other
low-level details.
⦁ Portable: Python code can run on different platforms without
modification.
⦁ Extensive Libraries: Python has a rich set of libraries and
frameworks that can simplify many tasks.
Python also supports various data types and data structures, including
numbers, strings, lists, tuples, sets, and dictionaries. These built-in
types provide the foundation for data manipulation and storage,
allowing developers to efficiently manage and process information.
⦁ Numbers:
⦁ Integers (int): These are whole numbers without a decimal
point, such as 5, -42, or 1024. Python supports arbitrary-
precision integers, allowing you to work with very large
numbers.
⦁ Floating-point numbers (float): These are numbers with a
decimal point, such as 3.14, -0.001, or 2.71828. Floats
are used to represent real numbers and support scientific
notation.
⦁ Complex numbers (complex): These numbers have a
real part and an imaginary part, represented as a +
bj, where a is the real part and b is the imaginary
part. For example, 3 + 4j is a complex number.
⦁ Strings (str): Strings are sequences of characters, used to
represent text. They are enclosed in single quotes (' ') or
double quotes (" "). For example, 'hello' and "world" are
both strings. Python supports various string operations, such
as concatenation, slicing, and formatting.
⦁ Lists: Lists are ordered, mutable sequences of elements, defined by
square brackets ([
]). They can contain elements of different data types,
including other lists. For example, [1, 2, 3] and ['apple',
'banana', 'cherry'] are lists. Lists support various
operations like indexing, slicing, appending, and
removing elements.
⦁ Tuples: Tuples are ordered, immutable sequences of elements,
defined by parentheses (( )). Like lists, they can contain elements
of different data types. For example, (1, 2, 3) and ('a', 'b', 'c') are
tuples. Since tuples are immutable, their elements cannot be
changed after creation.
10
⦁ Sets: Sets are unordered collections of unique elements, defined by
curly braces ({
}). For example, {1, 2, 3} and {'a', 'b', 'c'} are sets. Sets support
operations like union, intersection, and difference, making them
useful for tasks involving unique elements and membership
testing.
⦁ Dictionaries (dict): Dictionaries are unordered collections of key-
value pairs, defined by curly braces ({ }). Each key must be
unique and immutable (e.g., strings, numbers, or tuples), while
values can be of any data type. For example, {'name': 'Alice',
'age': 30} is a dictionary. Dictionaries support operations like
adding, updating, and removing key-value pairs, and provide
efficient lookups based on keys.
Program to initialize
Python Datatypes :- Code :
my_int = 10
my_float = 10.5
my_string = "Hello, Python!"
my_list = [1, 2, 3, 4, 5]
my_tuple = (1, 2, 3)
my_dict = {"name": "shubh", "age": 25}
my_set = {1, 2, 3, 4, 5}
my_bool = True
my_none = None
11
print(f"Integer: {my_int}")
print(f"Float: {my_float}")
print(f"String: {my_string}")
print(f"List: {my_list}")
print(f"Tuple: {my_tuple}")
print(f"Dictionary: {my_dict}")
print(f"Set: {my_set}")
print(f"Boolean: {my_bool}")
print(f"NoneType: {my_none}")
OUTPUT
Viva Questions :-
⦁ What is a variable in Python?
12
⦁ Arithmetic Operators: Perform basic mathematical
operations like addition (+), subtraction (-),
multiplication (*), division (/), and more.
⦁ Comparison Operators: Compare values and return a
boolean result, such as equal to (==), not equal to (!=),
greater than (>), and less than (<).
⦁ Logical Operators: Combine boolean expressions and
return a boolean result, like and, or, and not.
⦁ Assignment Operators: Assign values to variables,
such as equals (=), plus equals (+=), and minus equals
(-=).
⦁ Bitwise Operators: Perform bit-level operations, like
AND (&), OR (|), XOR (^), and NOT (~).
⦁ Membership Operators: Test for membership in a sequence, like in
and not in.
⦁ Identity Operators: Compare the memory locations of two objects,
like is and is not.
Experiment 2
Aim: Python program to find union of two lists
13
Code:
list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]
OUTPUT
VIVA QUESTIONS
⦁ What is list
Ans- A list in Python is an ordered and mutable collection of
elements. It can hold items of different data types (e.g., integers,
strings, etc.). Lists are created using square brackets [], and items are
indexed starting from 0. Lists allow modification, such as adding,
removing, or changing elements. Since they are mutable, you can
change their contents after creation.
Key Points:
Experiment – 3
Aim: Python program to find intersection of two lists.
Code:
list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]
OUTPUT
15
VIVA QUESTIONS:
Ans- The intersection of two lists refers to the set of elements that
are common to both lists. In other words, it consists of the items that
appear in both lists, without duplication.
Key Points:
16
Experiment – 4
Code :
OUTPUT
17
VIVA QUESTIONS:
Key Points:
⦁ List:
⦁ A list is an ordered, mutable collection that can hold
18
items of different data types.
⦁ Lists are created using square brackets [].
⦁ Lists allow duplicates and support various operations
like adding, removing, and modifying elements.
EXPERIMENT: 5
CODE:
word_count = {}
19
word_count[word] = 1
print(word_count)
OUTPUT
VIVA QUESTIONS:
⦁ What is String?
⦁ Split the string into words: You first need to split the string
into individual words. This can be done using the split() method,
which separates the string by spaces or any other delimiters.
⦁ Normalize the words: To ensure the comparison is case-
insensitive, you can convert the entire string to lowercase using
the lower() method. This ensures that words like "Hello" and
"hello" are treated the same.
⦁ Count the occurrences: After splitting the string into words,
you can count the occurrences of each word using a dictionary
or Python's collections.Counter class. A dictionary would map
each word to its frequency, while Counter automatically counts
the frequency of elements.
EXPERIMENT-06
Code:
OUTPUT
Viva Questions :
What is a substring ?
Ans - A substring is a sequence of characters that appears
consecutively within another string. In simpler terms, a substring is a
portion or a segment of a longer string. For example, if we have the
string "hello world," the substrings could be "hello," "world," "lo wo,"
or even a single character like "h" or "o."
22
EXPERIMENT-07
Code:
print(dictionary)
OUTPUT
Viva Questions :
⦁ what is dictionary in python ?
a colon :
EXPERIMENT-08
Aim: Python program to count the frequency of words
appearing in a string using a dictionary. (CO3)
Code:
string = "apple banana apple orange banana apple grapes"
words = string.split()
24
frequency = {}
print(frequency)
OUTPUT
Viva Questions :
Ans - The split() method in Python is used to split a string into a list
of substrings based on a specified delimiter (separator). In the
provided program, the split() method is called on the input string to
break it down into individual words, which are then stored in a list.
EXPERIMENT-09
Code:
if key in dictionary:
dictionary[key].append(word)
else:
dictionary[key] = [word]
print(dictionary)
output :
26
Viva Questions :
27
EXPERIMENT-10
def list_length(lst):
if not lst:
return 0
return 1 + list_length(lst[1:])
my_list = [1, 8, 9, 7, 5]
print(my_list)
28
print(list_length(my_list))
OUTPUT
Viva Questions :
⦁ what do you mean by recursion ?
29
EXPERIMENT-11
with
open("sample.txt",
"r") as file: content
= file.read()
capitalized_content = " ".join(word.capitalize() for
word in content.split()) print(capitalized_content)
OUTPUT
Viva Questions :
30
Ans - If the specified file does not exist, a FileNotFoundError is raised.
In the provided program, this error is caught by the try...except block,
and the program prints an error
message indicating that the file does not exist. This ensures that the
program handles such exceptions gracefully and informs the user about
the issue.
EXPERIMENT-12
Aim: Python program to read the contents of a file in
reverse order. (CO5)
Code:
with
open("sample.txt
31
= file.readlines()
for line in
reverse
d(lines):
print(lin
e.strip())
OUTPUT
hello
python
class
Viva Questions :
33