BCA-502 Python
BCA-502 Python
Python & AI
Guess Questions 2025
ADARSH SINGH
collegebuddy.co.in
PYTHON (BCA-502)
Guess questions for BCA 5th semester exam 2025
----------------------------------------------------------------------------------------
Q1. Explain different types of operators in Python with examples. How do built-in functions help in
handling numeric data types?
Q2. (a) What are conditional statements in Python? Explain if-else, nested if with examples.
(b) Write a Python program to check whether a number is prime or not.
Q4. Differentiate between List, Tuple, Set, and Dictionary in Python with examples.
Q5. Explain different string functions in Python. Write a program to check if a given string is a
palindrome.
Q6. Explain the types of file handling in Python. Write a Python program to read a text file and
count the number of words.
Q9. What is the Eval function in Python ? Write advantages of using eval function. Write a
program to evaluate a mathematical expression entered by a user using the eval function.
Q11. What is the re (Regular Expressions) module in Python? Explain with examples of search(),
match(), and findall().
Q12. What is a module and package in Python? Explain how to create and import a module.
Q13. Explain the different types of machine learning (Supervised, Unsupervised, Reinforcement
Learning) with examples.
Q14. Write a Python program to implement the Minimax algorithm for game playing.
Q15. Explain SQL database connectivity in Python. Write a program to connect Python with
MySQL and retrieve data from a table.
collegebuddy.co.in
Q1. Explain different types of operators in Python with examples. How do built-in functions
help in handling numeric data types?
Python operators, functions, and modules make working with numbers in Python flexible and
efficient, allowing for anything from basic calculations to advanced mathematical and statistical
operations.
Arithmetic Operators
a = 10
b = 3
print(a + b) # Output: 13
print(a ** b) # Output: 1000
Assignment Operators
collegebuddy.co.in
x = 10
x += 5 # Equivalent to x = x + 5
print(x) # Output: 15
a = 5
b = 8
Logical Operators
x = 10
y = 5
collegebuddy.co.in
Bitwise Operators
a = 5 # 101 in binary
b = 3 # 011 in binary
Membership Operators
Used to check whether a value exists in a sequence (list, tuple, string, etc.).
collegebuddy.co.in
Identity Operators
x = [1, 2, 3]
y = [1, 2, 3]
Built-in Functions
● Type Conversion:
○ int(): Converts a value to an integer.
○ float(): Converts a value to a floating-point number.
○ complex(): Converts a value to a complex number (e.g., complex(5, 3) → 5 +
3j).
● Basic Math:
○ abs(): Returns the absolute value of a number.
○ round(): Rounds a floating-point number to a specified number of decimal places.
○ pow(): Raises a number to a specific power (pow(base, exp[, mod])).
● Miscellaneous:
○ divmod(): Returns a tuple of quotient and remainder, e.g., divmod(10, 3) → (3,
1).
○ sum(): Adds up all elements in an iterable.
○ min(), max(): Find the smallest or largest number in an iterable.
collegebuddy.co.in
Standard Library Modules
collegebuddy.co.in
Q2. (a) What are conditional statements in Python? Explain if-else, nested if with examples.
(b) Write a Python program to check whether a number is prime or not.
Conditional statements are used in Python to control the flow of execution based on certain
conditions. The condition is evaluated as True or False, and the corresponding block of code is
executed.
1️⃣ if Statement
if condition:
Example
age = 18
Output:
if condition:
else:
collegebuddy.co.in
Example
num = -5
if num >= 0:
print("Positive Number")
else:
print("Negative Number")
Output:
Negative Number
Syntax
if condition1:
elif condition2:
else:
Example
marks = 75
print("Grade: A")
collegebuddy.co.in
print("Grade: B")
print("Grade: C")
else:
print("Fail")
Output:
Grade: B
Syntax
if condition1:
if condition2:
Example
num = 10
if num > 0:
print("Positive number")
if num % 2 == 0:
print("Even number")
Output:
Positive number
Even number
collegebuddy.co.in
(b) Python Program to Check Whether a Number is Prime or Not
A prime number is a number greater than 1 that has only two factors: 1 and itself.
import math
def is_prime(n):
if n < 2:
return False
if n % i == 0:
return False
return True
# Checking if prime
if is_prime(num):
else:
collegebuddy.co.in
Q3. Explain looping structures in Python (for, while, do-while).
Write a Python program to print the following pyramid pattern:
collegebuddy.co.in
Q4. Differentiate between List, Tuple, Set, and Dictionary in Python with examples.
A List is an ordered collection that is mutable, meaning its elements can be modified after
creation. It allows duplicate values and supports indexing & slicing.
Characteristics:
# Accessing Elements
print(my_list[1]) # Output: 20
# Modifying List
# Removing Elements
collegebuddy.co.in
2️⃣ Tuple (Ordered & Immutable)
A Tuple is an ordered collection but immutable, meaning elements cannot be modified after
creation. It allows duplicate values and supports indexing & slicing.
Characteristics:
# Accessing Elements
print(my_tuple[1]) # Output: 20
A Set is an unordered collection of unique elements. It does not allow duplicates and does not
support indexing or slicing.
Characteristics:
# Adding Elements
my_set.add(60) # Adds 60
# Removing Elements
my_set.remove(30)
collegebuddy.co.in
4️⃣ Dictionary (Key-Value Pair, Mutable & Ordered)
A Dictionary is a collection of key-value pairs, where each key is unique and maps to a specific
value.
Characteristics:
# Accessing Values
# Modifying Dictionary
print(my_dict)
collegebuddy.co.in
Practical Example to Show Differences
my_list = [1, 2, 3]
my_list.append(4) # Modifiable
print("List:", my_list)
my_tuple = (1, 2, 3)
my_set = {1, 2, 3, 3}
print("Set:", my_set)
my_dict["age"] = 26 # Changeable
print("Dictionary:", my_dict)
Output
List: [1, 2, 3, 4]
Tuple: (1, 2, 3)
Set: {1, 2, 3, 4}
collegebuddy.co.in
Q5. Explain different string functions in Python. Write a program to check if a given string is
a palindrome.
In Python, strings are sequences of characters enclosed in single (' '), double (" "), or triple (''' ''' or
""" """) quotes. Python provides various built-in string functions to manipulate strings efficiently.
collegebuddy.co.in
startswit Checks if string starts with "hello".startswith("he") → True
h() a substring
print(len(text)) # Output: 21
print(text.count("i")) # Output: 2
collegebuddy.co.in
Python Program to Check if a String is a Palindrome
def is_palindrome(s):
# User input
if is_palindrome(text):
print(f"'{text}' is a Palindrome!")
else:
Example Outputs
'Madam' is a Palindrome!
collegebuddy.co.in
Q6. Explain the types of file handling in Python. Write a Python program to read a text file
and count the number of words.
File handling refers to the process of performing operations on a file such as creating, opening,
reading, writing and closing it, through a programming interface. It involves managing the data
flow between the program and the file system on the storage device, ensuring that data is
handled safely and efficiently.
Python provides built-in functions to work with text files (.txt) and binary files (.bin, .jpg, .png,
etc.).
There are two main types of file handling based on file formats:
Mode Description
'r' Read mode (default). Opens a file for reading. Raises an error if the file doesn’t exist.
'w' Write mode. Creates a file if it doesn’t exist. Overwrites existing content.
'a' Append mode. Creates a file if it doesn’t exist. Adds data at the end of the file.
'wb' Write binary mode. Used for binary files (images, videos).
collegebuddy.co.in
'rb' Read binary mode. Used for binary files.
Syntax
Method Description
collegebuddy.co.in
file = open("sample.txt", "r")
file.close()
file.close()
6️⃣ Python Program to Read a Text File and Count the Number of Words
The program reads a text file and counts the number of words.
def count_words(filename):
try:
words = text.split()
return len(words)
collegebuddy.co.in
except FileNotFoundError:
word_count = count_words(file_name)
Example Output
collegebuddy.co.in
A lambda function in Python is a small, anonymous function that can have any number of
arguments but only one expression. It is defined using the lambda keyword and is commonly used
for short, simple operations.
Characteristic Description
Single Expression They contain only one expression (cannot have multiple statements).
Multiple Arguments Can take multiple arguments but return only one value.
Return Value Automatically No need to use the return keyword; the result is returned
automatically.
Used in Higher-Order Often used with functions like map(), filter(), and sorted().
Functions
Short & Readable Best for short, simple operations (not recommended for complex logic).
# Regular function
def square(x):
return x * x
square_lambda = lambda x: x * x
# Output
print(square_lambda(5)) # Output: 25
collegebuddy.co.in
4️⃣ Examples of Lambda Functions in Use
add = lambda x, y: x + y
numbers = [1, 2, 3, 4, 5]
nums = [1, 2, 3, 4, 5, 6]
collegebuddy.co.in
Q8. (a) Explain exception handling in Python with examples.
An exception in Python is an error that occurs during program execution. Exception handling
allows the program to catch and handle errors instead of crashing.
Exception Description
try:
except ExceptionType:
collegebuddy.co.in
Example: Handling ZeroDivisionError
try:
result = 10 / 0
except ZeroDivisionError:
Output:
try:
content = file.read()
except FileNotFoundError:
finally:
try:
except ValueError:
else:
collegebuddy.co.in
(b) Write a program to handle division by zero error.
try:
# User input
# Division operation
# Print result
print("Result:", result)
except ZeroDivisionError:
except ValueError:
finally:
print("Execution completed.")
collegebuddy.co.in
Example Outputs
Enter numerator: 10
Enter denominator: 2
Result: 5.0
Execution completed.
Enter numerator: 10
Enter denominator: 0
Execution completed.
Enter numerator: 10
Execution completed.
collegebuddy.co.in
Q9. What is the Eval function in Python ? Write advantages of using eval function. Write a
program to evaluate a mathematical expression entered by a user using the eval function.
The eval() function evaluates a string as a Python expression and returns the result. It is used for
dynamically executing expressions that are input or generated at runtime.
Syntax of eval()
globals and locals: Optional dictionaries specifying the global and local scope for evaluation.
This program demonstrates the use of eval() to evaluate a mathematical expression entered by
the user.
How It Works
● User Input: The user enters a mathematical expression as a string (e.g., 2 + 3 * 4).
● Evaluate with eval():
○ The string is passed to eval(), which interprets and computes the result.
● Security Risk: Avoid using eval() with untrusted input as it can execute arbitrary code.
Example: If someone enters __import__('os').system('rm -rf /'), it could harm the system.
collegebuddy.co.in
Q10. Write a Python program to multiply two matrices.
if cols_A != rows_B:
return None
for i in range(rows_A):
for j in range(cols_B):
for k in range(cols_A):
return result
# Example Matrices
A = [[1, 2],
[3, 4]]
B = [[5, 6],
[7, 8]]
collegebuddy.co.in
# Multiply Matrices
result = multiply_matrices(A, B)
if result:
print("Resultant Matrix:")
print(row)
collegebuddy.co.in
Q11. What is the re (Regular Expressions) module in Python? Explain with examples of
search(), match(), and findall().
The re (Regular Expressions) module in Python is used for pattern matching, searching, and
manipulating text. It allows us to find, replace, and extract specific patterns in strings using regex
(regular expressions).
import re
Function Description
collegebuddy.co.in
4️⃣ Example: Using search(), match(), and findall()
import re
if match:
else:
Output:
import re
if match:
else:
Output:
✔ If the string does not start with "Python", it will return None.
collegebuddy.co.in
● re.findall() → Returns All Matches in a List
○ Finds all occurrences of a pattern.
import re
Output:
collegebuddy.co.in
Q12. What is a module and package in Python? Explain how to create and import a module.
A module in Python is a file that contains Python code (functions, classes, and variables) that can
be reused in other programs.
import math
import random
A module is simply a Python file (.py) that contains functions and variables.
def greet(name):
PI = 3.1416
import my_module
collegebuddy.co.in
● import my_module → Loads the module into the program.
● Use module_name.function_name() to access functions.
A package is a collection of multiple modules organized into a directory with an __init__.py file.
my_package/
│── module1.py
│── module2.py
File: my_package/module1.py
return a + b
File: my_package/module2.py
return a - b
collegebuddy.co.in
4️⃣ Importing Modules in Different Ways
from module import from math import Imports only specific functions.
function sqrt
from module import * from math import * Imports all functions (not recommended).
5️⃣ Summary
🚀
● Importing Modules → Use import module_name or from module import function.
● Helps in structuring large projects and reusing code efficiently.
collegebuddy.co.in
Q13. Explain the different types of machine learning (Supervised, Unsupervised,
Reinforcement Learning) with examples.
Machine Learning (ML) is a branch of Artificial Intelligence (AI) that allows computers to learn
from data without explicit programming. ML is categorized into three main types:
The model learns from this past data and can predict the price for new houses.
Algorithm Usage
collegebuddy.co.in
Support Vector Machines Used for classification tasks.
(SVM)
model = LinearRegression()
model.fit(X, y)
prediction = model.predict([[1800]])
collegebuddy.co.in
2️⃣ Unsupervised Learning (Learning Without Labels)
● Definition: The model is trained on unlabeled data and finds hidden patterns.
● Working: It groups or clusters similar data points without predefined labels.
● Example: Grouping customers based on shopping behavior without knowing predefined
customer categories.
Algorithm Usage
Autoencoders (Neural Networks) Used for anomaly detection and feature extraction.
collegebuddy.co.in
Python Code for Unsupervised Learning (K-Means Clustering)
import numpy as np
X = np.array([[20, 1000], [25, 1200], [30, 5000], [35, 5200], [40, 7000]])
kmeans = KMeans(n_clusters=2)
kmeans.fit(X)
cluster = kmeans.predict(new_customer)
collegebuddy.co.in
3️⃣ Reinforcement Learning (Learning Through Rewards)
● Definition: The model learns by interacting with the environment and receiving rewards or
penalties.
● Working: An agent performs actions in an environment and gets feedback in the form of
rewards or penalties.
● Example: A robot learning to walk by adjusting its movements based on success or failure.
Action Reward/Penalty
The model learns from rewards and makes better decisions over time.
Algorithm Usage
collegebuddy.co.in
Python Code for Reinforcement Learning (Q-Learning Example)
import numpy as np
best_action = np.argmax(rewards)
🏡 ♟️
🛒
Example Predict house prices Customer AI playing chess
segmentation
collegebuddy.co.in
Q14. Write a Python program to implement the Minimax algorithm for game playing.
The Minimax algorithm is used in game-playing AI to choose the best move by evaluating all
possible future moves. It is widely used in two-player games like Tic-Tac-Toe, Chess, and Connect
Four.
import math
board = [
def is_moves_left(board):
if '_' in row:
return True
return False
collegebuddy.co.in
# Evaluate Board: +10 for AI win, -10 for Opponent win, 0 for draw
def evaluate(board):
# Check rows
# Check columns
# Check diagonals
return 0 # No winner
# Minimax Algorithm
score = evaluate(board)
# If AI wins
if score == 10:
if score == -10:
if not is_moves_left(board):
return 0
if is_max:
for i in range(3):
for j in range(3):
return best
else:
for i in range(3):
for j in range(3):
return best
collegebuddy.co.in
# Function to Find the Best Move
def find_best_move(board):
best_val = -math.inf
for i in range(3):
for j in range(3):
best_move = (i, j)
best_val = move_val
return best_move
best_move = find_best_move(board)
collegebuddy.co.in
5️⃣ Example Output
Initial Board:
X | O | X
O | X | O
_ | _ | _
6️⃣ Summary
🚀
✔ Used in Tic-Tac-Toe, Chess, Checkers, and Strategy Games.
✔ Backtracking ensures AI always makes the best move.
collegebuddy.co.in
Q15. Explain SQL database connectivity in Python. Write a program to connect Python with
MySQL and retrieve data from a table.
SQL database connectivity in Python allows programs to interact with databases like MySQL,
PostgreSQL, SQLite, or Oracle. It enables Python to:
✔ Store, update, and delete data in a database.
✔ Execute SQL queries directly from Python.
✔ Automate database operations.
3️⃣ Python Program to Connect Python with MySQL and Retrieve Data
Table Structure
1 Adarsh 20 BCA
2 Harshit 21 MCA
3 Rohan 22 B.Tech
collegebuddy.co.in
import mysql.connector
conn = mysql.connector.connect(
host="localhost",
user="root",
password="password",
database="college_db"
cursor = conn.cursor()
rows = cursor.fetchall()
print("Student Data:")
print(row)
cursor.close()
conn.close()
collegebuddy.co.in
4️⃣ Explanation of Code
Student Data:
6️⃣ Summary
🚀
● Ensures efficient data management using Python scripts.
● Always close the database connection to free up resources.
collegebuddy.co.in