0% found this document useful (0 votes)
8 views52 pages

BCA-502 Python

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
8 views52 pages

BCA-502 Python

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

BCA-502

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.

Q3. Explain looping structures in Python (for, while, do-while).​


Write a Python program to print the following pyramid pattern:

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.

Q7. What is a lambda function? Explain its characteristics with an example.

Q8. (a) Explain exception handling in Python with examples.​


(b) Write a program to handle division by zero error.

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.

Q10. Write a Python program to multiply two matrices.

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

Used to perform mathematical operations.

a = 10
b = 3
print(a + b) # Output: 13
print(a ** b) # Output: 1000

Assignment Operators

Used to assign values to variables.

collegebuddy.co.in
x = 10

x += 5 # Equivalent to x = x + 5

print(x) # Output: 15

Comparison (Relational) Operators

Used to compare values and return a Boolean (True or False).

a = 5

b = 8

print(a < b) # Output: True

Logical Operators

Used to perform logical operations.

x = 10

y = 5

print(x > 5 and y < 10) # Output: True

collegebuddy.co.in
Bitwise Operators

Used to perform bitwise operations on numbers.

a = 5 # 101 in binary

b = 3 # 011 in binary

print(a & b) # Output: 1

Membership Operators

Used to check whether a value exists in a sequence (list, tuple, string, etc.).

fruits = ["apple", "banana", "cherry"]

print("banana" in fruits) # Output: True

collegebuddy.co.in
Identity Operators

Used to compare the memory locations of two objects.

x = [1, 2, 3]

y = [1, 2, 3]

print(x is y) # Output: False (different memory locations)

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

●​ math: Provides a range of mathematical functions.


○​ math.sqrt(x): Returns the square root of x.
○​ math.factorial(x): Returns the factorial of x.
○​ math.gcd(a, b): Returns the greatest common divisor.
○​ math.pi, math.e: Constants for π and e.
○​ Trigonometric functions: math.sin(), math.cos(), math.tan().
○​ Rounding functions: math.floor(), math.ceil().

●​ random: For generating random numbers.


○​ random.randint(a, b): Returns a random integer between a and b.
○​ random.choice(sequence): Returns a random element from a sequence.
○​ random.uniform(a, b): Returns a random floating-point number between a and b.

●​ decimal: For decimal floating-point arithmetic with high precision.


○​ decimal.Decimal(): Creates a decimal object.
○​ decimal.getcontext().prec = n: Sets the precision to n digits.

●​ fractions: For rational number calculations.


○​ fractions.Fraction(numerator, denominator): Creates a fraction.
○​ Provides accurate fractional operations like addition, subtraction, etc.

●​ statistics: For statistical calculations.


○​ statistics.mean(data): Returns the mean (average) of data.
○​ statistics.median(data): Returns the median of data.
○​ statistics.mode(data): Returns the mode of data.

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.

(a) Conditional Statements in Python

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.

Types of Conditional Statements in Python

1.​ if Statement → Executes a block of code if the condition is True.


2.​ if-else Statement → Executes one block if True, another block if False.
3.​ elif Statement → Used when multiple conditions need to be checked.
4.​ Nested if → An if statement inside another if statement.

1️⃣ if Statement

Executes a block of code only when the condition is True.

if condition:

# Code to execute if condition is True

Example

age = 18

if age >= 18:

print("You are eligible to vote!")

Output:

You are eligible to vote!

2️⃣ if-else Statement

Executes one block if the condition is True, another block if False.

if condition:

# Code if condition is True

else:

# Code if condition is False

collegebuddy.co.in
Example

num = -5

if num >= 0:

print("Positive Number")

else:

print("Negative Number")

Output:

Negative Number

3️⃣ elif Statement

Used when multiple conditions need to be checked.

Syntax

if condition1:

# Code if condition1 is True

elif condition2:

# Code if condition2 is True

else:

# Code if all conditions are False

Example

marks = 75

if marks >= 90:

print("Grade: A")

elif marks >= 75:

collegebuddy.co.in
print("Grade: B")

elif marks >= 50:

print("Grade: C")

else:

print("Fail")

Output:

Grade: B

4️⃣ Nested if Statement

An if statement inside another if statement.

Syntax

if condition1:

if condition2:

# Code if both conditions are True

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

# Function to check if a number is prime

def is_prime(n):

if n < 2:

return False

for i in range(2, int(math.sqrt(n)) + 1): # Check till sqrt(n)

if n % i == 0:

return False

return True

# Input from the user

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

# Checking if prime

if is_prime(num):

print(num, "is a Prime Number")

else:

print(num, "is NOT a Prime Number")

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.

Python provides four main built-in collection types:

●​ List (list) → Ordered, Mutable


●​ Tuple (tuple) → Ordered, Immutable
●​ Set (set) → Unordered, Unique Elements
●​ Dictionary (dict) → Key-Value Mapping

1️⃣ List (Ordered & Mutable)

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:

✅ Ordered (Elements maintain their order)​


✅ Mutable (Elements can be changed)​
✅ Allows Duplicates (Same values can repeat)​
✅ Indexed & Slicing Supported (Access elements using position)
# Creating a List

my_list = [10, 20, 30, 40, 50]

# Accessing Elements

print(my_list[1]) # Output: 20

# Modifying List

my_list.append(60) # Adds 60 at the end

my_list[0] = 100 # Modifies the first element

print(my_list) # Output: [100, 20, 30, 40, 50, 60]

# Removing Elements

my_list.remove(30) # Removes first occurrence of 30

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:

✅ Ordered (Elements maintain their order)​


❌ Immutable (Cannot be changed once created)​
✅ Allows Duplicates​
✅ Supports Indexing & Slicing
# Creating a Tuple

my_tuple = (10, 20, 30, 40, 50)

# Accessing Elements

print(my_tuple[1]) # Output: 20

3️⃣ Set (Unordered & Unique Elements)

A Set is an unordered collection of unique elements. It does not allow duplicates and does not
support indexing or slicing.

Characteristics:

❌ Unordered (Does not maintain element order)​


✅ Mutable (Can add/remove elements)​
❌ Does NOT allow Duplicates (Ensures unique values)​
❌ No Indexing & Slicing
# Creating a Set

my_set = {10, 20, 30, 40, 50}

# Adding Elements

my_set.add(60) # Adds 60

my_set.add(20) # Duplicate, will not be added

# Removing Elements

my_set.remove(30)

print(my_set) # Output: {10, 20, 40, 50, 60}

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:

✅ Ordered (Maintains insertion order in Python 3.7+)​


✅ Mutable (Can modify values)​
❌ Keys Must Be Unique​
✅ Fast Lookups (Uses hashing)
# Creating a Dictionary

my_dict = {"name": "Adarsh", "age": 20, "city": "Patna"}

# Accessing Values

print(my_dict["name"]) # Output: Adarsh

# Modifying Dictionary

my_dict["age"] = 21 # Updates age

# Adding New Key-Value Pair

my_dict["college"] = "BCA College"

print(my_dict)

collegebuddy.co.in
Practical Example to Show Differences

# List Example (Ordered & Mutable)

my_list = [1, 2, 3]

my_list.append(4) # Modifiable

print("List:", my_list)

# Tuple Example (Ordered & Immutable)

my_tuple = (1, 2, 3)

# my_tuple.append(4) ❌ ERROR (Cannot Modify)


print("Tuple:", my_tuple)

# Set Example (Unordered & Unique)

my_set = {1, 2, 3, 3}

my_set.add(4) # Unique elements only

print("Set:", my_set)

# Dictionary Example (Key-Value)

my_dict = {"name": "John", "age": 25}

my_dict["age"] = 26 # Changeable

print("Dictionary:", my_dict)

Output

List: [1, 2, 3, 4]

Tuple: (1, 2, 3)

Set: {1, 2, 3, 4}

Dictionary: {'name': 'John', 'age': 26}

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.

1️⃣ String Functions in Python

Function Description Example & Output

upper() Converts all characters to "hello".upper() → 'HELLO'


uppercase

lower() Converts all characters to "Hello".lower() → 'hello'


lowercase

capitaliz Capitalizes first letter of a "hello".capitalize() → 'Hello'


e() string

title() Capitalizes first letter of "hello world".title() → 'Hello


every word World'

strip() Removes leading and " hello ".strip() → 'hello'


trailing spaces

replace() Replaces substring with "hello world".replace("world",


another "Python") → 'hello Python'

find() Returns index of first "hello".find("l") → 2


occurrence of substring

count() Counts occurrences of a "banana".count("a") → 3


substring

collegebuddy.co.in
startswit Checks if string starts with "hello".startswith("he") → True
h() a substring

endswith( Checks if string ends with a "hello".endswith("lo") → True


) substring

split() Splits a string into list of "hello world".split() → ['hello',


words 'world']

join() Joins elements of a list into " ".join(['hello', 'world']) →


a string 'hello world'

len() Returns length of the string len("hello") → 5

Example: Demonstrating String Functions

text = " Python is Amazing! "

# Applying string functions

print(text.upper()) # Output: " PYTHON IS AMAZING! "

print(text.strip()) # Output: "Python is Amazing!"

print(text.replace("Python", "Coding")) # Output: " Coding is Amazing! "

print(len(text)) # Output: 21

print(text.count("i")) # Output: 2

collegebuddy.co.in
Python Program to Check if a String is a Palindrome

A palindrome is a string that reads the same forward and backward.​


Examples: "madam", "racecar", "level", "radar".

def is_palindrome(s):

# Convert to lowercase and remove spaces

s = s.lower().replace(" ", "")

# Compare string with its reverse

return s == s[::-1] # [::-1] reverses the string

# User input

text = input("Enter a string: ")

# Check and print result

if is_palindrome(text):

print(f"'{text}' is a Palindrome!")

else:

print(f"'{text}' is NOT a Palindrome.")

Example Outputs

Enter a string: Madam

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

1️⃣ Types of File Handling in Python

There are two main types of file handling based on file formats:

A. Text File Handling (.txt)

●​ Stores data in human-readable format (plain text).


●​ Uses UTF-8 or ASCII encoding.
●​ Can be opened and edited using any text editor.

B. Binary File Handling (.bin, .jpg, .mp3)

●​ Stores data in raw binary format (not human-readable).


●​ Used for images, audio, video, and executable files.

2️⃣ File Handling Operations

Python provides four main modes to work with files:

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.

'r+' Read & Write mode. The file must exist.

'wb' Write binary mode. Used for binary files (images, videos).

collegebuddy.co.in
'rb' Read binary mode. Used for binary files.

3️⃣ Opening & Closing Files in Python

Python provides the open() function to open a file.

Syntax

file = open("filename.txt", mode)

●​ "filename.txt" → The file name.


●​ mode → The mode in which the file is opened.

Example: Opening & Closing a File

file = open("example.txt", "r") # Open file in read mode

content = file.read() # Read file content

print(content) # Print content

file.close() # Close file after use

4️⃣ Reading a File

Python provides three ways to read a file:

Method Description

read(size) Reads the entire file (or first size bytes).

readline() Reads one line at a time.

readlines() Reads all lines as a list.

Example: Reading a File

collegebuddy.co.in
file = open("sample.txt", "r")

print(file.read()) # Reads the whole file

file.close()

5️⃣ Writing to a File

To write data into a file, use the 'w' or 'a' mode.

Example: Writing Data

file = open("output.txt", "w")

file.write("Hello, Python File Handling!")

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:

# Open the file in read mode

with open(filename, "r") as file:

text = file.read() # Read the file content

# Split the text into words

words = text.split()

# Count and return the number of words

return len(words)
collegebuddy.co.in
except FileNotFoundError:

return "Error: File not found!"

# Input: File name from the user

file_name = input("Enter file name: ")

# Call function and print word count

word_count = count_words(file_name)

print(f"Total words in '{file_name}':", word_count)

Example Input File (sample.txt):

Python is a powerful programming language.

It is widely used in web development, AI, and data science.

Example Output

Enter file name: sample.txt

Total words in 'sample.txt': 15

Q7. What is a lambda function? Explain its characteristics with an example.

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.

lambda arguments: expression

2️⃣ Characteristics of Lambda Functions

Characteristic Description

Anonymous Lambda functions have no name (unlike regular functions).

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

3️⃣ Example: Using Lambda Function

1. Basic Lambda Function

# Regular function

def square(x):

return x * x

# Lambda function equivalent

square_lambda = lambda x: x * x

# Output

print(square_lambda(5)) # Output: 25

collegebuddy.co.in
4️⃣ Examples of Lambda Functions in Use

2. Lambda with Multiple Arguments

# Lambda function with two parameters

add = lambda x, y: x + y

print(add(5, 3)) # Output: 8

3. Lambda with map() Function

The map() function applies a function to all elements in a list.

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

squared_numbers = list(map(lambda x: x ** 2, numbers))

print(squared_numbers) # Output: [1, 4, 9, 16, 25]

4. Lambda with filter() Function

The filter() function filters elements based on a condition.

nums = [1, 2, 3, 4, 5, 6]

even_nums = list(filter(lambda x: x % 2 == 0, nums))

print(even_nums) # Output: [2, 4, 6]

5. Lambda with sorted() Function

Sorting a list of tuples by the second element.

students = [("Alice", 85), ("Bob", 92), ("Charlie", 78)]

sorted_students = sorted(students, key=lambda x: x[1]) # Sort by marks

print(sorted_students) # Output: [('Charlie', 78), ('Alice', 85),


('Bob', 92)]

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.

2️⃣ Common Exceptions in Python

Exception Description

ZeroDivisionE Division by zero (10 / 0).


rror

TypeError Unsupported operation between different types ("hello" + 5).

ValueError Invalid value for a function (int("abc")).

IndexError Accessing an out-of-range index in a list (arr[10]).

KeyError Accessing a non-existing dictionary key (dict["missing"]).

FileNotFoundE Trying to open a non-existent file.


rror

3️⃣ Exception Handling Using try-except

Python handles exceptions using try-except blocks.

try:

# Code that may cause an exception

except ExceptionType:

# Code to handle the exception

collegebuddy.co.in
Example: Handling ZeroDivisionError

try:

result = 10 / 0

except ZeroDivisionError:

print("Error: Cannot divide by zero!")

Output:

Error: Cannot divide by zero!

4️⃣ Using try-except-finally

●​ finally runs always, even if an exception occurs.

try:

file = open("data.txt", "r")

content = file.read()

except FileNotFoundError:

print("File not found!")

finally:

print("This will always execute!")

5️⃣ Using try-except-else

●​ else executes only if no exception occurs.

try:

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

print("Valid number:", num)

except ValueError:

print("Invalid input! Enter a numeric value.")

else:

print("No errors occurred.")

collegebuddy.co.in
(b) Write a program to handle division by zero error.

try:

# User input

num1 = int(input("Enter numerator: "))

num2 = int(input("Enter denominator: "))

# Division operation

result = num1 / num2

# Print result

print("Result:", result)

except ZeroDivisionError:

print("Error: Cannot divide by zero!")

except ValueError:

print("Error: Invalid input! Please enter numeric values.")

finally:

print("Execution completed.")

collegebuddy.co.in
Example Outputs

●​ Case 1: Valid Input

Enter numerator: 10

Enter denominator: 2

Result: 5.0

Execution completed.

●​ Case 2: Division by Zero

Enter numerator: 10

Enter denominator: 0

Error: Cannot divide by zero!

Execution completed.

●​ Case 3: Invalid Input

Enter numerator: 10

Enter denominator: xyz

Error: Invalid input! Please enter numeric values.

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

expression: The string to be evaluated as a Python expression.

globals and locals: Optional dictionaries specifying the global and local scope for evaluation.

Advantages of Using eval()

●​ Dynamic Evaluation: Executes expressions entered at runtime.


●​ Flexibility: Allows direct evaluation of mathematical or Python expressions without parsing.
●​ Ease of Use: Simplifies the process of interpreting string-based expressions.
●​ Fast Prototyping: Useful for quick testing of expressions.

Program: Evaluate a Mathematical Expression

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.

Precautions When Using eval()

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

●​ Safe Scope: Restrict available functions/variables using globals and locals.

collegebuddy.co.in
Q10. Write a Python program to multiply two matrices.

# Function to multiply two matrices

def multiply_matrices(A, B):

# Number of rows in A and columns in B

rows_A, cols_A = len(A), len(A[0])

rows_B, cols_B = len(B), len(B[0])

# Check if multiplication is possible

if cols_A != rows_B:

print("Matrix multiplication not possible!")

return None

# Initialize result matrix with zeros

result = [[0] * cols_B for _ in range(rows_A)]

# Perform matrix multiplication

for i in range(rows_A):

for j in range(cols_B):

for k in range(cols_A):

result[i][j] += A[i][k] * B[k][j]

return result

# Example Matrices

A = [[1, 2],

[3, 4]]

B = [[5, 6],

[7, 8]]

collegebuddy.co.in
# Multiply Matrices

result = multiply_matrices(A, B)

# Print the result

if result:

print("Resultant Matrix:")

for row in result:

print(row)

collegebuddy.co.in
Q11. What is the re (Regular Expressions) module in Python? Explain with examples of
search(), match(), and findall().

1️⃣ What is the re Module in Python?

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

Common Use Cases:​


✔ Validating email addresses, phone numbers, and passwords.​
✔ Searching for specific words in a document.​
✔ Replacing specific text patterns.

2️⃣ Importing the re Module

To use regular expressions, import the re module:

import re

3️⃣ Commonly Used re Functions

Function Description

re.search() Finds first match of the pattern in the string.

re.match() Checks if the pattern matches from the beginning.

re.findall() Returns all occurrences of the pattern in a list.

re.sub() Replaces matched patterns with a new string.

re.split() Splits string based on a regex pattern.

collegebuddy.co.in
4️⃣ Example: Using search(), match(), and findall()

●​ re.search() → Finds First Match Anywhere


○​ Returns first match if found, else None.

import re

text = "Python is a powerful programming language."

# Search for 'Python' in text

match = re.search(r"Python", text)

if match:

print("Match found:", match.group())

else:

print("No match found.")

Output:

Match found: Python

●​ re.match() → Checks for a Match at the Start


○​ Matches only at the beginning of the string.

import re

text = "Python is amazing"

match = re.match(r"Python", text)

if match:

print("Match found:", match.group())

else:

print("No match found.")

Output:

Match found: Python

✔ 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

text = "The rain in Spain stays mainly in the plain."

# Find all occurrences of 'ain'

matches = re.findall(r"ain", text)

print("All matches:", matches)

Output:

All matches: ['ain', 'ain', 'ain']

✔ Returns a list of all matches found in the text.

6️⃣ Summary Table

Function Description Example

re.search() Finds the first match re.search(r"Python", "Python is great!")


in the string.

re.match() Matches only from the re.match(r"Python", "Python is great!")


start.

re.findall() Finds all occurrences re.findall(r"ain", "The rain in Spain")


and returns a list.

re.sub() Replace pattern with re.sub(r"Python", "Java", text)


another string.

re.split() Splits string at given re.split(r"[;,]", "Python; Java, C++")


pattern.

collegebuddy.co.in
Q12. What is a module and package in Python? Explain how to create and import a module.

1️⃣ What is a Module in Python?

A module in Python is a file that contains Python code (functions, classes, and variables) that can
be reused in other programs.

●​ Code Reusability → Write once, use anywhere.


●​ Organized Structure → Helps in maintaining large codebases.
●​ Built-in & User-defined Modules → Python has many built-in modules (math, random), and
users can create their own.

Example: Built-in Modules (math, random)

import math

print(math.sqrt(25)) # Output: 5.0

import random

print(random.randint(1, 10)) # Output: Random number between 1-10

2️⃣ Creating a User-Defined Module

A module is simply a Python file (.py) that contains functions and variables.

Step 1: Create a Module (File: my_module.py)

# my_module.py (User-defined module)

def greet(name):

return f"Hello, {name}!"

PI = 3.1416

Step 2: Import and Use the Module

# main.py (Importing the module)

import my_module

print(my_module.greet("Adarsh")) # Output: Hello, Adarsh!

print("Value of PI:", my_module.PI) # Output: Value of PI: 3.1416

collegebuddy.co.in
●​ import my_module → Loads the module into the program.
●​ Use module_name.function_name() to access functions.

3️⃣ What is a Package in Python?

A package is a collection of multiple modules organized into a directory with an __init__.py file.

✔ Used to organize related modules into a structured directory.​


✔ Makes large projects more manageable.

Example: Creating a Package

my_package/

│── __init__.py (Indicates it's a package)

│── module1.py

│── module2.py

Step 1: Create Modules in a Package

File: my_package/module1.py

def add(a, b):

return a + b

File: my_package/module2.py

def subtract(a, b):

return a - b

Step 2: Importing from a Package

from my_package import module1, module2

print(module1.add(5, 3)) # Output: 8

print(module2.subtract(10, 4)) # Output: 6

collegebuddy.co.in
4️⃣ Importing Modules in Different Ways

Import Method Example Usage

import module import math Imports the entire module.

from module import from math import Imports only specific functions.
function sqrt

import module as import numpy as np Imports with an alias name.


alias

from module import * from math import * Imports all functions (not recommended).

5️⃣ Summary

●​ Modules → Individual .py files containing Python code.


●​ Packages → Collection of modules in a directory.

🚀
●​ 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:

1.​ Supervised Learning


2.​ Unsupervised Learning
3.​ Reinforcement Learning

1️⃣ Supervised Learning (Learning with Labels)

●​ Definition: The model is trained using labeled data (input-output pairs).


●​ Working: The algorithm learns from past examples and makes predictions on new data.
●​ Example: If a dataset contains emails labeled as spam or not spam, the model learns from
this and classifies new emails.

Supervised Learning Example: Predicting House Prices

Features (X) Price (Y - Output Label)

Area = 1000 sq ft, Bedrooms = 2 $200,000

Area = 1500 sq ft, Bedrooms = 3 $300,000

Area = 2000 sq ft, Bedrooms = 4 $400,000

The model learns from this past data and can predict the price for new houses.

Common Algorithms in Supervised Learning

Algorithm Usage

Linear Regression Predicts continuous values (house prices, salary).

Logistic Regression Used for classification (spam detection, disease


prediction).

Decision Trees Predicts based on decision rules.

collegebuddy.co.in
Support Vector Machines Used for classification tasks.
(SVM)

Neural Networks Used in complex problems like image recognition.

Python Code for Supervised Learning (Linear Regression)

from sklearn.linear_model import LinearRegression

# Training Data (Area in sq ft vs Price)

X = [[1000], [1500], [2000]] # Input (Features)

y = [200000, 300000, 400000] # Output (Target)

# Create and Train Model

model = LinearRegression()

model.fit(X, y)

# Predict for new house area

prediction = model.predict([[1800]])

print("Predicted Price:", prediction[0])

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.

Unsupervised Learning Example: Customer Segmentation

Customer Spending Data

Customer A - Buys sports items

Customer B - Buys electronics

Customer C - Buys groceries

The model groups customers with similar behavior into clusters.

Common Algorithms in Unsupervised Learning

Algorithm Usage

K-Means Clustering Groups data into k clusters (customer segmentation).

Hierarchical Clustering Builds a tree-like structure to group data.

Principal Component Analysis (PCA) Reduces dimensions for better visualization.

Autoencoders (Neural Networks) Used for anomaly detection and feature extraction.

collegebuddy.co.in
Python Code for Unsupervised Learning (K-Means Clustering)

from sklearn.cluster import KMeans

import numpy as np

# Sample Data (Customers' spending habits)

X = np.array([[20, 1000], [25, 1200], [30, 5000], [35, 5200], [40, 7000]])

# Create Model with 2 Clusters

kmeans = KMeans(n_clusters=2)

kmeans.fit(X)

# Predict Cluster for a new customer

new_customer = np.array([[27, 1300]])

cluster = kmeans.predict(new_customer)

print("Customer belongs to Cluster:", cluster[0])

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.

Reinforcement Learning Example: Playing a Game

Action Reward/Penalty

Move Left +10 (Correct move)

Move Right -5 (Wrong move)

Jump +15 (Avoids obstacle)

The model learns from rewards and makes better decisions over time.

Common Algorithms in Reinforcement Learning

Algorithm Usage

Q-Learning Learns an optimal action strategy (robot navigation).

Deep Q-Networks (DQN) Uses neural networks for complex problems.

Policy Gradient Methods Used in real-time strategy games.

collegebuddy.co.in
Python Code for Reinforcement Learning (Q-Learning Example)

import numpy as np

# Define Rewards for Different Actions

rewards = np.array([10, -5, 15]) # [Move Left, Move Right, Jump]

# Select Best Action (Max Reward)

best_action = np.argmax(rewards)

actions = ["Move Left", "Move Right", "Jump"]

print("Best Action to Take:", actions[best_action])

✔ The model chooses the action with the highest reward.

4️⃣ Comparison of Machine Learning Types

Feature Supervised Learning Unsupervised Reinforcement Learning


Learning

Training Data Labeled Data ✅ Unlabeled Data ❌ Interactive Feedback 🎮


Goal Predict outcomes Find patterns Maximize rewards

🏡 ♟️
🛒
Example Predict house prices Customer AI playing chess
segmentation

Common Linear Regression, K-Means, Q-Learning, Deep


Algorithms SVM, Decision Trees Hierarchical Q-Networks
Clustering

collegebuddy.co.in
Q14. Write a Python program to implement the Minimax algorithm for game playing.

1️⃣ What is the Minimax Algorithm?

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.

●​ Min Player (Opponent): Tries to minimize the score.


●​ Max Player (AI): Tries to maximize the score.
●​ Recursion: Explores all possible moves to make the optimal decision.

2️⃣ Steps of Minimax Algorithm

1.​ Generate all possible game states.


2.​ Evaluate each state using a scoring function.
3.​ Recursively apply Minimax:
○​ AI (Maximizing Player) chooses the highest score.
○​ Opponent (Minimizing Player) chooses the lowest score.
4.​ Backtrack and find the best move.

3️⃣ Python Implementation of Minimax for Tic-Tac-Toe

import math

# Define the Tic-Tac-Toe Board

board = [

['X', 'O', 'X'],

['O', 'X', 'O'],

['_', '_', '_'] # Empty spaces

# Function to Check if Moves are Left

def is_moves_left(board):

for row in 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):

for row in range(3):

# Check rows

if board[row][0] == board[row][1] == board[row][2]:

if board[row][0] == 'X': return 10

elif board[row][0] == 'O': return -10

for col in range(3):

# Check columns

if board[0][col] == board[1][col] == board[2][col]:

if board[0][col] == 'X': return 10

elif board[0][col] == 'O': return -10

# Check diagonals

if board[0][0] == board[1][1] == board[2][2]:

if board[0][0] == 'X': return 10

elif board[0][0] == 'O': return -10

if board[0][2] == board[1][1] == board[2][0]:

if board[0][2] == 'X': return 10

elif board[0][2] == 'O': return -10

return 0 # No winner

# Minimax Algorithm

def minimax(board, depth, is_max):

score = evaluate(board)

# If AI wins

if score == 10:

return score - depth


collegebuddy.co.in
# If Opponent wins

if score == -10:

return score + depth

# If no more moves left (draw)

if not is_moves_left(board):

return 0

# If it's AI's turn (Maximizing)

if is_max:

best = -math.inf # Worst case for AI

for i in range(3):

for j in range(3):

if board[i][j] == '_': # Check if cell is empty

board[i][j] = 'X' # AI makes a move

best = max(best, minimax(board, depth + 1, False)) # Recursive


call

board[i][j] = '_' # Undo move

return best

# If it's Opponent's turn (Minimizing)

else:

best = math.inf # Worst case for Opponent

for i in range(3):

for j in range(3):

if board[i][j] == '_': # Check if cell is empty

board[i][j] = 'O' # Opponent makes a move

best = min(best, minimax(board, depth + 1, True)) # Recursive


call

board[i][j] = '_' # Undo move

return best

collegebuddy.co.in
# Function to Find the Best Move

def find_best_move(board):

best_val = -math.inf

best_move = (-1, -1)

for i in range(3):

for j in range(3):

if board[i][j] == '_': # Check if cell is empty

board[i][j] = 'X' # AI makes a move

move_val = minimax(board, 0, False) # Calculate move score

board[i][j] = '_' # Undo move

if move_val > best_val:

best_move = (i, j)

best_val = move_val

return best_move

# Get AI's Best Move

best_move = find_best_move(board)

print("Best Move for AI (X):", best_move)

4️⃣ Explanation of Code

●​ Board Representation: 'X' (AI), 'O' (Opponent), '_' (Empty).


●​ evaluate(): Returns +10 for AI win, -10 for Opponent win, 0 for draw.
●​ minimax(): Recursively evaluates best and worst moves.
●​ find_best_move(): Uses Minimax to find the best move for AI.

collegebuddy.co.in
5️⃣ Example Output

Initial Board:

X | O | X

O | X | O

_ | _ | _

Best Move for AI (X)

Best Move for AI (X): (2, 1)

✔ AI selects position (2,1) as the best move.

6️⃣ Summary

✔ Minimax Algorithm → Used in AI game-playing to find the best move.​


✔ Evaluates all possible moves and selects the optimal one.​

🚀
✔ 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.

1️⃣ What is SQL Database Connectivity in Python?

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.

Python uses MySQL Connector, sqlite3, or SQLAlchemy to connect to SQL databases.

2️⃣ Steps for Connecting Python with MySQL

Install MySQL Connector

pip install mysql-connector-python

1.​ Import the MySQL module in Python.


2.​ Establish a connection to the MySQL database.
3.​ Create a cursor object to execute SQL queries.
4.​ Fetch and display data from the database.
5.​ Close the connection after executing queries.

3️⃣ Python Program to Connect Python with MySQL and Retrieve Data

Table Structure

We assume a MySQL database college_db with a table students.

Student_ID Name Age Course

1 Adarsh 20 BCA

2 Harshit 21 MCA

3 Rohan 22 B.Tech

collegebuddy.co.in
import mysql.connector

# Establish Connection to MySQL

conn = mysql.connector.connect(

host="localhost",

user="root",

password="password",

database="college_db"

# Create a cursor object

cursor = conn.cursor()

# Execute SQL Query to Fetch Data

cursor.execute("SELECT * FROM students")

# Fetch all rows

rows = cursor.fetchall()

# Print the retrieved data

print("Student Data:")

for row in rows:

print(row)

# Close the cursor and connection

cursor.close()

conn.close()

collegebuddy.co.in
4️⃣ Explanation of Code

✔ mysql.connector.connect() → Establishes a connection with MySQL.​


✔ cursor.execute("SELECT * FROM students") → Runs an SQL query.​
✔ fetchall() → Fetches all results from the table.​
✔ Loop prints each row of student data.​
✔ conn.close() → Closes the database connection.

5️⃣ Output Example

Student Data:

(1, 'Adarsh', 20, 'BCA')

(2, 'Harshit', 21, 'MCA')

(3, 'Rohan', 22, 'B.Tech')

6️⃣ Summary

●​ Python can connect to MySQL using mysql-connector-python.


●​ SQL queries like SELECT, INSERT, UPDATE, DELETE can be executed.

🚀
●​ Ensures efficient data management using Python scripts.
●​ Always close the database connection to free up resources.

collegebuddy.co.in

You might also like