Shri Vaishnav Vidyapeeth Vishwavidyalaya
Shri Shri Vaishnav Institute of Information Technology
Department of Computer Science Engineering
Programming with Python
Lab File
2025
Submitted By: Rudraksh Mishra
Enroll. No: 23100BTCSE15059
Program: B.Tech
Section: E
Year/Sem: 3nd yr/ 5th sem
Course Name: Programming with Python
Course Code: BTIT507N
Submitted To: Prof. Sunny Bagga
23100BTCSE15059 Rudraksh Mishra Programming with
Python(BTIT507N)
Shri Vaishnav Vidyapeeth Vishwavidyalaya
Shri Shri Vaishnav Institute of Information Technology
Department of Computer Science Engineering
INDEX
No Aim/Objective Date of Sign /
Experiment Remarks
1 To Print Hello world!
To demonstrate different number
2
data types in Python.
To perform different Arithmetic
3
Operations on numbers in Python.
4 To Swap Two Variables.
5 To Convert Celsius to Fahrenheit.
To Find the Largest Among Three
6
Numbers.
7 To Check Prime Number.
8 To Find the Factorial of a Number.
9 To Print the Fibonacci sequence.
To create, append, and remove
10
lists in python.
To demonstrate working with
11
tuples in python.
To demonstrate working with set
12
in python.
To demonstrate working with
13
dictionaries in python.
To find reverse of given number
14
using function.
To call data member and function
15
using classes and objects
To read 3 subject marks and
16 display pass or failed using class
and object.
23100BTCSE15059 Rudraksh Mishra Programming with
Python(BTIT507N)
Shri Vaishnav Vidyapeeth Vishwavidyalaya
Shri Shri Vaishnav Institute of Information Technology
Department of Computer Science Engineering
17 To handle user defined exception
for given problem.
18 To create an array and check the
following using Numpy module:
a. Type of array
b. Axes of array
c. Shape of array
d. Type of elements in array
To concatenate the dataframes
19
with two different objects.
To Demonstrate how to Draw a
20 Scatter Plot, Bar Graph and Pie
Chart using Matplotlib.
23100BTCSE15059 Rudraksh Mishra Programming with
Python(BTIT507N)
Shri Vaishnav Vidyapeeth Vishwavidyalaya
Shri Shri Vaishnav Institute of Information Technology
Department of Computer Science Engineering
Experiment - 1
1. Title:
To Print Hello world!
2. Objective:
The objective of this experiment is to learn how to write and execute a simple Python
program that prints output on the screen.
3. Solution:
print("Hello World!")
4. Output:
Hello World!
5. Quiz and Viva Questions:
5.1 Quiz Multiple Choice Questions (MCQs):
1. Which function is used to display output in Python?
a) echo()
b) printf()
c) print()
d) display()
Answer: c) print()
2. What will be the output of the code: print("Hello" + "World") ?
a) Hello + World
b) HelloWorld
c) Error
d) Hello World
Answer: b) HelloWorld
23100BTCSE15059 Rudraksh Mishra Programming with
Python(BTIT507N)
Shri Vaishnav Vidyapeeth Vishwavidyalaya
Shri Shri Vaishnav Institute of Information Technology
Department of Computer Science Engineering
3. Python is a ___ language.
a) Compiled
b) Interpreted
c) Machine-level
d) Assembly-level
Answer: b) Interpreted
4. Which symbol is used for comments in Python?
a) //
b) #
c) /* */
d) --
Answer: b) #
5. What is the correct file extension for Python programs?
a) .py
b) .java
c) .exe
d) .pyt
Answer: a) .py
5.2 Viva Questions:
1. What is Python and why is it popular?
2. How do you run a Python program?
3. What is the difference between a compiler and an interpreter?
4. What is the role of the print() function in Python?
5. Can we print multiple lines using a single print() statement? If yes, how?
23100BTCSE15059 Rudraksh Mishra Programming with
Python(BTIT507N)
Shri Vaishnav Vidyapeeth Vishwavidyalaya
Shri Shri Vaishnav Institute of Information Technology
Department of Computer Science Engineering
Experiment - 2
1. Title:
To demonstrate different number data types in Python.
2. Objective:
The objective of this experiment is to understand the different number
data types in Python such as int, float, and complex, and how to use them.
3. Solution:
# Integer data type (whole numbers)
int_variable = 42
print("Integer Value:", int_variable)
print("Type of variable is:", type(int_variable))
# Float data type (numbers with a decimal point)
float_variable = 3.14
print("Float Value:", float_variable)
print("Type of variable is:", type(float_variable))
# Complex data type (numbers with a real and imaginary part)
complex_variable = 5 + 6j
print("Complex Value:", complex_variable)
print("Type of variable is:", type(complex_variable))
4. Output:
23100BTCSE15059 Rudraksh Mishra Programming with
Python(BTIT507N)
Shri Vaishnav Vidyapeeth Vishwavidyalaya
Shri Shri Vaishnav Institute of Information Technology
Department of Computer Science Engineering
5. Quiz and Viva Questions:
5.1 Quiz Multiple Choice Questions (MCQs):
1. Which of the following represents a floating-point number in Python?
a) 87
b) 87.0
c) "87"
d) 8+7j
Answer: b) 87.0
2. What will be the output of type(10)?
a) <class 'integer'>
b) <class 'number'>
c) <class 'int'>
d) <class 'float'>
Answer: c) <class 'int'>
3. In Python, the imaginary part of a complex number is represented by
which letter?
a) i
b) m
c) x
d) j
Answer: d) j
4. What is the process of converting one data type to another called?
a) Conversion
b) Type Casting
c) Declaration
d) Initialization
Answer: b) Type Casting
5. What will be the result of the expression int(22.8)?
23100BTCSE15059 Rudraksh Mishra Programming with
Python(BTIT507N)
Shri Vaishnav Vidyapeeth Vishwavidyalaya
Shri Shri Vaishnav Institute of Information Technology
Department of Computer Science Engineering
a) 23
b) 22.8
c) 22
d) Error
Answer: c) 22
5.2 Viva Questions:
1. What are the three numeric data types you learned about in this
experiment?
2. How does Python know if a number is an integer or a float when you
declare it?
3. What is the difference between a float and a complex number?
4. Can you perform arithmetic operations between an integer and a float?
What would be the data type of the result?
5. How can you check the data type of any variable in Python?
23100BTCSE15059 Rudraksh Mishra Programming with
Python(BTIT507N)
Shri Vaishnav Vidyapeeth Vishwavidyalaya
Shri Shri Vaishnav Institute of Information Technology
Department of Computer Science Engineering
Experiment - 3
1. Title:
To perform different Arithmetic Operations on numbers in Python.
2. Objective:
The objective of this experiment is to learn and apply Python's basic arithmetic operators to
perform calculations such as addition, subtraction, multiplication, division, floor division,
modulus, and exponentiation.
3. Solution:
num1 = 16
num2 = 5
print(f"Using numbers: num1 = {num1}, num2 = {num2}\n")
# Addition
add_result = num1 + num2
print(f"Addition (+) : {num1} + {num2} = {add_result}")
# Subtraction
sub_result = num1 - num2
print(f"Subtraction (-) : {num1} - {num2} = {sub_result}")
# Multiplication
mul_result = num1 * num2
print(f"Multiplication (*) : {num1} * {num2} = {mul_result}")
# Division
div_result = num1 / num2
print(f"Division (/) : {num1} / {num2} = {div_result}")
# Floor Division
floor_div_result = num1 // num2
print(f"Floor Division (//) : {num1} // {num2} = {floor_div_result}")
# Modulus
mod_result = num1 % num2
23100BTCSE15059 Rudraksh Mishra Programming with
Python(BTIT507N)
Shri Vaishnav Vidyapeeth Vishwavidyalaya
Shri Shri Vaishnav Institute of Information Technology
Department of Computer Science Engineering
print(f"Modulus (%) : {num1} % {num2} = {mod_result}")
# Exponentiation
exp_result = num1 ** num2
print(f"Exponentiation (**) : {num1} ** {num2} = {exp_result}")
4. Output:
5. Quiz and Viva Questions:
5.1 Quiz Multiple Choice Questions (MCQs):
1. Which operator is used to find the remainder of a division?
a) //
b) /
c) **
d) %
Answer: d) %
2. What is the result of the expression 13 // 4?
a) 3.25
b) 4
c) 3
d) 1
Answer: c) 3
3. Which operator has the highest precedence in the expression 5 + 10 *
2?
a) +
23100BTCSE15059 Rudraksh Mishra Programming with
Python(BTIT507N)
Shri Vaishnav Vidyapeeth Vishwavidyalaya
Shri Shri Vaishnav Institute of Information Technology
Department of Computer Science Engineering
b) *
c) Both have the same precedence
d) The expression is invalid
Answer: b) *
4. What will be the output of 2 ** 3?
a) 6
b) 5
c) 8
d) 9
Answer: c) 8
5. The division operator (/) in Python 3 always returns a value of which
data type?
a) int
b) float
c) complex
d) It depends on the operands
Answer: b) float
5.2 Viva Questions:
1. What is the main difference between the / (division) and // (floor
division) operators?
2. Can you give a practical example where the modulus operator (%)
would be useful?
3. What is "operator precedence"? Why is it important in writing
mathematical expressions?
4. How would you calculate the square of a number using an arithmetic
operator in Python?
5. What error occurs if you try to divide any number by zero in Python?
23100BTCSE15059 Rudraksh Mishra Programming with
Python(BTIT507N)
Shri Vaishnav Vidyapeeth Vishwavidyalaya
Shri Shri Vaishnav Institute of Information Technology
Department of Computer Science Engineering
Experiment - 4
1. Title:
To Swap Two Variables.
2. Objective:
The objective of this experiment is to learn how to interchange the values of two variables
using Python's concise tuple unpacking syntax.
3. Solution:
# Initialize two variables
a=5
b = 10
print(f"Before swap: a = {a}, b = {b}")
# Swap the values in a single line
a, b = b, a
print(f"After swap: a = {a}, b = {b}")
4. Output:
5. Quiz and Viva Questions:
5.1 Quiz Multiple Choice Questions (MCQs):
1. Which is the most "Pythonic" way to swap the values of variables x and
y?
a) temp = x; x = y; y = temp
b) x = y; y = x
c) x, y = y, x
d) x.swap(y)
Answer: c) x, y = y, x
23100BTCSE15059 Rudraksh Mishra Programming with
Python(BTIT507N)
Shri Vaishnav Vidyapeeth Vishwavidyalaya
Shri Shri Vaishnav Institute of Information Technology
Department of Computer Science Engineering
2. After executing p = 15; q = 25; p, q = q, p;, what will be the value of p?
a) 15
b) 25
c) 40
d) Error
Answer: b) 25
3. The traditional method of swapping variables involves using a third
variable known as a...?
a) Constant variable
b) Placeholder variable
c) Global variable
d) Temporary variable
Answer: d) Temporary variable
4. The syntax a, b = b, a works because of a feature called...?
a) List comprehension
b) Tuple unpacking
c) Value reassignment
d) Operator overloading
Answer: b) Tuple unpacking
5. What are the final values of a and b after this code: a = 1; b = 2; a = b;
b = a;?
a) a is 2, b is 1
b) a is 1, b is 2
c) a is 2, b is 2
d) a is 1, b is 1
23100BTCSE15059 Rudraksh Mishra Programming with
Python(BTIT507N)
Shri Vaishnav Vidyapeeth Vishwavidyalaya
Shri Shri Vaishnav Institute of Information Technology
Department of Computer Science Engineering
Answer: c) a is 2, b is 2
5.2 Viva Questions:
1. Explain the logic of swapping two variables using the classic temporary
variable method.
2. How does Python's one-line swap (a, b = b, a) work?
3. Why is the one-line swap method generally preferred in Python?
4. Can you swap the values of more than two variables in a single
statement in Python? Give an example.
5. What is tuple unpacking and where else might it be useful besides
swapping variables?
23100BTCSE15059 Rudraksh Mishra Programming with
Python(BTIT507N)
Shri Vaishnav Vidyapeeth Vishwavidyalaya
Shri Shri Vaishnav Institute of Information Technology
Department of Computer Science Engineering
Experiment - 5
1. Title:
To Convert Celsius to Fahrenheit.
2. Objective:
The objective is to write a Python program that converts a temperature from Celsius to
Fahrenheit using the standard conversion formula.
Solution:
celsius = float(input("Enter temperature in Celsius: "))
fahrenheit = (celsius * 9/5) + 32
print(f'{celsius}°C is equal to {fahrenheit}°F')
4. Output:
5. Quiz and Viva Questions:
5.1 Quiz Multiple Choice Questions (MCQs):
1. What is the correct formula for Celsius to Fahrenheit conversion?
a) F = C * 9/5 + 32
b) F = (C - 32) * 5/9
c) F = C + 273.15
d) F = C * 1.8 - 32
Answer: a) F = C * 9/5 + 32
2. If the temperature in Celsius is 0°C, what is it in Fahrenheit?
a) 0°F
b) -32°F
c) 32°F
23100BTCSE15059 Rudraksh Mishra Advanced Java-BTIT410M(P)
Shri Vaishnav Vidyapeeth Vishwavidyalaya
Shri Shri Vaishnav Institute of Information Technology
Department of Computer Science Engineering
d) 100°F
Answer: c) 32°F
3. In the expression (celsius * 9/5), what is the result of 9/5 in Python 3?
a) 1
b) 1.8
c) 2
d) It causes an error.
Answer: b) 1.8
4. To accept user input, which function is used in Python?
a) get()
b) read()
c) input()
d) print()
Answer: c) input()
5. Which data type is most suitable for storing the value 99.5?
a) int
b) string
c) float
d) boolean
Answer: c) float
5.2 Viva Questions:
1. Can you state the formula used to convert Celsius to Fahrenheit?
2. What is the reverse formula to convert Fahrenheit back to Celsius?
3. Why is using floating-point arithmetic important for this calculation?
4. How would you change the program to let a user type in the Celsius
value?
5. What are the freezing and boiling points of water on the Fahrenheit
scale?
23100BTCSE15059 Rudraksh Mishra Advanced Java-BTIT410M(P)
Shri Vaishnav Vidyapeeth Vishwavidyalaya
Shri Shri Vaishnav Institute of Information Technology
Department of Computer Science Engineering
Experiment - 6
1. Title:
To Find the Largest Among Three Numbers.
2. Objective:
The objective of this experiment is to learn how to compare three
numbers to find the largest one using Python's built-in max() function.
3. Solution:
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
num3 = int(input("Enter the third number: "))
largest_number = max(num1, num2, num3)
print(f"The largest number is: {largest_number}")
4. Output:
5. Quiz and Viva Questions:
5.1 Quiz Multiple Choice Questions (MCQs):
1. Which built-in Python function is the easiest way to find the largest
number in a set?
a) maximum()
b) large()
c) top()
d) max()
Answer: d) max()
2. Which comparison operator checks if a value is greater than another?
a) <
23100BTCSE15059 Rudraksh Mishra Advanced Java-BTIT410M(P)
Shri Vaishnav Vidyapeeth Vishwavidyalaya
Shri Shri Vaishnav Institute of Information Technology
Department of Computer Science Engineering
b) >
c) ==
d) >=
Answer: b) >
3. What is the output of max(15, -20, 0)?
a) 15
b) -20
c) 0
d) Error
Answer: a) 15
4. Without using max(), you would typically use which programming
structure to compare numbers?
a) A for loop
b) A while loop
c) if-elif-else statements
d) A try-except block
Answer: c) if-elif-else statements
5. The condition if x > y and x > z: checks if x is:
a) Larger than y or z
b) The sum of y and z
c) Larger than both y and z
d) Equal to y and z
Answer: c) Larger than both y and z
5.2 Viva Questions:
1. Describe how you would find the largest of three numbers using an if-
elif-else structure instead of the max() function.
2. What are the advantages of using the max() function?
3. How would you find the smallest number among the three? Which
function would you use?
23100BTCSE15059 Rudraksh Mishra Advanced Java-BTIT410M(P)
Shri Vaishnav Vidyapeeth Vishwavidyalaya
Shri Shri Vaishnav Institute of Information Technology
Department of Computer Science Engineering
4. What happens if two of the numbers are identical and are the largest
(e.g., num1=50, num2=20, num3=50)?
Experiment - 7
1. Title:
To Check Prime Number.
2. Objective:
The objective is to write a Python program that takes an integer as input
and determines whether it is a prime number.
3. Solution:
num = int(input("Enter a number: "))
if num > 1:
for i in range(2, num):
if (num % i) == 0:
print(f"{num} is not a prime number.")
break
else:
print(f"{num} is a prime number.")
else:
print(f"{num} is not a prime number.")
4. Output:
5. Quiz and Viva Questions:
23100BTCSE15059 Rudraksh Mishra Advanced Java-BTIT410M(P)
Shri Vaishnav Vidyapeeth Vishwavidyalaya
Shri Shri Vaishnav Institute of Information Technology
Department of Computer Science Engineering
5.1 Quiz Multiple Choice Questions (MCQs):
1. A prime number is a natural number greater than 1 that has exactly
how many distinct positive divisors?
a) 1
b) 2
c) 3
d) As many as the number itself
Answer: b) 2
2. Which operator is used to check for divisibility in the code?
a) /
b) //
c) %
d) *
Answer: c) %
3. What does the break statement do in a loop?
a) Skips the current iteration
b) Pauses the loop for a few seconds
c) Exits the loop immediately
d) Restarts the loop
Answer: c) Exits the loop immediately
4. According to the logic, is the number 1 considered prime?
a) Yes
b) No
c) The code will give an error
d) It is a special prime
Answer: b) No
23100BTCSE15059 Rudraksh Mishra Advanced Java-BTIT410M(P)
Shri Vaishnav Vidyapeeth Vishwavidyalaya
Shri Shri Vaishnav Institute of Information Technology
Department of Computer Science Engineering
5. The else block in the provided for loop executes only if...?
a) The loop is empty
b) The break statement is executed
c) The loop completes all its iterations without a break
d) An error occurs
Answer: c) The loop completes all its iterations without a break
5.2 Viva Questions:
1. What is the definition of a prime number?
2. Why does the loop in the program start from 2 and not 1?
3. What is a composite number?
4. Can you think of a way to make this program more efficient for very
large numbers?
5. Why is 1 not considered a prime number?
23100BTCSE15059 Rudraksh Mishra Advanced Java-BTIT410M(P)
Shri Vaishnav Vidyapeeth Vishwavidyalaya
Shri Shri Vaishnav Institute of Information Technology
Department of Computer Science Engineering
Experiment - 8
1. Title:
To Find the Factorial of a Number.
2. Objective:
The objective of this experiment is to write a Python program that
calculates the factorial of a non-negative integer provided by the user.
3. Solution:
num = int(input("Enter a number: "))
factorial = 1
if num < 0:
print("Sorry, factorial does not exist for negative numbers.")
elif num == 0:
print("The factorial of 0 is 1.")
else:
for i in range(1, num + 1):
factorial = factorial * i
print(f"The factorial of {num} is {factorial}.")
4. Output:
5. Quiz and Viva Questions:
5.1 Quiz Multiple Choice Questions (MCQs):
1. What is the factorial of 0 (0!)?
a) 0
23100BTCSE15059 Rudraksh Mishra Advanced Java-BTIT410M(P)
Shri Vaishnav Vidyapeeth Vishwavidyalaya
Shri Shri Vaishnav Institute of Information Technology
Department of Computer Science Engineering
b) 1
c) Undefined
d) Infinite
Answer: b) 1
2. The factorial of 4 (4!) is calculated as:
a) 4 * 3 * 2 * 1
b) 4 * 4 * 4 * 4
c) 1 + 2 + 3 + 4
d) 4 * 1
Answer: a) 4 * 3 * 2 * 1
3. For which set of numbers is the factorial not defined?
a) Positive integers
b) Negative integers
c) Zero
d) All integers
Answer: b) Negative integers
4. In the code, what is the initial value of the factorial variable before the loop starts?
a) 0
b) 1
c) num
23100BTCSE15059 Rudraksh Mishra Advanced Java-BTIT410M(P)
Shri Vaishnav Vidyapeeth Vishwavidyalaya
Shri Shri Vaishnav Institute of Information Technology
Department of Computer Science Engineering
d) It is not initialized.
Answer: b) 1
5. What is the value of 5!?
a) 25
b) 120
c) 15
d) 60
Answer: b) 120
5.2 Viva Questions:
1. In your own words, what is a factorial?
2. Why is the factorial variable initialized to 1 and not 0?
3. Besides using a loop (iteration), what is another common method to calculate factorials in
programming? (Hint: A function that calls itself).
4. What is the purpose of the if-elif-else structure in this program?
5. What do you think will happen if you try to calculate the factorial of a very large number,
like 100?
23100BTCSE15059 Rudraksh Mishra Advanced Java-BTIT410M(P)
Shri Vaishnav Vidyapeeth Vishwavidyalaya
Shri Shri Vaishnav Institute of Information Technology
Department of Computer Science Engineering
Experiment - 9
1. Title:
To Print the Fibonacci sequence.
2. Objective:
The objective of this experiment is to write a Python program that
generates and prints the Fibonacci sequence up to a user-specified
number of terms.
3. Solution:
num_terms = int(input("Enter the number of terms: "))
n1, n2 = 0, 1
count = 0
if num_terms <= 0:
print("Please enter a positive integer.")
elif num_terms == 1:
print(f"Fibonacci sequence up to {num_terms} term:")
print(n1)
else:
print("Fibonacci sequence:")
while count < num_terms:
print(n1, end=' ')
nth_term = n1 + n2
n1 = n2
n2 = nth_term
23100BTCSE15059 Rudraksh Mishra Advanced Java-BTIT410M(P)
Shri Vaishnav Vidyapeeth Vishwavidyalaya
Shri Shri Vaishnav Institute of Information Technology
Department of Computer Science Engineering
count += 1
4. Output:
5. Quiz and Viva Questions:
5.1 Quiz Multiple Choice Questions (MCQs):
1. In the Fibonacci sequence, each number is the sum of the ___ preceding ones.
a) One
b) Two
c) Three
d) Previous number and 1
Answer: b) Two
2. What are the first two terms of the standard Fibonacci sequence?
a) 1, 1
b) 1, 2
c) 0, 1
d) 0, 0
Answer: c) 0, 1
3. What is the next number in the sequence: 0, 1, 1, 2, 3, 5, ...?
a) 6
b) 7
23100BTCSE15059 Rudraksh Mishra Advanced Java-BTIT410M(P)
Shri Vaishnav Vidyapeeth Vishwavidyalaya
Shri Shri Vaishnav Institute of Information Technology
Department of Computer Science Engineering
c) 8
d) 9
Answer: c) 8
4. In the solution's while loop, what is the purpose of n1 = n2?
a) To end the loop
b) To calculate the next term
c) To update the first of the two previous numbers for the next iteration
d) To check for a negative number
Answer: c) To update the first of the two previous numbers for the next iteration
5. What does end=' ' do in the print() function?
a) Ends the program
b) Prints a space instead of a newline character after the output
c) Adds an error message at the end
d) Prints the text 'end'
Answer: b) Prints a space instead of a newline character after the output
5.2 Viva Questions:
1. Explain the logic used in the while loop to generate the sequence.
2. What are the "base cases" or starting points of the Fibonacci sequence?
3. Besides using a loop, can you think of another way to program the
Fibonacci sequence? (Hint: recursion).
4. Can you give an example of where the Fibonacci sequence appears in
nature?
5. What happens if you don't handle the case where a user enters 1 as
input?
23100BTCSE15059 Rudraksh Mishra Advanced Java-BTIT410M(P)
Shri Vaishnav Vidyapeeth Vishwavidyalaya
Shri Shri Vaishnav Institute of Information Technology
Department of Computer Science Engineering
Experiment - 10
1. Title:
To create, append, and remove lists in python.
2. Objective:
The objective of this experiment is to understand how to create a Python
list, add elements to it, and remove elements using different methods.
3. Solution:
# Create a list
my_list = ['pen', 'pencil', 'eraser']
print(f"Initial list: {my_list}")
# Append an element to the end
my_list.append('sharpener')
print(f"After appending 'sharpener': {my_list}")
# Remove an element by its value
my_list.remove('pencil')
print(f"After removing 'pencil': {my_list}")
# Remove an element by its index
popped_item = my_list.pop(0)
print(f"After popping index 0: {my_list}")
print(f"Popped item: {popped_item}")
4.Output:
23100BTCSE15059 Rudraksh Mishra Advanced Java-BTIT410M(P)
Shri Vaishnav Vidyapeeth Vishwavidyalaya
Shri Shri Vaishnav Institute of Information Technology
Department of Computer Science Engineering
5. Quiz and Viva Questions:
5.1 Quiz Multiple Choice Questions (MCQs):
1. Which symbol is used to create an empty list?
a) {}
b) ()
c) []
d) ""
Answer: c) []
2. Which method adds an element to the very end of a list?
a) insert()
b) add()
c) extend()
d) append()
Answer: d) append()
3. The list.remove(x) method removes the...?
a) First occurrence of value x
b) Last occurrence of value x
c) Element at index x
d) All occurrences of value x
Answer: a) First occurrence of value x
23100BTCSE15059 Rudraksh Mishra Advanced Java-BTIT410M(P)
Shri Vaishnav Vidyapeeth Vishwavidyalaya
Shri Shri Vaishnav Institute of Information Technology
Department of Computer Science Engineering
4. What does the list.pop(i) method do?
a) Removes the item with the value i
b) Adds an item at index i
c) Removes and returns the item at index i
d) Only returns the item at index i without removing it
Answer: c) Removes and returns the item at index i
5. What will be the output of this code? my_list = [10, 20, 30];
my_list.pop(); print(my_list)
a) [10, 20, 30]
b) [10, 20]
c) [20, 30]
d) 30
Answer: b) [10, 20]
5.2 Viva Questions:
1. What is the difference between the remove() and pop() list methods?
2. What happens if you try to remove() an element that is not present in
the list?
3. How would you add an element to a specific position in a list, like the
beginning? (Hint: There is a different method for this).
4. Are lists in Python mutable or immutable? What does that mean?
5. Besides remove() and pop(), do you know another way to delete an
element from a list? (Hint: del keyword).
23100BTCSE15059 Rudraksh Mishra Advanced Java-BTIT410M(P)
Shri Vaishnav Vidyapeeth Vishwavidyalaya
Shri Shri Vaishnav Institute of Information Technology
Department of Computer Science Engineering
Experiment - 11
1. Title:
To demonstrate working with tuples in python.
2. Objective:
The objective of this experiment is to learn how to create and access
Python tuples and to understand their core characteristic: immutability.
immutable means that it cannot be changed.
3. Solution:
# Create a tuple and access an element
my_tuple = ("apple", "banana", "cherry")
print(f"The tuple: {my_tuple}")
print(f"Element at index 0: {my_tuple[0]}")
# Demonstrate immutability by trying to change an element
print("\nAttempting to change 'apple' to 'orange'...")
try:
my_tuple[0] = "orange"
except TypeError as e:
print(f"Error received: {e}")
# Demonstrate tuple unpacking
fruit1, fruit2, fruit3 = my_tuple
print(f"\nUnpacked variables: {fruit1}, {fruit2}, {fruit3}")
23100BTCSE15059 Rudraksh Mishra Advanced Java-BTIT410M(P)
Shri Vaishnav Vidyapeeth Vishwavidyalaya
Shri Shri Vaishnav Institute of Information Technology
Department of Computer Science Engineering
4. Output:
5. Quiz and Viva Questions:
5.1 Quiz Multiple Choice Questions (MCQs):
1. Which symbols are used to create a tuple?
a) []
b) {}
c) ()
d) <>
Answer: c) ()
2. What is the primary characteristic of a tuple?
a) They are mutable
b) They are immutable
c) They can only store numbers
d) They are sorted by default
Answer: b) They are immutable
3. What does "immutable" mean?
a) The object can be changed after creation
b) The object cannot be changed after creation
c) The object can be deleted
d) The object can hold duplicate values
23100BTCSE15059 Rudraksh Mishra Advanced Java-BTIT410M(P)
Shri Vaishnav Vidyapeeth Vishwavidyalaya
Shri Shri Vaishnav Institute of Information Technology
Department of Computer Science Engineering
Answer: b) The object cannot be changed after creation
4. How do you access the second element of a tuple named t?
a) t(1)
b) t[2]
c) t.get(1)
d) t[1]
Answer: d) t[1]
5. What happens when you try to run my_tuple[0] = "new_value"?
a) The first element is updated
b) A ValueError occurs
c) A TypeError occurs
d) A KeyError occurs
Answer: c) A TypeError occurs
5.2 Viva Questions:
1. What is the main difference between a list and a tuple?
2. Why would you choose to use a tuple instead of a list?
3. Can a tuple contain different data types (e.g., an integer, a string, and a list)?
4. What is tuple unpacking?
5. Although a tuple is immutable, if it contains a mutable object like a list, can that object be
changed?
Experiment - 12
1. Title:
23100BTCSE15059 Rudraksh Mishra Advanced Java-BTIT410M(P)
Shri Vaishnav Vidyapeeth Vishwavidyalaya
Shri Shri Vaishnav Institute of Information Technology
Department of Computer Science Engineering
To demonstrate working with set in python.
2. Objective:
The objective of this experiment is to learn how to create and manipulate
Python sets, understanding their properties of containing unique,
unordered elements, and performing common set operations.
3. Solution:
# Create a set from a list with duplicates
list_with_duplicates = [10, 20, 20, 30, 10]
my_set = set(list_with_duplicates)
print(f"Set created from list: {my_set}")
# Add an element
my_set.add(40)
print(f"After adding 40: {my_set}")
# Remove an element
my_set.remove(20)
print(f"After removing 20: {my_set}")
# Perform a set operation (union)
other_set = {30, 40, 50}
union_result = my_set | other_set
print(f"Union with {other_set}: {union_result}")
4. Output:
23100BTCSE15059 Rudraksh Mishra Advanced Java-BTIT410M(P)
Shri Vaishnav Vidyapeeth Vishwavidyalaya
Shri Shri Vaishnav Institute of Information Technology
Department of Computer Science Engineering
5. Quiz and Viva Questions:
5.1 Quiz Multiple Choice Questions (MCQs):
1. What is a key property of a Python set?
a) It stores elements in a sorted order.
b) It allows duplicate elements.
c) It stores unique elements.
d) It is immutable.
Answer: c) It stores unique elements.
2. Which function is used to create a set from a list?
a) list()
b) convert_to_set()
c) set()
d) make_set()
Answer: c) set()
3. How do you add a single element to an existing set named s?
a) s.append(5)
b) s.add(5)
c) s.insert(5)
d) s.update(5)
Answer: b) s.add(5)
23100BTCSE15059 Rudraksh Mishra Advanced Java-BTIT410M(P)
Shri Vaishnav Vidyapeeth Vishwavidyalaya
Shri Shri Vaishnav Institute of Information Technology
Department of Computer Science Engineering
4. Which operator is used for the union of two sets?
a) &
b) +
c) |
d) ^
Answer: c) |
5. What happens if you try to add an element that is already in the set?
a) A ValueError occurs.
b) The element is added again.
c) The set remains unchanged.
d) A KeyError occurs.
Answer: c) The set remains unchanged.
5.2 Viva Questions:
1. What are the two main properties of a set in Python?
2. How is a set different from a list?
3. Besides union, what are other common set operations? (e.g.,
intersection, difference).
4. What is the difference between the .remove() and .discard() methods
for sets?
5. Can a set contain a list as one of its elements? Why or why not?
23100BTCSE15059 Rudraksh Mishra Advanced Java-BTIT410M(P)
Shri Vaishnav Vidyapeeth Vishwavidyalaya
Shri Shri Vaishnav Institute of Information Technology
Department of Computer Science Engineering
Experiment - 13
1. Title:
To demonstrate working with dictionaries in python.
2. Objective:
The objective is to learn about Python's dictionaries, including how to
create them, access, add, modify, and remove data using key-value pairs.
3. Solution:
# Create a dictionary
student = {
"name": "Rohan",
"age": 20,
"major": "Physics"
print(f"Original dictionary: {student}")
# Access a value by its key
print(f"Student's name: {student['name']}")
# Add a new key-value pair
student['city'] = "Bhopal"
print(f"After adding a city: {student}")
# Modify an existing value
student['age'] = 21
print(f"After modifying age: {student}")
23100BTCSE15059 Rudraksh Mishra Advanced Java-BTIT410M(P)
Shri Vaishnav Vidyapeeth Vishwavidyalaya
Shri Shri Vaishnav Institute of Information Technology
Department of Computer Science Engineering
# Remove a key-value pair
del student['major']
print(f"After removing major: {student}")
4. Output:
5. Quiz and Viva Questions:
5.1 Quiz Multiple Choice Questions (MCQs):
1. Which symbols are used to create a dictionary?
a) []
b) ()
c) {}
d) <>
Answer: c) {}
2. In a dictionary, data is stored as...
a) A sequence of items
b) Key-value pairs
c) A set of unique items
d) A list of lists
Answer: b) Key-value pairs
3. How do you access the value associated with the key 'name' in a
dictionary d?
23100BTCSE15059 Rudraksh Mishra Advanced Java-BTIT410M(P)
Shri Vaishnav Vidyapeeth Vishwavidyalaya
Shri Shri Vaishnav Institute of Information Technology
Department of Computer Science Engineering
a) d.get('name')
b) d['name']
c) d.name
d) Both a and b
Answer: d) Both a and b
4. What happens if you assign a value to a key that already exists in a
dictionary?
a) A KeyError is raised.
b) The new value is ignored.
c) The original value is updated with the new one.
d) A new key-value pair is created.
Answer: c) The original value is updated with the new one.
5. Which keyword is used to remove a key-value pair from a dictionary?
a) remove
b) delete
c) del
d) erase
Answer: c) del
5.2 Viva Questions:
1. What is the main difference between a dictionary and a list?
2. What are the rules for dictionary keys? (e.g., uniqueness, data type).
3. What happens if you try to access a key that does not exist in the
dictionary?
4. How can you get a list of all the keys or all the values from a dictionary?
23100BTCSE15059 Rudraksh Mishra Advanced Java-BTIT410M(P)
Shri Vaishnav Vidyapeeth Vishwavidyalaya
Shri Shri Vaishnav Institute of Information Technology
Department of Computer Science Engineering
5. Why are dictionaries considered one of Python's most powerful data
structures?
23100BTCSE15059 Rudraksh Mishra Advanced Java-BTIT410M(P)
Shri Vaishnav Vidyapeeth Vishwavidyalaya
Shri Shri Vaishnav Institute of Information Technology
Department of Computer Science Engineering
Experiment - 14
1. Title:
To find reverse of given number using function.
2. Objective:
The objective is to learn how to encapsulate logic within a Python function
by creating a program that reverses an integer.
3. Solution:
def reverse_integer(number):
reversed_number = 0
while number > 0:
digit = number % 10
reversed_number = (reversed_number * 10) + digit
number = number // 10
return reversed_number
# Main program
num = int(input("Enter a number: "))
result = reverse_integer(num)
print(f"The reverse of {num} is {result}")
4. Output:
5. Quiz and Viva Questions:
23100BTCSE15059 Rudraksh Mishra Advanced Java-BTIT410M(P)
Shri Vaishnav Vidyapeeth Vishwavidyalaya
Shri Shri Vaishnav Institute of Information Technology
Department of Computer Science Engineering
5.1 Quiz Multiple Choice Questions (MCQs):
1. Which keyword is used to define a function in Python?
a) function
b) def
c) fun
d) define
Answer: b) def
2. In the expression digit = number % 10, what does the % operator do?
a) Divides the numbers
b) Finds the quotient
c) Finds the remainder
d) Performs floor division
Answer: c) Finds the remainder
3. What is the purpose of the return statement in a function?
a) To print a value to the screen
b) To stop the execution of the entire program
c) To send a value back to the place where the function was called
d) To get input from the user
Answer: c) To send a value back to the place where the function was
called
4. The expression number // 10 effectively does which of the following?
a) Gets the last digit of the number
b) Multiplies the number by 10
c) Removes the last digit from the number
23100BTCSE15059 Rudraksh Mishra Advanced Java-BTIT410M(P)
Shri Vaishnav Vidyapeeth Vishwavidyalaya
Shri Shri Vaishnav Institute of Information Technology
Department of Computer Science Engineering
d) Converts the number to a float
Answer: c) Removes the last digit from the number
5. If you call reverse_integer(520), what will be the output?
a) 25
b) 025
c) 52
d) 250
Answer: a) 25
5.2 Viva Questions:
1. Explain the logic inside the while loop. How does it build the reversed
number?
2. Why is it beneficial to put the reversing logic inside a function?
3. What is the difference between a function parameter (like number)
and a return value?
4. How would you modify this function to also work correctly for negative
numbers (e.g., reversing -123 to -321)?
5. Can you think of a completely different way to reverse a number in
Python, perhaps using strings?
23100BTCSE15059 Rudraksh Mishra Advanced Java-BTIT410M(P)
Shri Vaishnav Vidyapeeth Vishwavidyalaya
Shri Shri Vaishnav Institute of Information Technology
Department of Computer Science Engineering
Experiment - 15
1. Title:
To call data member and function using classes and objects.
2. Objective:
The objective of this experiment is to understand the basics of Object-
Oriented Programming (OOP) by creating a Python class with attributes
(data members) and methods (functions), then instantiating an object to
access them.
3. Solution:
class Dog:
# This is the constructor
def __init__(self, name, breed):
# These are data members (attributes)
self.name = name
self.breed = breed
# This is a member function (method)
def bark(self):
print(f"{self.name} says Woof!")
# Create an object (instance) of the Dog class
my_dog = Dog("Buddy", "Golden Retriever")
# Accessing a data member directly
print(f"My dog's name is {my_dog.name}.")
# Calling a member function
my_dog.bark()
4. Output:
23100BTCSE15059 Rudraksh Mishra Advanced Java-BTIT410M(P)
Shri Vaishnav Vidyapeeth Vishwavidyalaya
Shri Shri Vaishnav Institute of Information Technology
Department of Computer Science Engineering
5. Quiz and Viva Questions:
5.1 Quiz Multiple Choice Questions (MCQs):
1. Which keyword is used to create a class in Python?
a) object
b) class
c) def
d) new
Answer: b) class
2. What is an object?
a) A template or blueprint for creating things.
b) A specific instance of a class.
c) A built-in function in Python.
d) A type of variable.
Answer: b) A specific instance of a class.
3. What is the special name for the method that initializes an object's attributes?
a) __main__
b) __start__
c) __init__
d) __setup__
Answer: c) __init__
4. The first parameter of any method in a class is conventionally named...?
a) this
23100BTCSE15059 Rudraksh Mishra Advanced Java-BTIT410M(P)
Shri Vaishnav Vidyapeeth Vishwavidyalaya
Shri Shri Vaishnav Institute of Information Technology
Department of Computer Science Engineering
b) object
c) instance
d) self
Answer: d) self
5. How do you access the name attribute of an object called my_dog?
a) my_dog['name']
b) get_name(my_dog)
c) my_dog.name
d) name(my_dog)
Answer: c) my_dog.name
5.2 Viva Questions:
1. In your own words, what is the difference between a class and an
object?
2. What is the purpose of the __init__ method? Is it required in every class?
3. Explain the role of the self keyword.
4. What are attributes and methods in the context of a class?
5. What are the main advantages of using classes to structure your code?
23100BTCSE15059 Rudraksh Mishra Advanced Java-BTIT410M(P)
Shri Vaishnav Vidyapeeth Vishwavidyalaya
Shri Shri Vaishnav Institute of Information Technology
Department of Computer Science Engineering
Experiment - 16
1. Title:
To read 3 subject marks and display pass or failed using class and object.
2. Objective:
The objective is to apply OOP concepts to a practical problem by creating
a class to manage student marks and determine their pass/fail status
based on a defined criterion.
3. Solution:
class Student:
def __init__(self):
self.marks1 = 0
self.marks2 = 0
self.marks3 = 0
def read_marks(self):
self.marks1 = int(input("Enter marks for Subject 1: "))
self.marks2 = int(input("Enter marks for Subject 2: "))
self.marks3 = int(input("Enter marks for Subject 3: "))
def display_result(self):
passing_mark = 40
if self.marks1 >= passing_mark and self.marks2 >= passing_mark and self.marks3 >=
passing_mark:
print("Result: Pass")
else:
print("Result: Fail")
23100BTCSE15059 Rudraksh Mishra Advanced Java-BTIT410M(P)
Shri Vaishnav Vidyapeeth Vishwavidyalaya
Shri Shri Vaishnav Institute of Information Technology
Department of Computer Science Engineering
# Create a student object
s1 = Student()
# Call methods to read marks and display the result
s1.read_marks()
s1.display_result()
4. Output:
5. Quiz and Viva Questions:
5.1 Quiz Multiple Choice Questions (MCQs):
1. In the Student class, marks1 is an example of a(n)...
a) Method
b) Global variable
c) Attribute
d) Class variable
Answer: c) Attribute
2. The read_marks function in the class is known as a...
a) Constructor
b) Method
c) Parameter
d) Module
23100BTCSE15059 Rudraksh Mishra Advanced Java-BTIT410M(P)
Shri Vaishnav Vidyapeeth Vishwavidyalaya
Shri Shri Vaishnav Institute of Information Technology
Department of Computer Science Engineering
Answer: b) Method
3. What does the self parameter represent inside a method?
a) The class itself
b) A global variable
c) The specific object on which the method was called
d) The method's return value
Answer: c) The specific object on which the method was called
4. How is the pass/fail condition checked in the display_result method?
a) With a for loop
b) With an if/else statement and the and operator
c) With a try/except block
d) With a while loop
Answer: b) With an if/else statement and the and operator
5. When you create s1 = Student(), you are creating a(n)...
a) Instance of the class
b) Copy of the class
c) Child of the class
d) Function
Answer: a) Instance of the class
5.2 Viva Questions:
1. Why is it better to use a class for this problem instead of just using functions?
2. How would you change the logic if a student needed to pass based on their average score
instead of individual subject scores?
3. Explain the purpose of the __init__ method in this specific class.
23100BTCSE15059 Rudraksh Mishra Advanced Java-BTIT410M(P)
Shri Vaishnav Vidyapeeth Vishwavidyalaya
Shri Shri Vaishnav Institute of Information Technology
Department of Computer Science Engineering
4. How could you create and check the results for two different student objects?
Experiment - 17
1. Title:
To handle user defined exception for given problem.
2. Objective:
The objective is to learn how to create a custom, user-defined exception
class and then use the raise keyword to trigger it based on a specific
condition, handling it with a try...except block.
3. Solution:
# Create a custom exception class inheriting from Exception
class InvalidAgeError(Exception):
"Raised when the input value is less than 18"
pass
# Main program logic
try:
age = int(input("Enter your age: "))
if age < 18:
raise InvalidAgeError
else:
print("Age is valid. You are eligible.")
except InvalidAgeError:
print("Error: You must be at least 18 years old to be eligible.")
23100BTCSE15059 Rudraksh Mishra Advanced Java-BTIT410M(P)
Shri Vaishnav Vidyapeeth Vishwavidyalaya
Shri Shri Vaishnav Institute of Information Technology
Department of Computer Science Engineering
except ValueError:
print("Error: Please enter a valid number for age.")
4. Output:
5. Quiz and Viva Questions:
5.1 Quiz Multiple Choice Questions (MCQs):
1. How do you create a custom exception class named MyError?
a) def MyError(Exception): pass
b) exception MyError: pass
c) class MyError(Exception): pass
d) MyError = Exception()
Answer: c) class MyError(Exception): pass
2. Which keyword is used to manually trigger an exception?
a) throw
b) try
c) except
d) raise
Answer: d) raise
3. The code that might raise an exception should be placed inside a ___
block.
a) try
23100BTCSE15059 Rudraksh Mishra Advanced Java-BTIT410M(P)
Shri Vaishnav Vidyapeeth Vishwavidyalaya
Shri Shri Vaishnav Institute of Information Technology
Department of Computer Science Engineering
b) catch
c) finally
d) raise
Answer: a) try
4. To handle a specific exception, you use a(n) ___ block.
a) try
b) except
c) handle
d) if
Answer: b) except
5. What is the main purpose of creating a user-defined exception?
a) To make the program run faster.
b) To handle specific, custom error conditions in a clear way.
c) To replace all if/else statements.
d) To stop the program when an error occurs.
Answer: b) To handle specific, custom error conditions in a clear way.
5.2 Viva Questions:
1. In your own words, what is an exception?
2. Why is it useful to create your own exception types instead of using
Python's built-in ones for every situation?
3. Explain the flow of program execution when an exception is raised
inside a try block.
4. What is the difference between the raise keyword and the except
keyword?
23100BTCSE15059 Rudraksh Mishra Advanced Java-BTIT410M(P)
Shri Vaishnav Vidyapeeth Vishwavidyalaya
Shri Shri Vaishnav Institute of Information Technology
Department of Computer Science Engineering
5. What would happen in the sample program if a user entered "twenty"
instead of 20? Which except block would handle it?
Experiment - 18
1. Title:
To create an array and check the following using Numpy module:
a. Type of array
b. Axes of array
c. Shape of array
d. Type of elements in array
2. Objective:
The objective is to learn how to create a basic NumPy array and inspect its fundamental
properties, such as its type, dimensions (axes), shape, and the data type of its elements.
3. Solution:
import numpy as np
# Create a 2-dimensional NumPy array
my_array = np.array([[5, 10, 15], [20, 25, 30]])
print(f"Array created:\n{my_array}\n")
# a. Check the type of the array object itself
print(f"a. Type of array: {type(my_array)}")
# b. Check the number of axes (dimensions)
print(f"b. Axes of array: {my_array.ndim}")
# c. Check the shape (rows, columns)
23100BTCSE15059 Rudraksh Mishra Advanced Java-BTIT410M(P)
Shri Vaishnav Vidyapeeth Vishwavidyalaya
Shri Shri Vaishnav Institute of Information Technology
Department of Computer Science Engineering
print(f"c. Shape of array: {my_array.shape}")
# d. Check the data type of the elements
print(f"d. Type of elements: {my_array.dtype}")
4. Output:
5. Quiz and Viva Questions:
5.1 Quiz Multiple Choice Questions (MCQs):
1. What is the standard convention for importing the NumPy library?
a) import numpy
b) import numpy as np
c) import num as p
d) import numpy as n
Answer: b) import numpy as np
2. Which attribute is used to find the number of dimensions of a NumPy
array?
a) .shape
b) .dim
c. .axes
d) .ndim
Answer: d) .ndim
23100BTCSE15059 Rudraksh Mishra Advanced Java-BTIT410M(P)
Shri Vaishnav Vidyapeeth Vishwavidyalaya
Shri Shri Vaishnav Institute of Information Technology
Department of Computer Science Engineering
3. If an array has a shape of (3, 4), how many rows does it have?
a) 3
b) 4
c) 7
d) 12
Answer: a) 3
4. The .dtype attribute of a NumPy array tells you...?
a) The type of the array object itself
b) The data type of the elements inside the array
c) The shape of the array
d) The total number of elements
Answer: b) The data type of the elements inside the array
5. What does numpy.ndarray stand for?
a) NumPy Data Array
b) NumPy N-Dimensional Array
c) NumPy Numbered Array
d) NumPy Decimal Array
Answer: b) NumPy N-Dimensional Array
5.2 Viva Questions:
1. What is NumPy and why is it preferred over standard Python lists for
numerical computations?
2. What does the "shape" of an array, like (2, 3), represent?
3. How is my_array.ndim related to my_array.shape?
4. How would you create a simple one-dimensional array using NumPy?
23100BTCSE15059 Rudraksh Mishra Advanced Java-BTIT410M(P)
Shri Vaishnav Vidyapeeth Vishwavidyalaya
Shri Shri Vaishnav Institute of Information Technology
Department of Computer Science Engineering
5. Why is the data type (dtype) of elements an important property in
NumPy arrays?
23100BTCSE15059 Rudraksh Mishra Advanced Java-BTIT410M(P)
Shri Vaishnav Vidyapeeth Vishwavidyalaya
Shri Shri Vaishnav Institute of Information Technology
Department of Computer Science Engineering
Experiment - 19
1. Title:
To concatenate the dataframes with two different objects.
2. Objective:
The objective is to learn how to combine two separate Pandas DataFrame objects into a
single DataFrame along a specific axis using the pd.concat() function.
3. Solution:
import pandas as pd
# Create the first DataFrame object
df_staff = pd.DataFrame({
'ID': [101, 102],
'Name': ['Alice', 'Bob'],
'Role': ['Teacher', 'Admin']
})
# Create the second DataFrame object
df_students = pd.DataFrame({
'ID': [501, 502],
'Name': ['Charlie', 'David'],
'Role': ['Student', 'Student']
})
print("First DataFrame:")
print(df_staff)
print("\nSecond DataFrame:")
print(df_students)
# Concatenate the two DataFrames vertically
combined_df = pd.concat([df_staff, df_students], ignore_index=True)
print("\nConcatenated DataFrame:")
print(combined_df)
4. Output:
23100BTCSE15059 Rudraksh Mishra Advanced Java-BTIT410M(P)
Shri Vaishnav Vidyapeeth Vishwavidyalaya
Shri Shri Vaishnav Institute of Information Technology
Department of Computer Science Engineering
5. Quiz and Viva Questions:
5.1 Quiz Multiple Choice Questions (MCQs):
1. What is the standard convention for importing the Pandas library?
a) import pandas as p
b) import pandas as pan
c) import pandas as pd
d) import pandas as pds
Answer: c) import pandas as pd
2. Which function is used to concatenate DataFrame objects in Pandas?
a) pd.combine()
b) pd.merge()
c) pd.join()
d) pd.concat()
Answer: d) pd.concat()
3. What type of argument does the pd.concat() function expect for the
objects to be concatenated?
23100BTCSE15059 Rudraksh Mishra Advanced Java-BTIT410M(P)
Shri Vaishnav Vidyapeeth Vishwavidyalaya
Shri Shri Vaishnav Institute of Information Technology
Department of Computer Science Engineering
a) A tuple of DataFrames
b) A dictionary of DataFrames
c) A list of DataFrames
d) Two separate DataFrame arguments
Answer: c) A list of DataFrames
4. What is the purpose of the ignore_index=True parameter in
pd.concat()?
a) To ignore the column headers.
b) To create a new, continuous index for the resulting DataFrame.
c) To drop the index column entirely.
d) To cause an error if indices are not unique.
Answer: b) To create a new, continuous index for the resulting DataFrame.
5. By default, pd.concat() joins DataFrames along which axis?
a) axis=0 (rows)
b) axis=1 (columns)
c) axis=None (no axis)
d) axis='auto'
Answer: a) axis=0 (rows)
5.2 Viva Questions:
1. What does it mean to "concatenate" DataFrames?
2. What would happen if you tried to concatenate two DataFrames that
do not have the same columns?
23100BTCSE15059 Rudraksh Mishra Advanced Java-BTIT410M(P)
Shri Vaishnav Vidyapeeth Vishwavidyalaya
Shri Shri Vaishnav Institute of Information Technology
Department of Computer Science Engineering
3. How would the operation change if you specified axis=1 in the
pd.concat() function?
4. Why is resetting the index often a good idea after concatenating
DataFrames by rows?
5. What is the difference between pd.concat() and pd.merge()?
23100BTCSE15059 Rudraksh Mishra Advanced Java-BTIT410M(P)
Shri Vaishnav Vidyapeeth Vishwavidyalaya
Shri Shri Vaishnav Institute of Information Technology
Department of Computer Science Engineering
Experiment - 20
1. Title:
To Demonstrate how to Draw a Scatter Plot, Bar Graph and Pie Chart using Matplotlib.
2. Objective:
The objective is to learn how to visualize data by creating three fundamental plots—a scatter
plot, a bar graph, and a pie chart—using the popular Matplotlib library in Python.
3. Solution:
This experiment is divided into three parts, one for each type of plot.
a. Scatter Plot
A scatter plot is used to display values for typically two variables for a set of data.
Python
import matplotlib.pyplot as plt
# Sample data
x_values = [1, 2, 3, 4, 5, 6, 7, 8]
y_values = [2, 5, 3, 8, 4, 6, 7, 5]
plt.scatter(x_values, y_values, color='red')
plt.title("Sample Scatter Plot")
plt.xlabel("X-Axis")
plt.ylabel("Y-Axis")
plt.show()
b. Bar Graph
A bar graph represents categorical data with rectangular bars with heights proportional to the values
that they represent.
Python
import matplotlib.pyplot as plt
# Sample data
categories = ['Group A', 'Group B', 'Group C']
values = [75, 90, 60]
plt.bar(categories, values, color='green')
plt.title("Sample Bar Graph")
plt.xlabel("Groups")
plt.ylabel("Scores")
plt.show()
c. Pie Chart
23100BTCSE15059 Rudraksh Mishra Advanced Java-BTIT410M(P)
Shri Vaishnav Vidyapeeth Vishwavidyalaya
Shri Shri Vaishnav Institute of Information Technology
Department of Computer Science Engineering
A pie chart is a circular statistical graphic, which is divided into slices to illustrate numerical
proportion.
Python
import matplotlib.pyplot as plt
# Sample data
sizes = [25, 35, 30, 10]
labels = ['Apples', 'Bananas', 'Cherries', 'Dates']
plt.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=90)
plt.title("Sample Pie Chart")
plt.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.
plt.show()
4. Output:
5. Quiz and Viva Questions:
5.1 Quiz Multiple Choice Questions (MCQs):
1· What is the standard alias for matplotlib.pyplot? a) mpl b) plot c) mat d) plt
Answer: d) plt
· · Which function is used to create a scatter plot? a) plt.plot() b) plt.scatter() c)
plt.bar() d) plt.pie() Answer: b) plt.scatter()
· · To add a title to your plot, you use which function? a) plt.xlabel() b) plt.title()
c) plt.legend() d) plt.header() Answer: b) plt.title()
23100BTCSE15059 Rudraksh Mishra Advanced Java-BTIT410M(P)
Shri Vaishnav Vidyapeeth Vishwavidyalaya
Shri Shri Vaishnav Institute of Information Technology
Department of Computer Science Engineering
· · In a pie chart, what does the autopct parameter do? a) Sets the color of the slices. b)
Sets the labels for the slices. c) Automatically calculates and displays the percentage for each
slice. d) Rotates the pie chart. Answer: c) Automatically calculates and displays the
percentage for each slice.
· · Which function actually displays the plot on the screen? a) plt.render() b)
plt.draw() c) plt.show() d) plt.display() Answer: c) plt.show()
5.2 Viva Questions:
When would you choose to use a scatter plot over a bar graph?
What is the purpose of the plt.xlabel() and plt.ylabel() functions?
In a bar graph, what kind of data is typically represented on the x-axis and
y-axis?
Why is plt.axis('equal') important for a pie chart?
What is the last command you must issue to see your plot, and what does
it do?
23100BTCSE15059 Rudraksh Mishra Advanced Java-BTIT410M(P)