Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Pythonfile

Download as pdf or txt
Download as pdf or txt
You are on page 1of 35

INDEX

Date of
S.No. LAB Topics Remarks
Conduct
1 LAB-1 18/01/24
2 LAB-2 25/01/24
3 LAB-3 01/02/24
4 LAB-4 08/02/24
5 LAB-6 15/02/24
6 LAB-7 22/02/24
7 LAB-9.1 14/03/24
8 LAB-9.2 21/03/24
9 LAB-11 04/04/24
10 LAB-12 11/04/24
4/25/24, 7:13 PM Pythonlab1.ipynb - Colab

PYTHON SEM 2 LAB-1

1.Introducing the Python language, Understanding the Python shell.

Python is a high-level, versatile programming language known for its simplicity and readability.
It's widely used in various fields such as web development, data analysis, artificial intelligence,
and more. The Python shell is an interactive environment where you can execute Python code
line by line. To access the Python shell, you can open a terminal or command prompt and type
python. Once inside the shell, you can execute Python statements and see the results
immediately.

2.Development environment setup, Configuring – Installation of Anaconda IDE.

Setting up a development environment is essential for writing and running Python code
efficiently. Anaconda is a distribution of Python that comes bundled with many useful libraries
and tools for data science and scientific computing. To install Anaconda, you can download the
installer from the official website and follow the installation instructions provided. Once installed,
Anaconda provides an integrated development environment (IDE) called Anaconda Navigator,
which allows you to manage packages, environments, and launch applications like Jupyter
Notebook.

3.Introduction to jupyter notebook.

Jupyter Notebook is a web-based interactive computing environment that enables you to create
and share documents containing live code, equations, visualizations, and explanatory text. It
supports various programming languages, including Python, R, and Julia. Jupyter Notebooks are
organized into cells, which can contain either code or markdown text. You can execute code
cells individually and see the output immediately below the cell.

4.Working with jupyter notebook.

To work with Jupyter Notebook, you can launch it from Anaconda Navigator or from the
command line by typing jupyter notebook. This will open a web browser with the Jupyter
dashboard, where you can navigate your files and create new notebooks. To create a new
notebook, click on the "New" button and select "Python 3" (or any other available kernel). You can
then start writing code in the code cells and execute them by pressing Shift + Enter.

5.Writing a simple program.

https://colab.research.google.com/drive/1R4Ccaa3lMO97vWS8HpYWpvcPN2Wet55B?authuser=1#scrollTo=h2_wjJU5d9JJ&printMode=true 1/2
4/25/24, 7:13 PM Pythonlab1.ipynb - Colab

print("Hello, World!")

Hello, World!

https://colab.research.google.com/drive/1R4Ccaa3lMO97vWS8HpYWpvcPN2Wet55B?authuser=1#scrollTo=h2_wjJU5d9JJ&printMode=true 2/2
1/18/24, 6:54 PM pythonlab2.ipynb - Colaboratory

Ques 1)Write a program to demonstrate basic data type in python

a=55
b="pYTHON"
c=921.32
print(type(a))
print(type(b))
print(type(c))

<class 'int'>
<class 'str'>
<class 'float'>

Ques 2)Check whether a number is even or odd

n=int(input("Enter any Number:"))


if(n%2==0):
print("It is even Number")
else:
print("It is odd Number")

output Enter any Number:32


It is even Number

Ques 3)Check whether an entered year is leap year or not

year=int (input("Enter any year:"))


if(year%4==0 and year%100!=0 or year%400==0):
print("It is Leap year")
else:
print("It is not a leap year")

Enter any year:2015


It is not a leap year

Ques 4)WAP to check whether a character is vowel or consonant

ch=input("Enter any Character:")


if(ch=="a" or ch=="e" or ch=="i" or ch=="o" or ch=="u" or ch=="A" or ch=="E" or ch=="I" or ch=="O" or ch=="U"):
print("It is a Vowel")
else:
print("It is a consonant")

Enter any Character:U


It is a Vowel

Ques 5)WAP to find the smallest of two numbers

a=int(input("Enter 1st Number :"))


b=int(input("Enter 2nd Number :"))
if(a>=b):
print(b,"is smallest")
else:
print(a,"is smallest")

Enter 1st Number :92


Enter 2nd Number :91
91 is smallest

Ques 6)Find Factorial of a Number

a=int(input("Enter any number"))


fact=1
for i in range(1,a+1):
fact=fact*i
print("Factorial of",a , "is",fact)

Enter any number5


Factorial of 5 is 120

Ques 7)WAP to print the pattern :

https://colab.research.google.com/drive/1dlcBY2XeUrcjJiyYLq1iJQokXzJOSwsC#printMode=true 1/3
1/18/24, 6:54 PM pythonlab2.ipynb - Colaboratory
n = 4
k = n - 1
for i in range(0, n):
for j in range(0, k):
print(end=" ")
k = k - 1
for j in range(0, i+1):
print("* ", end="")
print("\r")

*
* *
* * *
* * * *

Ques 8)WAP to print this series : 1 1 2 3 5 8 13

a,b=1,1
i=0
print("Series is:")
for i in range(1,8):
print(a,end=" ")
sum=a+b
a=b
b=sum

Series is:
1 1 2 3 5 8 13

Ques 9)Check whether a number is prime or not

num = int(input("Enter any Number:"))


if num > 1:
for i in range(2, int(num/2)+1):
if (num % i) == 0:
print(num, "is not a prime number")
break
else:
print(num, "is a prime number")
else:
print(num, "is not a prime number")

Enter any Number:54


54 is not a prime number

Ques 10)Make a Simple Calculator.

num1 = float(input("Enter first number: "))


num2 = float(input("Enter second number: "))
operator = input("Enter operator (+, -, *, /): ")
if operator == '+':
result = num1+num2
elif operator == '-':
result = num1-num2
elif operator == '*':
result = num1*num2
elif operator == '/':
if num2 != 0:
result = num1/num2
else:
print("Cannot divide by zero")
else:
print("Invalid Operator")
print(result)

Enter first number: 83


Enter second number: 12
Enter operator (+, -, *, /): +
95.0

https://colab.research.google.com/drive/1dlcBY2XeUrcjJiyYLq1iJQokXzJOSwsC#printMode=true 2/3
1/18/24, 6:54 PM pythonlab2.ipynb - Colaboratory

https://colab.research.google.com/drive/1dlcBY2XeUrcjJiyYLq1iJQokXzJOSwsC#printMode=true 3/3
1/18/24, 8:10 PM pythonlab3.ipynb - Colaboratory

Ques 1)Write a python program to swap two numbers using a third variable

a=int(input("Enter 1st number:"))


b=int(input("Enter 2nd number:"))
print("Numbers before swaping:")
print(a,b)
c=a
a=b
b=c
print("Numbers after swaping:")
print(a,b)

Enter 1st number:32


Enter 2nd number:21
Numbers before swaping:
32 21
Numbers after swaping:
21 32

Ques 2)Write a python program to swap two numbers without using third variable
Code Text
a=int(input("Enter 1st number:"))
b=int(input("Enter 2nd number:"))
print("Numbers before swaping:")
print(a,b)
a=a+b
b=a-b
a=a-b
print("Numbers after swaping:")
print(a,b)

Enter 1st number:212


Enter 2nd number:43
Numbers before swaping:
212 43
Numbers after swaping:
43 212

Ques 3)Write a python program to read two numbers and find the sum of their cubes

a=int(input("Enter 1st number:"))


b=int(input("Enter 2nd number:"))
cub1=a**3
cub2=b**3
print(cub1+cub2)

Enter 1st number:4


Enter 2nd number:6
280

Ques 4)Write a python program to read three numbers and if any two variables are equal, print that number

num1 = float(input("Enter the first number: "))


num2 = float(input("Enter the second number: "))
num3 = float(input("Enter the third number: "))
if num1 == num2:
print(num1,"and",num2,"are equal")
elif num1 == num3:
print(num1,"and",num3,"are equal")
elif num2 == num3:
print(num2,"and",num3,"are equal")
else:
print("No two numbers are equal.")

Enter the first number: 834


Enter the second number: 19
Enter the third number: 6
No two numbers are equal.

Ques 5)Write a python program to read three numbers and find the smallest among them

a=float(input("Enter 1st number"))


b=float(input("Enter 2nd number"))
c=float(input("Enter 3rd number"))
if a<=b:
if a<=c:
https://colab.research.google.com/drive/1UW9VwZHFQflgC2D4pVXvCrx56k_4AfWw#printMode=true 1/3
1/18/24, 8:10 PM pythonlab3.ipynb - Colaboratory
if a< c:
print(a,"is smallest")
else:
print(c,"is smallest")
elif b<=c:
if b<=a:
print(b,"is smallest")
else:
print(a,"is smallest")
elif c<=a:
if c<=b:
print(c,"is smallest")
else:
print(b,"is smallest")

Enter 1st number21


Enter 2nd number67
Enter 3rd number90
21.0 is smallest

Ques 6)Write a python program to read three numbers and print them in ascending order (without using sort function)

num1 = float(input("Enter the first number: "))


num2 = float(input("Enter the second number: "))
num3 = float(input("Enter the third number: "))
if num1 <= num2 <= num3:
print("The numbers in ascending order are:",num1,num2,num3)
elif num1 <= num3 <= num2:
print("The numbers in ascending order are:",num1,num3,num2)
elif num2 <= num1 <= num3:
print("The numbers in ascending order are:",num2,num1,num3)
elif num2 <= num3 <= num1:
print("The numbers in ascending order are:",num2,num3,num1)
elif num3 <= num1 <= num2:
print("The numbers in ascending order are:",num3,num1,num2)
else:
print("The numbers in ascending order are:",num3,num2,num1)

Enter the first number: 23


Enter the second number: 97
Enter the third number: 100
The numbers in ascending order are: 23.0 97.0 100.0

Ques 7)Write a python program to read radius of a circle and print the area

pi=3.14
r=float(input("Enter the radius"))
print("Area of the circle is",pi*r*r)

Enter the radius8


Area of the circle is 200.96

Ques 8)Write a python program to read a number ,if it is an even number , print the square of that number and if it is odd number print cube of
that number.

n=int(input("Enter the number"))


if(n%2==0):
print("Square of number is:",n**2)
else:
print("Cube of number is:",n**3)

Enter the number9


Cube of number is: 729

https://colab.research.google.com/drive/1UW9VwZHFQflgC2D4pVXvCrx56k_4AfWw#printMode=true 2/3
1/18/24, 8:10 PM pythonlab3.ipynb - Colaboratory

https://colab.research.google.com/drive/1UW9VwZHFQflgC2D4pVXvCrx56k_4AfWw#printMode=true 3/3
2/15/24, 5:39 PM pythonlan6.ipynb - Colaboratory

PYTHON SEM2 LAB6

1. WAP to demonstrate while loop with else statement.

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


while count < 5:
print("Count is:", count)
count += 1
else:
print("Count is not less than 5 anymore.")

Enter a number:2
Count is: 2
Count is: 3
Count is: 4
Count is not less than 5 anymore.

2.Print 1st 5 even numbers (use break statement).

number = 0
count = 0
while True:
if number % 2 == 0:
print(number)
count += 1
if count == 5:
break
number += 1

output 0
2
4
6
8

3.Print 1st 4 even numbers (use continue statement).

number = 0
count = 0
while count < 4:
number += 1
if number % 2 != 0:
continue
print(number)
count += 1

2
4
6
8

4.WAP to demonstrate Pass statements.

for i in range(10):
if i == 3:
pass
print(i)

0
1
2
3
4
5
6
7
8
9

5.Write a Python program to calculate the length of a string.

string = input("Enter a string: ")


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

https://colab.research.google.com/drive/1c93e78x4Ykfsi_T93L1e8H67aWWdkMgL#scrollTo=qJzrrHNFsnlC&printMode=true 1/3
2/15/24, 5:39 PM pythonlan6.ipynb - Colaboratory

Enter a string: MAYANK


Length of the string: 6

6. Write a Python program to count the number of characters (character frequency) in a string

string = input("Enter a string: ")


char_freq = {}
for char in string:
if char in char_freq:
char_freq[char] += 1
else:
char_freq[char] = 1
print("Character frequency in the string:")
for char, freq in char_freq.items():
print(char,":",freq)

Enter a string: HELLO PYTHON


Character frequency in the string:
H : 2
E : 1
L : 2
O : 2
: 1
P : 1
Y : 1
T : 1
N : 1

7. Write a Python program to get a string made of the first 2 and the last 2 chars from a given a string. If the string length is less than 2,
return instead of the empty string.

input_string = input("Enter a string: ")


if len(input_string) < 2:
result_string = ""
else:
first_two_chars = input_string[:2]
last_two_chars = input_string[-2:]
result_string = first_two_chars + last_two_chars
print("Result:", result_string)

Enter a string: PYTHON WORLD


Result: PYLD

8. Write a Python program to get a string from a given string where all occurrences of its first char have been changed to '$', except the first
char itself

input_string = input("Enter a string: ")


first_char = input_string[0]
modified_string = first_char + input_string[1:].replace(first_char, '$')
print("Modified string:", modified_string)

Enter a string: madam


Modified string: mada$

9.Write a Python program to get a single string from two given strings, separated by a space and swap the first two characters of each string.

string1 = input("Enter the first string: ")


string2 = input("Enter the second string: ")
new_string1 = string2[:2] + string1[2:]
new_string2 = string1[:2] + string2[2:]
result_string = new_string1 + " " + new_string2
print("Result:", result_string)

Enter the first string: hello


Enter the second string: world
Result: wollo herld

10. Write a Python program to add 'ing' at the end of a given string (length should be at least 3). If the given string already ends with 'ing' then
add 'ly' instead. If the string length of the given string is less than 3, leave it unchanged.

https://colab.research.google.com/drive/1c93e78x4Ykfsi_T93L1e8H67aWWdkMgL#scrollTo=qJzrrHNFsnlC&printMode=true 2/3
2/15/24, 5:39 PM pythonlan6.ipynb - Colaboratory
input_string = input("Enter a string: ")
if len(input_string) >= 3:
if input_string.endswith("ing"):
modified_string = input_string + "ly"
else:
modified_string = input_string + "ing"
else:
modified_string = input_string
print("Modified string:", modified_string)

Enter a string: eat


Modified string: eating

https://colab.research.google.com/drive/1c93e78x4Ykfsi_T93L1e8H67aWWdkMgL#scrollTo=qJzrrHNFsnlC&printMode=true 3/3
2/15/24, 6:11 PM lab7.ipynb - Colaboratory

Python Sem 2 Lab 7

keyboard_arrow_down TUPLE
1. Write a Python program to create a tuple.

# Program to create a tuple


my_tuple = (1, 2, 3, 4, 5)
print(my_tuple)

(1, 2, 3, 4, 5)

2. Write a Python program to create a tuple with different data types.

# Program to create a tuple with different data types


mixed_tuple = (1, "Hello", 3.14, True)
print(mixed_tuple)

(1, 'Hello', 3.14, True)

3. Write a Python program to create a tuple with numbers and print one item

# Program to create a tuple with numbers and print one item


number_tuple = (10, 20, 30, 40, 50)
print("One item from the tuple:", number_tuple[2])

One item from the tuple: 30

4. Write a Python program to unpack a tuple in several variables.

# Program to unpack a tuple into several variables


my_tuple = (1, 2, 3)
a, b, c = my_tuple
print("Unpacked variables:", a, b, c)

Unpacked variables: 1 2 3

5. Write a Python program to add an item in a tuple.

# Program to add an item in a tuple


original_tuple = (1, 2, 3)
new_tuple = original_tuple + (4,)
print("Original tuple:", original_tuple)
print("Tuple after adding item:", new_tuple)

Original tuple: (1, 2, 3)


Tuple after adding item: (1, 2, 3, 4)

6. Write a Python program to convert a tuple to a string.

# Program to convert a tuple to a string


my_tuple = ('a', 'b', 'c', 'd', 'e')
tuple_str = ''.join(my_tuple)
print("Tuple converted to string:", tuple_str)

Tuple converted to string: abcde

7. Write a Python program to get the 4th element and 4th element from last of a tuple

# Program to get the 4th and 4th element from the last of a tuple
my_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9)
fourth_element = my_tuple[3]
fourth_from_last = my_tuple[-4]
print("4th element:", fourth_element)
print("4th element from last:", fourth_from_last)

4th element: 4
4th element from last: 6

https://colab.research.google.com/drive/1C1Aj5Byux4STAuiyRdmdumd39fI-_0qh#scrollTo=v0IGnB_zxm8A&printMode=true 1/5
2/15/24, 6:11 PM lab7.ipynb - Colaboratory

8. Write a Python program to create the colon of a tuple.

# Program to create the colon of a tuple


original_tuple = (1, 2, 3, 4, 5)
colon_tuple = original_tuple[:]
print("Colon of the tuple:", colon_tuple)

Colon of the tuple: (1, 2, 3, 4, 5)

9. Write a Python program to find the repeated items of a tuple.

# Program to find the repeated items of a tuple


my_tuple = (1, 2, 3, 4, 2, 3, 5, 6, 7, 3)
repeated_items = set(item for item in my_tuple if my_tuple.count(item) > 1)
print("Repeated items in the tuple:", repeated_items)

Repeated items in the tuple: {2, 3}

10. Write a Python program to check whether an element exists within a tuple.

# Program to check whether an element exists within a tuple


my_tuple = (1, 2, 3, 4, 5)
element = 3
if element in my_tuple:
print(element,"exists in the tuple.")
else:
print(element,"does not exist in the tuple.")

3 exists in the tuple.

11. Write a Python program to convert a list to a tuple.

# Program to convert a list to a tuple


my_list = [1, 2, 3, 4, 5]
my_tuple = tuple(my_list)
print("Converted tuple:", my_tuple)

Converted tuple: (1, 2, 3, 4, 5)

12. Write a Python program to remove an item from a tuple.

# Program to remove an item from a tuple


my_tuple = (1, 2, 3, 4, 5)
item_to_remove = 3
temp_list = list(my_tuple)
temp_list.remove(item_to_remove)
new_tuple = tuple(temp_list)
print("Tuple after removing item:", new_tuple)

Tuple after removing item: (1, 2, 4, 5)

13. Write a Python program to slice a tuple

# Program to slice a tuple


my_tuple = (1, 2, 3, 4, 5)
sliced_tuple = my_tuple[2:4]
print("Sliced tuple:", sliced_tuple)

Sliced tuple: (3, 4)

14. Write a Python program to find the index of an item of a tuple.

# Program to find the index of an item of a tuple


my_tuple = (1, 2, 3, 4, 5)
item = 3
index = my_tuple.index(item)
print("Index of item", item, ":", index)

Index of item 3 : 2

https://colab.research.google.com/drive/1C1Aj5Byux4STAuiyRdmdumd39fI-_0qh#scrollTo=v0IGnB_zxm8A&printMode=true 2/5
2/15/24, 6:11 PM lab7.ipynb - Colaboratory

15. Write a Python program to find the length of a tuple.

# Program to find the length of a tuple


my_tuple = (1, 2, 3, 4, 5)
length = len(my_tuple)
print("Length of the tuple:", length)

Length of the tuple: 5

keyboard_arrow_down LIST
1. Write a Python program to sum all the items in a list.

my_list = [1, 2, 3, 4, 5]
total = 0
for item in my_list:
total += item
print("Sum of list items:", total)

Sum of list items: 15

2. Write a Python program to multiplies all the items in a list.

my_list = [1, 2, 3, 4, 5]
result = 1
for item in my_list:
result *= item
print("Product of list items:", result)

Product of list items: 120

3. Write a Python program to get the largest number from a list

my_list = [1, 2, 3, 4, 5]
largest = max(my_list)
print("Largest number in list:", largest)

Largest number in list: 5

4. Write a Python program to get the smallest number from a list.

my_list = [1, 2, 3, 4, 5]
smallest = min(my_list)
print("Smallest number in list:", smallest)

Smallest number in list: 1

5. Write a Python program to count the number of strings where the string length is 2 or more and the first and last character are same from a
given list of strings

Sample List : ['abc', 'xyz', 'aba', '1221']

Expected Result : 2

# Sample List
sample_list = ['abc', 'xyz', 'aba', '1221']

# Initialize count
count = 0

# Iterate through each string in the list


for string in sample_list:
# Check if the string length is 2 or more and the first and last character are the same
if len(string) >= 2 and string[0] == string[-1]:
count += 1

# Print the count


print("Expected Result:", count)

Expected Result: 2

https://colab.research.google.com/drive/1C1Aj5Byux4STAuiyRdmdumd39fI-_0qh#scrollTo=v0IGnB_zxm8A&printMode=true 3/5
2/15/24, 6:11 PM lab7.ipynb - Colaboratory

6. Write a Python program to get a list, sorted in increasing order by the last element in each tuple from a given list of non-empty tuples.

Sample List : [(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)]

Expected Result : [(2, 1), (1, 2), (2, 3), (4, 4), (2, 5)]

# Sample List
sample_list = [(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)]

# Sort the list based on the last element of each tuple


sample_list.sort(key=lambda x: x[-1])

# Print the sorted list


print("Expected Result:", sample_list)

Expected Result: [(2, 1), (1, 2), (2, 3), (4, 4), (2, 5)]

7. Write a Python program to remove duplicates from a list.

my_list = [1, 2, 3, 4, 2, 3, 5]
unique_list = []
for item in my_list:
if item not in unique_list:
unique_list.append(item)
print("List after removing duplicates:", unique_list)

List after removing duplicates: [1, 2, 3, 4, 5]

8. Write a Python program to check a list is empty or not.

my_list = []
if not my_list:
print("List is empty")
else:
print("List is not empty")

List is empty

9. Write a Python program to clone or copy a list.

original_list = [1, 2, 3, 4, 5]
cloned_list = original_list[:]
print("Cloned list:", cloned_list)

Cloned list: [1, 2, 3, 4, 5]

10. Write a Python program to find the list of words that are longer than n from a given list of words.

word_list = ['apple', 'banana', 'grape', 'kiwi', 'orange']


n = 4
long_words = [word for word in word_list if len(word) > n]
print("Words longer than", n, "characters:", long_words)

Words longer than 4 characters: ['apple', 'banana', 'grape', 'orange']

11. Write a Python function that takes two lists and returns True if they have at least one common member.

list1 = [1, 2, 3, 4, 5]
list2 = [6, 7, 8, 9, 10]
common_member = False
for item in list1:
if item in list2:
common_member = True
break
print("Do the lists have at least one common member?", common_member)

Do the lists have at least one common member? False

12. Write a Python program to print a specified list after removing the 0th, 4th and 5th elements.

Sample List : ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow']

Expected Output : ['Green', 'White', 'Black']

https://colab.research.google.com/drive/1C1Aj5Byux4STAuiyRdmdumd39fI-_0qh#scrollTo=v0IGnB_zxm8A&printMode=true 4/5
2/15/24, 6:11 PM lab7.ipynb - Colaboratory

# Sample List
sample_list = ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow']

# Remove elements at specified positions


sample_list.pop(5)
sample_list.pop(4)
sample_list.pop(0)

# Print the modified list


print("Expected Output:", sample_list)

output Expected Output: ['Green', 'White', 'Black']

https://colab.research.google.com/drive/1C1Aj5Byux4STAuiyRdmdumd39fI-_0qh#scrollTo=v0IGnB_zxm8A&printMode=true 5/5
2/22/24, 10:00 PM Lab 9.1 Object-Oriented Programming.ipynb - Colaboratory

Python Sem 2 Lab-9.1

1. Write a Python program that create a class triangle and define two methods, create_triangle() and print_sides().

class Triangle:
def _init_(self):
self.sides = []

def create_triangle(self):
self.sides = [float(input("Enter side "+str(i+1)+": ")) for i in range(3)]

def print_sides(self):
print("Sides of the triangle are:", self.sides)
# Example usage:
triangle = Triangle()
triangle.create_triangle()
triangle.print_sides()

output Enter
Enter
side 1: 4
side 2: 6
Enter side 3: 1
Sides of the triangle are: [4.0, 6.0, 1.0]

2. Write a Python program to create a class with two methods get_String() and print_String().

class StringManipulator:
def __init__(self):
self.string = ""

def get_String(self):
self.string = input("Enter a string: ")

def print_String(self):
print("String:", self.string)

# Create an instance of the class


s = StringManipulator()
s.get_String()
s.print_String()

Enter a string: python


String: python

3. Write a Python program to create a class Rectangle that takes the parameter length and width. The class should also contain a method for
computing its perimeter.

class Rectangle:
def __init__(self, length, width):
self.length = length
self.width = width

def perimeter(self):
return 2 * (self.length + self.width)

# Create an instance of the class


rect = Rectangle(5, 4)
print("Perimeter of rectangle:", rect.perimeter())

Perimeter of rectangle: 18

4. Write a Python program to create a class Circle that takes the parameter radius. The class should also contain two methods for computing
its area & perimeter respectively. Use constructor to implement initialization of parameters

https://colab.research.google.com/drive/1z_dZFlKw-nN3v2-I55BFKOxzvWOkLZU8#scrollTo=o9RG6QkB4VTS&printMode=true 1/4
2/22/24, 10:00 PM Lab 9.1 Object-Oriented Programming.ipynb - Colaboratory
import math

class Circle:
def __init__(self, radius):
self.radius = radius

def area(self):
return math.pi * self.radius ** 2

def perimeter(self):
return 2 * math.pi * self.radius

# Create an instance of the class


cir = Circle(5)
print("Area of circle:", cir.area())
print("Perimeter of circle:", cir.perimeter())

Area of circle: 78.53981633974483


Perimeter of circle: 31.41592653589793

5.Create a Cricle class and intialize it with radius. Make two methods getArea and getCircumference inside this class.

import math

class Circle:
def __init__(self, radius):
self.radius = radius

def getArea(self):
return math.pi * self.radius ** 2

def getCircumference(self):
return 2 * math.pi * self.radius

# Create an instance of the class


cir = Circle(4)
print("Area of circle:", cir.getArea())
print("Circumference of circle:", cir.getCircumference())

Area of circle: 50.26548245743669


Circumference of circle: 25.132741228718345

6. Create a Temprature class. Make two methods :

1. convertFahrenheit - It will take celsius and will print it into Fahrenheit.

2. convertCelsius - It will take Fahrenheit and will convert it into Celsius.

class Temperature:
def convertFahrenheit(self, celsius):
fahrenheit = (celsius * 9/5) + 32
print(f"{celsius} degrees Celsius is equal to {fahrenheit} degrees Fahrenheit.")

def convertCelsius(self, fahrenheit):


celsius = (fahrenheit - 32) * 5/9
print(f"{fahrenheit} degrees Fahrenheit is equal to {celsius} degrees Celsius.")

# Create an instance of the class


temp = Temperature()
temp.convertFahrenheit(37) # Convert 37 degrees Celsius to Fahrenheit
temp.convertCelsius(98.6) # Convert 98.6 degrees Fahrenheit to Celsius

37 degrees Celsius is equal to 98.6 degrees Fahrenheit.


98.6 degrees Fahrenheit is equal to 37.0 degrees Celsius.

7. Create a Student class and initialize it with name and roll number. Make methods to :

1. Display - It should display all informations of the student.

2. setAge - It should assign age to student

3. setMarks - It should assign marks to the student.

https://colab.research.google.com/drive/1z_dZFlKw-nN3v2-I55BFKOxzvWOkLZU8#scrollTo=o9RG6QkB4VTS&printMode=true 2/4
2/22/24, 10:00 PM Lab 9.1 Object-Oriented Programming.ipynb - Colaboratory
class Student:
def __init__(self, name, roll_number):
self.name = name
self.roll_number = roll_number
self.age = None
self.marks = None

def display(self):
print("Name:", self.name)
print("Roll Number:", self.roll_number)
if self.age is not None:
print("Age:", self.age)
else:
print("Age not set.")
if self.marks is not None:
print("Marks:", self.marks)
else:
print("Marks not set.")

def setAge(self, age):


self.age = age

def setMarks(self, marks):


self.marks = marks

# Create an instance of the class


student = Student("John", 101)

# Display initial information


print("Initial Information:")
student.display()

# Set age and marks


student.setAge(20)
student.setMarks(85)

# Display updated information


print("\nUpdated Information:")
student.display()

Initial Information:
Name: John
Roll Number: 101
Age not set.
Marks not set.

Updated Information:
Name: John
Roll Number: 101
Age: 20
Marks: 85

8. Create a Time class and initialize it with hours and minutes.

1. Make a method addTime which should take two time object and add them. E.g.- (2 hour and 50 min)+(1 hr and 20 min) is (4 hr and 10 min)

2. Make a method displayTime which should print the time.

3. Make a method DisplayMinute which should display the total minutes in the Time. E.g.- (1 hr 2 min) should display 62 minute.

https://colab.research.google.com/drive/1z_dZFlKw-nN3v2-I55BFKOxzvWOkLZU8#scrollTo=o9RG6QkB4VTS&printMode=true 3/4
2/22/24, 10:00 PM Lab 9.1 Object-Oriented Programming.ipynb - Colaboratory
class Time:
def __init__(self, hours, minutes):
self.hours = hours
self.minutes = minutes

def addTime(self, t1, t2):


self.hours = t1.hours + t2.hours
self.minutes = t1.minutes + t2.minutes
if self.minutes >= 60:
self.hours += self.minutes // 60
self.minutes %= 60

9. Write a Python class to reverse a string word by word.


def displayTime(self):
print(f"Time: {self.hours} hours and {self.minutes} minutes")

class StringReverser:
def displayMinute(self):
def reverse_words(self, string):
total_minutes = self.hours * 60 + self.minutes
# Split the string into words
print(f"Total minutes: {total_minutes} minutes")
words = string.split()
# Create instances of the class
# Reverse the list of words
time1 = Time(2, 50)
reversed_words = words[::-1]
time2 = Time(1, 20)

# Join the reversed words back into a string


# Add times
reversed_string = ' '.join(reversed_words)
time3 = Time(0, 0)
time3.addTime(time1, time2)
return reversed_string
# Display time and total minutes
# Create an instance of the class
time3.displayTime()
reverser = StringReverser()
time3.displayMinute()

# Test the method


Time: 4 hours and 10 minutes
input_string = "Hello
Total minutes: world"
250 minutes
reversed_string = reverser.reverse_words(input_string)
print("Original string:", input_string)
print("Reversed string word by word:", reversed_string)

Original string: Hello world


Reversed string word by word: world Hello

https://colab.research.google.com/drive/1z_dZFlKw-nN3v2-I55BFKOxzvWOkLZU8#scrollTo=o9RG6QkB4VTS&printMode=true 4/4
3/9/24, 7:40 PM Lab-9.2: Object-Oriented Programming - Class Inheritance & Method Overriding.ipynb - Colaboratory

PYTHON SEM2 LAB 9.2

1. Write a Python program that has a class Animal with a method legs(). Create two subclasses Tiger and Dog, access the method leg
explicitly with class Dog and implicitly with the class Tiger.

class Animal:
def legs(self):
print("This animal has 4 legs")
class Tiger(Animal):
pass
class Dog(Animal):
def legs(self):
print("This animal has 4 legs (explicit access)")
tiger = Tiger()
tiger.legs() # Implicit access
dog = Dog()
dog.legs() # Explicit access

This animal has 4 legs


This animal has 4 legs (explicit access)

2. Write a Python program to create a class Employee. Define two subclasses: Engineer and Manager. Every class should have method named
printDesignation() that prints Engineer for Engineer class and Manager for Manager Class.

class Employee:
def printDesignation(self):
pass
class Engineer(Employee):
def printDesignation(self):
print("Engineer")
class Manager(Employee):
def printDesignation(self):
print("Manager")
engineer = Engineer()
engineer.printDesignation()
manager = Manager()
manager.printDesignation()

Engineer
Manager

3. Write a Python program to demonstrate classes and their attributes.

class Person:
def __init__(self, name, age):
self.name = name
self.age = age
person1 = Person("Alice", 30)
person2 = Person("Bob", 25)
print(person1.name, person1.age)
print(person2.name, person2.age)

Alice 30
Bob 25

4. Write a Python program to demonstrate Inheritance and method overriding.

class Parent:
def show(self):
print("Parent method")
class Child(Parent):
def show(self):
print("Child method")
obj = Child()
obj.show() # This will print "Child method"

Child method

5. Write a Python program to demonstrate multiple Inheritance.

class Class1:
def method1(self):
print("Method 1")

https://colab.research.google.com/drive/1AfX5JFL5mV-GpCYx2fi7Fp9A9q7nHI07?authuser=1#scrollTo=zhS1JrZMiX3p&printMode=true 1/2
3/9/24, 7:40 PM Lab-9.2: Object-Oriented Programming - Class Inheritance & Method Overriding.ipynb - Colaboratory
class Class2:
def method2(self):
print("Method 2")
class Class3(Class1, Class2):
pass
obj = Class3()
obj.method1()
obj.method2()

Method 1
Method 2

https://colab.research.google.com/drive/1AfX5JFL5mV-GpCYx2fi7Fp9A9q7nHI07?authuser=1#scrollTo=zhS1JrZMiX3p&printMode=true 2/2
4/25/24, 8:48 PM Lab11.ipynb - Colab

PYTHON SEM 2 LAB-11

1. Write a Python program to read an entire text file.

#Upload files to Google Colab environment by running this cell and selecting the files:
from google.colab import files
uploaded = files.upload()

def read_file(filename):
with open(filename, 'r') as file:
text = file.read()
return text

filename = 'python.txt'
print(read_file(filename))

output Choose Files python.txt


python.txt(text/plain) - 510 bytes, last modified: 4/25/2024 - 100% done
Saving python.txt to python (1).txt
Python is a high-level programming language renowned for its simplicity, readability, and
versatility. It finds applications across various domains, including web development, data
analysis, machine learning, and scientific computing. The Python shell serves as an interactive
interface for executing Python code. To access the Python shell, simply open a terminal or
command prompt and type python. Within the shell, users can execute Python commands,
statements, and scripts, observing immediate results

2. Write a Python program to read a file line by line and store it into a list.

#upload files to Google Colab environment by running this cell and selecting the files:
from google.colab import files
uploaded = files.upload()

def read_lines_to_list(filename):
with open(filename, 'r') as file:
lines = file.readlines()
return lines

filename = 'python.txt'
print(read_lines_to_list(filename))

Choose Files python.txt


python.txt(text/plain) - 510 bytes, last modified: 4/25/2024 - 100% done
Saving python.txt to python (2).txt
['Python is a high-level programming language renowned for its simplicity, readabilit

3. Write a Python program to read a file line by line store it into a variable.

#upload files to Google Colab environment by running this cell and selecting the files:
from google.colab import files
uploaded = files.upload()
def read_lines_to_variable(filename):
with open(filename, 'r') as file:
content = file.read()
return content

filename = 'python.txt'
content = read_lines_to_variable(filename)
print(content)

Choose Files python.txt


python.txt(text/plain) - 510 bytes, last modified: 4/25/2024 - 100% done
Saving python.txt to python (5).txt
Python is a high-level programming language renowned for its simplicity, readability,
versatility. It finds applications across various domains, including web development,
analysis, machine learning, and scientific computing. The Python shell serves as an i
interface for executing Python code. To access the Python shell, simply open a termin
command prompt and type python. Within the shell, users can execute Python commands,

4. Write a Python program to read a file line by line store it into an array.

https://colab.research.google.com/drive/16_biU4L8qDENyPowQ3TRVpZKh532dZJs?authuser=1#scrollTo=CrQuISGfhFqL&printMode=true 1/5
4/25/24, 8:48 PM Lab11.ipynb - Colab

#upload files to Google Colab environment by running this cell and selecting the files:
from google.colab import files
uploaded = files.upload()
def read_lines_to_array(filename):
with open(filename, 'r') as file:
lines = file.readlines()
return [line.strip() for line in lines]

filename = 'python.txt'
print(read_lines_to_array(filename))

Choose Files python.txt


python.txt(text/plain) - 510 bytes, last modified: 4/25/2024 - 100% done
Saving python.txt to python (6).txt
['Python is a high-level programming language renowned for its simplicity, readabilit

5. Write a python program to find the longest words.

#upload files to Google Colab environment by running this cell and selecting the files:
from google.colab import files
uploaded = files.upload()
def find_longest_words(filename):
with open(filename, 'r') as file:
words = file.read().split()
max_length = len(max(words, key=len))
return [word for word in words if len(word) == max_length]

filename = 'python.txt'
print(find_longest_words(filename))

Choose Files python.txt


python.txt(text/plain) - 510 bytes, last modified: 4/25/2024 - 100% done
Saving python.txt to python (7).txt
['readability,', 'versatility.', 'applications', 'development,']

6. Write a Python program to count the number of lines in a text file.

#upload files to Google Colab environment by running this cell and selecting the files:
from google.colab import files
uploaded = files.upload()
def count_lines(filename):
with open(filename, 'r') as file:
line_count = sum(1 for line in file)
return line_count

filename = 'python.txt'
print(count_lines(filename))

Choose Files python.txt


python.txt(text/plain) - 510 bytes, last modified: 4/25/2024 - 100% done
Saving python.txt to python (9).txt
6

7. Write a Python program to count the frequency of words in a file.

#upload files to Google Colab environment by running this cell and selecting the files:
from google.colab import files
uploaded = files.upload()
from collections import Counter

def count_word_frequency(filename):
with open(filename, 'r') as file:
words = file.read().split()
return Counter(words)

filename = 'python.txt'
print(count_word_frequency(filename))

Choose Files python.txt


python.txt(text/plain) - 510 bytes, last modified: 4/25/2024 - 100% done
Saving python.txt to python (8).txt
Counter({'Python': 5, 'and': 4, 'a': 2, 'for': 2, 'the': 2, 'shell,': 2, 'is': 1, 'hi

https://colab.research.google.com/drive/16_biU4L8qDENyPowQ3TRVpZKh532dZJs?authuser=1#scrollTo=CrQuISGfhFqL&printMode=true 2/5
4/25/24, 8:48 PM Lab11.ipynb - Colab

8. Write a Python program to get the file size of a plain file.

#upload files to Google Colab environment by running this cell and selecting the files:
from google.colab import files
uploaded = files.upload()
import os

def get_file_size(filename):
return os.path.getsize(filename)

filename = 'python.txt'
print(get_file_size(filename))

Choose Files python.txt


python.txt(text/plain) - 510 bytes, last modified: 4/25/2024 - 100% done
Saving python.txt to python (10).txt
510

9. Write a Python program to write a list to a file.

#upload files to Google Colab environment by running this cell and selecting the files:
from google.colab import files
uploaded = files.upload()
def write_list_to_file(filename, data):
with open(filename, 'w') as file:
for item in data:
file.write(str(item) + '\n')

filename = 'python.txt'
data = [1, 2, 3, 4, 5]
write_list_to_file(filename, data)

Choose Files python.txt


python.txt(text/plain) - 510 bytes, last modified: 4/25/2024 - 100% done
Saving python.txt to python (11).txt

10. Write a Python program to copy the contents of a file to another file.

#upload files to Google Colab environment by running this cell and selecting the files:
from google.colab import files
uploaded = files.upload()
def copy_file(source, destination):
with open(source, 'r') as src_file:
with open(destination, 'w') as dest_file:
dest_file.write(src_file.read())

source_file = 'python.txt'
destination_file = 'doc.txt'
copy_file(source_file, destination_file)

Choose Files python.txt


python.txt(text/plain) - 510 bytes, last modified: 4/25/2024 - 100% done
Saving python.txt to python (12).txt

11. Write a Python program to combine each line from first file with the corresponding line in second file.

#upload files to Google Colab environment by running this cell and selecting the files:
from google.colab import files
uploaded = files.upload()
def combine_files(file1, file2, output_file):
with open(file1, 'r') as f1, open(file2, 'r') as f2, open(output_file, 'w') as out_file:
for line1, line2 in zip(f1, f2):
out_file.write(line1.strip() + ' ' + line2)

file1 = 'python.txt'
file2 = 'jupiter.txt'
output_file = 'doc.txt'
combine_files(file1, file2, output_file)

Choose Files jupiter.txt


jupiter.txt(text/plain) - 514 bytes, last modified: 4/25/2024 - 100% done
Saving jupiter.txt to jupiter.txt

12. Write a Python program to read a random line from a file.

https://colab.research.google.com/drive/16_biU4L8qDENyPowQ3TRVpZKh532dZJs?authuser=1#scrollTo=CrQuISGfhFqL&printMode=true 3/5
4/25/24, 8:48 PM Lab11.ipynb - Colab
#upload files to Google Colab environment by running this cell and selecting the files:
from google.colab import files
uploaded = files.upload()
import random

def read_random_line(filename):
with open(filename, 'r') as file:
lines = file.readlines()
return random.choice(lines)

filename = 'python.txt'
print(read_random_line(filename))

Choose Files python.txt


python.txt(text/plain) - 510 bytes, last modified: 4/25/2024 - 100% done
Saving python.txt to python (14).txt
1

13. Write a Python program to assess if a file is closed or not.

#upload files to Google Colab environment by running this cell and selecting the files:
from google.colab import files
uploaded = files.upload()
def is_file_closed(file_obj):
return file_obj.closed

filename = 'python.txt'
file_obj = open(filename, 'r')
print("Is file closed?", is_file_closed(file_obj))
file_obj.close()
print("Is file closed?", is_file_closed(file_obj))

Choose Files python.txt


python.txt(text/plain) - 510 bytes, last modified: 4/25/2024 - 100% done
Saving python.txt to python (15).txt
Is file closed? False
Is file closed? True

14. Write a Python program to remove newline characters from a file.

#upload files to Google Colab environment by running this cell and selecting the files:
from google.colab import files
uploaded = files.upload()
def remove_newlines(filename):
with open(filename, 'r') as file:
lines = file.readlines()
with open(filename, 'w') as file:
for line in lines:
file.write(line.strip() + '\n')

filename = 'python.txt'
remove_newlines(filename)

Choose Files python.txt


python.txt(text/plain) - 510 bytes, last modified: 4/25/2024 - 100% done
Saving python.txt to python (16).txt

15. Write a Python program that takes a text file as input and returns the number of words of a given text file. Note: Some words can be
separated by a comma with no space.

#upload files to Google Colab environment by running this cell and selecting the files:
from google.colab import files
uploaded = files.upload()
def count_words(filename):
with open(filename, 'r') as file:
text = file.read()
# Remove commas without spaces
text = text.replace(',', ' ')
words = text.split()
return len(words)

filename = 'python.txt'
print("Number of words:", count_words(filename))

https://colab.research.google.com/drive/16_biU4L8qDENyPowQ3TRVpZKh532dZJs?authuser=1#scrollTo=CrQuISGfhFqL&printMode=true 4/5
4/25/24, 8:48 PM Lab11.ipynb - Colab

Choose Files python.txt


python.txt(text/plain) - 510 bytes, last modified: 4/25/2024 - 100% done
Saving python.txt to python (17).txt
Number of words: 5

https://colab.research.google.com/drive/16_biU4L8qDENyPowQ3TRVpZKh532dZJs?authuser=1#scrollTo=CrQuISGfhFqL&printMode=true 5/5
4/25/24, 9:21 PM Lab12.ipynb - Colab

PYTHON SEM 2 LAB-12

1. Create the following:

a. empty series

b. series from an array

c. series from dictionary

d. scalar series

import pandas as pd
import numpy as np

# a. Empty series
empty_series = pd.Series()
print("Empty Series:")
print(empty_series)
print()

# b. Series from an array


array = np.array([1, 2, 3, 4, 5])
series_from_array = pd.Series(array)
print("Series from an array:")
print(series_from_array)
print()

# c. Series from dictionary


dictionary = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
series_from_dict = pd.Series(dictionary)
print("Series from dictionary:")
print(series_from_dict)
print()

# d. Scalar series
scalar_series = pd.Series(5)
print("Scalar Series:")
print(scalar_series)
print()

output Empty Series:


Series([], dtype: object)

Series from an array:


0 1
1 2
2 3
3 4
4 5
dtype: int64

Series from dictionary:


a 1
b 2
c 3
d 4
e 5
dtype: int64

Scalar Series:
0 5
dtype: int64

2. Create indexed series for above b-d points

https://colab.research.google.com/drive/1RcllUdEMwfLBbkqOWwgj2RFPUmIEcID_?authuser=1#scrollTo=Xsr-nkSH4pOh&printMode=true 1/5
4/25/24, 9:21 PM Lab12.ipynb - Colab
import pandas as pd
import numpy as np

index_values = ['one', 'two', 'three', 'four', 'five']


indexed_series_from_array = pd.Series(array, index=index_values)
indexed_series_from_dict = pd.Series(dictionary, index=index_values)
indexed_scalar_series = pd.Series(5, index=index_values)
print("Indexed Series:")
print(indexed_series_from_array)
print(indexed_series_from_dict)
print(indexed_scalar_series)
print()

Indexed Series:
one 1
two 2
three 3
four 4
five 5
dtype: int64
one NaN
two NaN
three NaN
four NaN
five NaN
dtype: float64
one 5
two 5
three 5
four 5
five 5
dtype: int64

3. Retrieve elements from the series using

a. Index names

b. Index numbers

c. Slicing

import pandas as pd
import numpy as np
# a. Retrieve elements from the series using index names
element_using_index_names = series_from_dict['a']
print("Element using index names:", element_using_index_names)

# b. Retrieve elements from the series using index numbers


element_using_index_numbers = series_from_array[0]
print("Element using index numbers:", element_using_index_numbers)

# c. Slicing
sliced_elements = series_from_array[1:3]
print("Sliced elements:")
print(sliced_elements)
print()

Element using index names: 1


Element using index numbers: 1
Sliced elements:
1 2
2 3
dtype: int64

4. Create a DataFrame using the following:

a. Empty DataFrame

b. DataFrame using list

c. DataFrame using dictionary

d. DataFrame using series

https://colab.research.google.com/drive/1RcllUdEMwfLBbkqOWwgj2RFPUmIEcID_?authuser=1#scrollTo=Xsr-nkSH4pOh&printMode=true 2/5
4/25/24, 9:21 PM Lab12.ipynb - Colab
import pandas as pd
import numpy as np
# a. Empty DataFrame
empty_df = pd.DataFrame()
print("Empty DataFrame:")
print(empty_df)
print()

# b. DataFrame using list


data_list = [[1, 'a'], [2, 'b'], [3, 'c']]
df_from_list = pd.DataFrame(data_list, columns=['Column1', 'Column2'])
print("DataFrame from list:")
print(df_from_list)
print()

# c. DataFrame using dictionary


data_dict = {'Column1': [1, 2, 3], 'Column2': ['a', 'b', 'c']}
df_from_dict = pd.DataFrame(data_dict)
print("DataFrame from dictionary:")
print(df_from_dict)
print()

# d. DataFrame using series


data_series = {'Column1': indexed_series_from_array, 'Column2': indexed_series_from_dict}
df_from_series = pd.DataFrame(data_series)
print("DataFrame from series:")
print(df_from_series)
print()

Empty DataFrame:
Empty DataFrame
Columns: []
Index: []

DataFrame from list:


Column1 Column2
0 1 a
1 2 b
2 3 c

DataFrame from dictionary:


Column1 Column2
0 1 a
1 2 b
2 3 c

DataFrame from series:


Column1 Column2
one 1 NaN
two 2 NaN
three 3 NaN
four 4 NaN
five 5 NaN

5. Create 3-4 four colums in a DataFrame for Q4 b-d points

import pandas as pd
import numpy as np
df_from_list['Column3'] = [4, 5, 6]
df_from_list['Column4'] = ['d', 'e', 'f']
print("DataFrame with 3-4 columns:")
print(df_from_list)
print()

DataFrame with 3-4 columns:


Column1 Column2 Column3 Column4
0 1 a 4 d
1 2 b 5 e
2 3 c 6 f

6. Add index to all the rows in Q5

import pandas as pd
import numpy as np
print("DataFrame with index:")
print(df_from_list)
print()

DataFrame with index:


Column1 Column2 Column3 Column4

https://colab.research.google.com/drive/1RcllUdEMwfLBbkqOWwgj2RFPUmIEcID_?authuser=1#scrollTo=Xsr-nkSH4pOh&printMode=true 3/5
4/25/24, 9:21 PM Lab12.ipynb - Colab
0 1 a 4 d
1 2 b 5 e
2 3 c 6 f

7. Display all the values from the DataFrame mentioned in Q6 using index and index name for :

a. Second row values

b. Second column values

import pandas as pd
import numpy as np
import pandas as pd
import numpy as np

# Define the DataFrame


data_list = [[1, 'a', 4, 'd'], [2, 'b', 5, 'e'], [3, 'c', 6, 'f']]
index_values = ['one', 'two', 'three']
columns = ['Column1', 'Column2', 'Column3', 'Column4']
df_from_list = pd.DataFrame(data_list, columns=columns, index=index_values)

# a. Display all the values from the DataFrame mentioned in Q6 using index and index name for the second row values
second_row_values_by_index = df_from_list.iloc[1]
second_row_values_by_index_name = df_from_list.loc['two']
print("Second row values by index:")
print(second_row_values_by_index)
print("\nSecond row values by index name:")
print(second_row_values_by_index_name)

# b. Display all the values from the DataFrame mentioned in Q6 using index and index name for the second column values
second_column_values_by_index = df_from_list.iloc[:, 1]
second_column_values_by_name = df_from_list['Column2']
print("\nSecond column values by index:")
print(second_column_values_by_index)
print("\nSecond column values by name:")
print(second_column_values_by_name)

Second row values by index:


Column1 2
Column2 b
Column3 5
Column4 e
Name: two, dtype: object

Second row values by index name:


Column1 2
Column2 b
Column3 5
Column4 e
Name: two, dtype: object

Second column values by index:


one a
two b
three c
Name: Column2, dtype: object

Second column values by name:


one a
two b
three c
Name: Column2, dtype: object

8. Perform slicing by displaying 3rd and 4th row on the DataFrame

import pandas as pd
import numpy as np
sliced_df = df_from_list.iloc[2:4]
print("Sliced DataFrame:")
print(sliced_df)
print()

Sliced DataFrame:
Column1 Column2 Column3 Column4
2 3 c 6 f

9. Delete a row

import pandas as pd
i t
https://colab.research.google.com/drive/1RcllUdEMwfLBbkqOWwgj2RFPUmIEcID_?authuser=1#scrollTo=Xsr-nkSH4pOh&printMode=true 4/5
4/25/24, 9:21 PM Lab12.ipynb - Colab
import numpy as np
df_after_row_deletion = df_from_list.drop('three', axis=0, errors='ignore')
print("DataFrame after row deletion:")
print(df_after_row_deletion)
print()

DataFrame after row deletion:


Column1 Column2 Column3 Column4
0 1 a 4 d
1 2 b 5 e
2 3 c 6 f

10. Delete a column

import pandas as pd
import numpy as np
df_after_column_deletion = df_from_list.drop('Column4', axis=1)
print("DataFrame after column deletion:")
print(df_after_column_deletion)

DataFrame after column deletion:


Column1 Column2 Column3
0 1 a 4
1 2 b 5
2 3 c 6

https://colab.research.google.com/drive/1RcllUdEMwfLBbkqOWwgj2RFPUmIEcID_?authuser=1#scrollTo=Xsr-nkSH4pOh&printMode=true 5/5

You might also like