0% found this document useful (0 votes)
9 views

BCA-502 Python Micro 1

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

BCA-502 Python Micro 1

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

Comparison (Relational) Operators a = 5 # 101 in binary

Q1. Explain different types of operators in Python with examples. How do built-in functions b = 3 # 011 in binary
help in handling numeric data types? Used to compare values and return a Boolean (True or False). print(a & b) # Output: 1

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. Membership Operators

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

Used to perform mathematical operations.

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


a=5 print("banana" in fruits) # Output: True
b=8
print(a < b) # Output: True
Identity Operators
Logical Operators
Used to compare the memory locations of two objects.
Used to perform logical operations.

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

Assignment Operators x = 10
y=5
Used to assign values to variables. print(x > 5 and y < 10) # Output: True x = [1, 2, 3]
y = [1, 2, 3]
Bitwise Operators print(x is y) # Output: False (different memory locations)

Used to perform bitwise operations on numbers.

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

x = 10
x += 5 # Equivalent to x = x + 5
print(x) # Output: 15 ●​ Basic Math:
○​ abs(): Returns the absolute value of a number.
○​ round(): Rounds a floating-point number to a specified number of decimal places.
collegebuddy.co.in collegebuddy.co.in collegebuddy.co.in

○​ pow(): Raises a number to a specific power (pow(base, exp[, mod])). Q2. (a) What are conditional statements in Python? Explain if-else, nested if with examples.​ 3️⃣ elif Statement
(b) Write a Python program to check whether a number is prime or not.
Used when multiple conditions need to be checked.
(a) Conditional Statements in Python
●​ Miscellaneous: Syntax
○​ divmod(): Returns a tuple of quotient and remainder, e.g., divmod(10, 3) → (3, Conditional statements are used in Python to control the flow of execution based on certain if condition1:
1). conditions. The condition is evaluated as True or False, and the corresponding block of code is # Code if condition1 is True
○​ sum(): Adds up all elements in an iterable. executed. elif condition2:
○​ min(), max(): Find the smallest or largest number in an iterable. # Code if condition2 is True
Types of Conditional Statements in Python else:
# Code if all conditions are False
1.​ if Statement → Executes a block of code if the condition is True.
Standard Library Modules 2.​ if-else Statement → Executes one block if True, another block if False. Example
3.​ elif Statement → Used when multiple conditions need to be checked. marks = 75
●​ math: Provides a range of mathematical functions. if marks >= 90:
4.​ Nested if → An if statement inside another if statement.
○​ math.sqrt(x): Returns the square root of x. print("Grade: A")
○​ math.factorial(x): Returns the factorial of x. elif marks >= 75:
○​ math.gcd(a, b): Returns the greatest common divisor. print("Grade: B")
○​ math.pi, math.e: Constants for π and e. 1️⃣ if Statement elif marks >= 50:
○​ Trigonometric functions: math.sin(), math.cos(), math.tan(). print("Grade: C")
○​ Rounding functions: math.floor(), math.ceil(). Executes a block of code only when the condition is True. else:
print("Fail")
if condition:
# Code to execute if condition is True Output:
●​ random: For generating random numbers.
○​ random.randint(a, b): Returns a random integer between a and b. Example Grade: B
○​ random.choice(sequence): Returns a random element from a sequence. age = 18
○​ random.uniform(a, b): Returns a random floating-point number between a and b. if age >= 18:
print("You are eligible to vote!")
Output: 4️⃣ Nested if Statement
You are eligible to vote!
●​ decimal: For decimal floating-point arithmetic with high precision. An if statement inside another if statement.
○​ decimal.Decimal(): Creates a decimal object.
Syntax
○​ decimal.getcontext().prec = n: Sets the precision to n digits.
2️⃣ if-else Statement if condition1:
if condition2:
Executes one block if the condition is True, another block if False. # Code if both conditions are True
●​ fractions: For rational number calculations.
○​ fractions.Fraction(numerator, denominator): Creates a fraction. if condition:
○​ Provides accurate fractional operations like addition, subtraction, etc. # Code if condition is True
else: Example
# Code if condition is False num = 10
if num > 0:
●​ statistics: For statistical calculations. Example print("Positive number")
○​ statistics.mean(data): Returns the mean (average) of data. num = -5 if num % 2 == 0:
○​ statistics.median(data): Returns the median of data. if num >= 0: print("Even number")
○​ statistics.mode(data): Returns the mode of data. print("Positive Number")
else: Output:
print("Negative Number")
Positive number
Output: Even number

Negative Number

collegebuddy.co.in collegebuddy.co.in collegebuddy.co.in

(b) Python Program to Check Whether a Number is Prime or Not Q4. Differentiate between List, Tuple, Set, and Dictionary in Python with examples. 3️⃣ Set (Unordered & Unique Elements)

A prime number is a number greater than 1 that has only two factors: 1 and itself. Python provides four main built-in collection types: A Set is an unordered collection of unique elements. It does not allow duplicates and does not
support indexing or slicing.
import math ●​ List (list) → Ordered, Mutable
# Function to check if a number is prime ●​ Tuple (tuple) → Ordered, Immutable Characteristics:

❌ Unordered (Does not maintain element order)​


def is_prime(n): ●​ Set (set) → Unordered, Unique Elements

✅ Mutable (Can add/remove elements)​


if n < 2: ●​ Dictionary (dict) → Key-Value Mapping

❌ Does NOT allow Duplicates (Ensures unique values)​


return False

❌ No Indexing & Slicing


for i in range(2, int(math.sqrt(n)) + 1): # Check till sqrt(n)
if n % i == 0:
return False
1️⃣ List (Ordered & Mutable)
return True
A List is an ordered collection that is mutable, meaning its elements can be modified after my_set = {10, 20, 30, 40, 50}
# Input from the user creation. It allows duplicate values and supports indexing & slicing.
num = int(input("Enter a number: ")) my_set.add(60)
my_set.add(20)
Characteristics:
# Checking if prime
if is_prime(num): ✅ Ordered (Elements maintain their order)​ my_set.remove(30)
print(num, "is a Prime Number") ✅ Mutable (Elements can be changed)​ print(my_set)
else: ✅ Allows Duplicates (Same values can repeat)​
print(num, "is NOT a Prime Number") ✅ Indexed & Slicing Supported (Access elements using position) 4️⃣ Dictionary (Key-Value Pair, Mutable & Ordered)
Q3. Explain looping structures in Python (for, while, do-while).​ # Creating a List
Write a Python program to print the following pyramid pattern: my_list = [10, 20, 30, 40, 50] A Dictionary is a collection of key-value pairs, where each key is unique and maps to a specific
value.
# Accessing Elements
print(my_list[1]) # Output: 20 Characteristics:

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


# Modifying List
✅ Mutable (Can modify values)​
my_list.append(60) # Adds 60 at the end
❌ Keys Must Be Unique​
my_list[0] = 100 # Modifies the first element
print(my_list) # Output: [100, 20, 30, 40, 50, 60] ✅ Fast Lookups (Uses hashing)
# Creating a Dictionary
# Removing Elements
my_dict = {"name": "Adarsh", "age": 20, "city": "Patna"}
my_list.remove(30) # Removes first occurrence of 30
def print_pattern(): print(my_dict["name"]) # Output: Adarsh
for i in range(1, 4): 2️⃣ Tuple (Ordered & Immutable)
print(" " * (3 - i), end="") my_dict["age"] = 21 # Updates age
for j in range(1, i * 2): A Tuple is an ordered collection but immutable, meaning elements cannot be modified after
if j <= i: creation. It allows duplicate values and supports indexing & slicing. my_dict["college"] = "BCA College"
print(j, end="") print(my_dict)
else: Characteristics:
print(i * 2 - j, end="")
✅ Ordered (Elements maintain their order)​ Practical Example to Show Differences
print()
❌ Immutable (Cannot be changed once created)​
for i in range(2, 0, -1):
✅ Allows Duplicates​ # List Example (Ordered & Mutable)
print(" " * (3 - i), end="")
for j in range(1, i * 2): ✅ Supports Indexing & Slicing my_list = [1, 2, 3]
my_list.append(4) # Modifiable
if j <= i: print("List:", my_list)
print(j, end="") # Creating a Tuple
else: my_tuple = (10, 20, 30, 40, 50) # Tuple Example (Ordered & Immutable)


print(i * 2 - j, end="") my_tuple = (1, 2, 3)
print() # Accessing Elements # my_tuple.append(4) ERROR (Cannot Modify)
print_pattern() print(my_tuple[1]) # Output: 20 print("Tuple:", my_tuple)

collegebuddy.co.in collegebuddy.co.in collegebuddy.co.in


if is_palindrome(text):
# Set Example (Unordered & Unique) find() Returns index of first "hello".find("l") → 2 print(f"'{text}' is a Palindrome!")
my_set = {1, 2, 3, 3} occurrence of substring else:
my_set.add(4) # Unique elements only print(f"'{text}' is NOT a Palindrome.")
print("Set:", my_set)
count() Counts occurrences of a "banana".count("a") → 3 Example Outputs
# Dictionary Example (Key-Value) substring
my_dict = {"name": "John", "age": 25} Enter a string: Madam
my_dict["age"] = 26 # Changeable 'Madam' is a Palindrome!
startswith( Checks if string starts with a "hello".startswith("he") → True
print("Dictionary:", my_dict)
) substring
Output
List: [1, 2, 3, 4] Q6. Explain the types of file handling in Python. Write a Python program to read a text file
endswith() Checks if string ends with a "hello".endswith("lo") → True
Tuple: (1, 2, 3) and count the number of words.
substring
Set: {1, 2, 3, 4}
File handling refers to the process of performing operations on a file such as creating, opening,
Dictionary: {'name': 'John', 'age': 26}
reading, writing and closing it, through a programming interface. It involves managing the data
split() Splits a string into list of "hello world".split() → ['hello',
words flow between the program and the file system on the storage device, ensuring that data is
'world']
handled safely and efficiently.
Q5. Explain different string functions in Python. Write a program to check if a given string is
a palindrome. Python provides built-in functions to work with text files (.txt) and binary files (.bin, .jpg, .png,
join() Joins elements of a list into a " ".join(['hello', 'world']) →
etc.).
string 'hello world'
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️⃣ Types of File Handling in Python
len() Returns length of the string len("hello") → 5
1️⃣ String Functions in Python There are two main types of file handling based on file formats:

A. Text File Handling (.txt)


Function Description Example & Output
Example: Demonstrating String Functions ●​ Stores data in human-readable format (plain text).
●​ Uses UTF-8 or ASCII encoding.
upper() Converts all characters to "hello".upper() → 'HELLO' text = " Python is Amazing! " ●​ Can be opened and edited using any text editor.
uppercase # Applying string functions
print(text.upper()) # Output: " PYTHON IS AMAZING! " B. Binary File Handling (.bin, .jpg, .mp3)
print(text.strip()) # Output: "Python is Amazing!"
lower() Converts all characters to "Hello".lower() → 'hello' print(text.replace("Python", "Coding")) # Output: " Coding is Amazing! " ●​ Stores data in raw binary format (not human-readable).
lowercase print(len(text)) # Output: 21 ●​ Used for images, audio, video, and executable files.
print(text.count("i")) # Output: 2

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


string Python Program to Check if a String is a Palindrome
) 2️⃣ File Handling Operations
A palindrome is a string that reads the same forward and backward.​
Python provides four main modes to work with files:
title() Capitalizes first letter of "hello world".title() → 'Hello Examples: "madam", "racecar", "level", "radar".
every word World'
def is_palindrome(s): Mode Description
# Convert to lowercase and remove spaces
strip() Removes leading and trailing " hello ".strip() → 'hello' s = s.lower().replace(" ", "")
spaces # Compare string with its reverse 'r' Read mode (default). Opens a file for reading. Raises an error if the file doesn’t exist.
return s == s[::-1] # [::-1] reverses the string

replace() Replaces substring with "hello world".replace("world", # User input 'w' Write mode. Creates a file if it doesn’t exist. Overwrites existing content.
another "Python") → 'hello Python' text = input("Enter a string: ")

# Check and print result

collegebuddy.co.in collegebuddy.co.in collegebuddy.co.in

Example: Reading a File Example Output


'a' Append mode. Creates a file if it doesn’t exist. Adds data at the end of the file. file = open("sample.txt", "r")
print(file.read()) # Reads the whole file Enter file name: sample.txt
file.close() Total words in 'sample.txt': 15
'r+' Read & Write mode. The file must exist.

'wb' Write binary mode. Used for binary files (images, videos). Q7. What is a lambda function? Explain its characteristics with an example.
5️⃣ Writing to a File
A lambda function in Python is a small, anonymous function that can have any number of
'rb' Read binary mode. Used for binary files. To write data into a file, use the 'w' or 'a' mode.
arguments but only one expression. It is defined using the lambda keyword and is commonly used
for short, simple operations.
Example: Writing Data
file = open("output.txt", "w") lambda arguments: expression
file.write("Hello, Python File Handling!")
3️⃣ Opening & Closing Files in Python file.close() 2️⃣ Characteristics of Lambda Functions
Python provides the open() function to open a file.

Syntax 6️⃣ Python Program to Read a Text File and Count the Number of Words Characteristic Description
file = open("filename.txt", mode)
The program reads a text file and counts the number of words.
Anonymous Lambda functions have no name (unlike regular functions).
●​ "filename.txt" → The file name. def count_words(filename):
●​ mode → The mode in which the file is opened. try:
# Open the file in read mode Single Expression They contain only one expression (cannot have multiple statements).
Example: Opening & Closing a File with open(filename, "r") as file:
text = file.read() # Read the file content
file = open("example.txt", "r") # Open file in read mode Multiple Arguments Can take multiple arguments but return only one value.
# Split the text into words
content = file.read() # Read file content
words = text.split()
print(content) # Print content
file.close() # Close file after use
# Count and return the number of words Return Value Automatically No need to use the return keyword; the result is returned
return len(words) automatically.

except FileNotFoundError:
4️⃣ Reading a File return "Error: File not found!"
Used in Higher-Order Often used with functions like map(), filter(), and sorted().
Python provides three ways to read a file:
# Input: File name from the user Functions
file_name = input("Enter file name: ")

Method Description # Call function and print word count


Short & Readable Best for short, simple operations (not recommended for complex logic).
word_count = count_words(file_name)
print(f"Total words in '{file_name}':", word_count)
read(size) Reads the entire file (or first size bytes).
3️⃣ Example: Using Lambda Function

Example Input File (sample.txt): 1. Basic Lambda Function


readline() Reads one line at a time.
Python is a powerful programming language. # Regular function
It is widely used in web development, AI, and data science.
def square(x):
readlines() Reads all lines as a list.
return x * x
collegebuddy.co.in collegebuddy.co.in collegebuddy.co.in

# Lambda function equivalent An exception in Python is an error that occurs during program execution. Exception handling try:
allows the program to catch and handle errors instead of crashing.
square_lambda = lambda x: x * x result = 10 / 0
2️⃣ Common Exceptions in Python
# Output except ZeroDivisionError:

print(square_lambda(5)) # Output: 25 print("Error: Cannot divide by zero!")


Exception Description
4️⃣ Examples of Lambda Functions in Use
Output:
2. Lambda with Multiple Arguments ZeroDivisionE Division by zero (10 / 0).
rror Error: Cannot divide by zero!
# Lambda function with two parameters

add = lambda x, y: x + y
TypeError Unsupported operation between different types ("hello" + 5). 4️⃣ Using try-except-finally
print(add(5, 3)) # Output: 8
●​ finally runs always, even if an exception occurs.
ValueError Invalid value for a function (int("abc")).
try:
3. Lambda with map() Function
file = open("data.txt", "r")
The map() function applies a function to all elements in a list.
IndexError Accessing an out-of-range index in a list (arr[10]).
content = file.read()
numbers = [1, 2, 3, 4, 5]
except FileNotFoundError:
squared_numbers = list(map(lambda x: x ** 2, numbers))
KeyError Accessing a non-existing dictionary key (dict["missing"]).
print("File not found!")
print(squared_numbers) # Output: [1, 4, 9, 16, 25]
finally:
FileNotFoundE Trying to open a non-existent file.
rror print("This will always execute!")
4. Lambda with filter() Function

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


5️⃣ Using try-except-else
nums = [1, 2, 3, 4, 5, 6]
3️⃣ Exception Handling Using try-except
●​ else executes only if no exception occurs.
even_nums = list(filter(lambda x: x % 2 == 0, nums))
Python handles exceptions using try-except blocks.
try:
print(even_nums) # Output: [2, 4, 6]
try:
num = int(input("Enter a number: "))
5. Lambda with sorted() Function
# Code that may cause an exception
print("Valid number:", num)
Sorting a list of tuples by the second element.
except ExceptionType:
except ValueError:
students = [("Alice", 85), ("Bob", 92), ("Charlie", 78)]
# Code to handle the exception
print("Invalid input! Enter a numeric value.")
sorted_students = sorted(students, key=lambda x: x[1]) # Sort by marks
else:
print(sorted_students) # Output: [('Charlie', 78), ('Alice', 85), ('Bob', 92)]
print("No errors occurred.")

Example: Handling ZeroDivisionError (b) Write a program to handle division by zero error.
Q8. (a) Explain exception handling in Python with examples.
collegebuddy.co.in collegebuddy.co.in collegebuddy.co.in
try: Enter numerator: 10 ●​ Flexibility: Allows direct evaluation of mathematical or Python expressions without parsing.
●​ Ease of Use: Simplifies the process of interpreting string-based expressions.
# User input Enter denominator: 2 ●​ Fast Prototyping: Useful for quick testing of expressions.

num1 = int(input("Enter numerator: ")) Result: 5.0 Program: Evaluate a Mathematical Expression

num2 = int(input("Enter denominator: ")) Execution completed. This program demonstrates the use of eval() to evaluate a mathematical expression entered by
the user.

# Division operation ●​ Case 2: Division by Zero

result = num1 / num2


Enter numerator: 10

Enter denominator: 0
# Print result
Error: Cannot divide by zero!
print("Result:", result)
Execution completed. How It Works

●​ User Input: The user enters a mathematical expression as a string (e.g., 2 + 3 * 4).
except ZeroDivisionError: ●​ Evaluate with eval():
●​ Case 3: Invalid Input ○​ The string is passed to eval(), which interprets and computes the result.
print("Error: Cannot divide by zero!")
Precautions When Using eval()
Enter numerator: 10
●​ Security Risk: Avoid using eval() with untrusted input as it can execute arbitrary code.
except ValueError: Enter denominator: xyz
Example: If someone enters __import__('os').system('rm -rf /'), it could harm the system.
print("Error: Invalid input! Please enter numeric values.") Error: Invalid input! Please enter numeric values.
●​ Safe Scope: Restrict available functions/variables using globals and locals.
Execution completed.

finally:
Q10. Write a Python program to multiply two matrices.
print("Execution completed.") 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. # Function to multiply two matrices

The eval() function evaluates a string as a Python expression and returns the result. It is used for def multiply_matrices(A, B):
dynamically executing expressions that are input or generated at runtime.
# Number of rows in A and columns in B
Syntax of eval()
rows_A, cols_A = len(A), len(A[0])

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

# Check if multiplication is possible


expression: The string to be evaluated as a Python expression.
if cols_A != rows_B:
globals and locals: Optional dictionaries specifying the global and local scope for evaluation.
print("Matrix multiplication not possible!")
Example Outputs Advantages of Using eval()
return None
●​ Case 1: Valid Input ●​ Dynamic Evaluation: Executes expressions entered at runtime.

collegebuddy.co.in collegebuddy.co.in collegebuddy.co.in

# Initialize result matrix with zeros 1️⃣ What is the re Module in Python? import re

result = [[0] * cols_B for _ in range(rows_A)] The re (Regular Expressions) module in Python is used for pattern matching, searching, and text = "Python is a powerful programming language."
manipulating text. It allows us to find, replace, and extract specific patterns in strings using regex
(regular expressions). # Search for 'Python' in text

# Perform matrix multiplication Common Use Cases:​ match = re.search(r"Python", text)


✔ Validating email addresses, phone numbers, and passwords.​
for i in range(rows_A): ✔ Searching for specific words in a document.​ if match:
✔ Replacing specific text patterns.
for j in range(cols_B): print("Match found:", match.group())

for k in range(cols_A): else:

result[i][j] += A[i][k] * B[k][j] 2️⃣ Importing the re Module print("No match found.")

To use regular expressions, import the re module:

return result import re Output:

Match found: Python

# Example Matrices
3️⃣ Commonly Used re Functions
A = [[1, 2], ●​ re.match() → Checks for a Match at the Start
○​ Matches only at the beginning of the string.
[3, 4]] Function Description
import re

text = "Python is amazing"


B = [[5, 6], re.search() Finds first match of the pattern in the string.
match = re.match(r"Python", text)
[7, 8]]
if match:
re.match() Checks if the pattern matches from the beginning.
print("Match found:", match.group())

else:
# Multiply Matrices re.findall() Returns all occurrences of the pattern in a list.
print("No match found.")
result = multiply_matrices(A, B)
Output:
re.sub() Replaces matched patterns with a new string.
Match found: Python
# Print the result

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

print("Resultant Matrix:")

for row in result:

print(row)
✔ If the string does not start with "Python", it will return None.
Q11. What is the re (Regular Expressions) module in Python? Explain with examples of 4️⃣ Example: Using search(), match(), and findall()
search(), match(), and findall().
●​ re.findall() → Returns All Matches in a List
●​ re.search() → Finds First Match Anywhere ○​ Finds all occurrences of a pattern.
○​ Returns first match if found, else None.
collegebuddy.co.in collegebuddy.co.in collegebuddy.co.in

import re A module in Python is a file that contains Python code (functions, classes, and variables) that can ✔ Used to organize related modules into a structured directory.​
be reused in other programs. ✔ Makes large projects more manageable.
text = "The rain in Spain stays mainly in the plain."
●​ Code Reusability → Write once, use anywhere. Example: Creating a Package
# Find all occurrences of 'ain' ●​ Organized Structure → Helps in maintaining large codebases.
●​ Built-in & User-defined Modules → Python has many built-in modules (math, random), and my_package/
matches = re.findall(r"ain", text) users can create their own.
│── __init__.py (Indicates it's a package)
print("All matches:", matches)
Example: Built-in Modules (math, random)
│── module1.py
import math
│── module2.py
Output:
print(math.sqrt(25)) # Output: 5.0
All matches: ['ain', 'ain', 'ain']
import random
Step 1: Create Modules in a Package
✔ Returns a list of all matches found in the text.
print(random.randint(1, 10)) # Output: Random number between 1-10
File: my_package/module1.py

def add(a, b):


6️⃣ Summary Table
2️⃣ Creating a User-Defined Module return a + b
Function Description Example A module is simply a Python file (.py) that contains functions and variables.

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


re.search() Finds the first match in re.search(r"Python", "Python is great!")
the string. # my_module.py (User-defined module) def subtract(a, b):

def greet(name): return a - b


re.match() Matches only from the re.match(r"Python", "Python is great!")
start. return f"Hello, {name}!"

re.findall() Finds all occurrences re.findall(r"ain", "The rain in Spain") Step 2: Importing from a Package
and returns a list. PI = 3.1416 from my_package import module1, module2

Step 2: Import and Use the Module


re.sub() Replace pattern with re.sub(r"Python", "Java", text)
another string. # main.py (Importing the module) print(module1.add(5, 3)) # Output: 8

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


re.split() Splits string at given re.split(r"[;,]", "Python; Java, C++")
pattern. print(my_module.greet("Adarsh")) # Output: Hello, Adarsh!

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

●​ import my_module → Loads the module into the program.


●​ Use module_name.function_name() to access functions.

3️⃣ What is a Package in Python? 4️⃣ Importing Modules in Different Ways


Q12. What is a module and package in Python? Explain how to create and import a module.
A package is a collection of multiple modules organized into a directory with an __init__.py file.
1️⃣ What is a Module in Python?

collegebuddy.co.in collegebuddy.co.in collegebuddy.co.in


●​ Definition: The model is trained on unlabeled data and finds hidden patterns.
Import Method Example Usage Area = 2000 sq ft, Bedrooms = 4 $400,000 ●​ Working: It groups or clusters similar data points without predefined labels.
●​ Example: Grouping customers based on shopping behavior without knowing predefined
customer categories.
import module import math Imports the entire module. The model learns from this past data and can predict the price for new houses.
Unsupervised Learning Example: Customer Segmentation
Common Algorithms in Supervised Learning
from module import from math import Imports only specific functions.
Customer Spending Data
function sqrt Algorithm Usage

Customer A - Buys sports items


import module as alias import numpy as np Imports with an alias name. Linear Regression Predicts continuous values (house prices, salary).

Customer B - Buys electronics


from module import * from math import * Imports all functions (not recommended). Logistic Regression Used for classification (spam detection, disease
prediction).
Customer C - Buys groceries

Decision Trees Predicts based on decision rules.


5️⃣ Summary The model groups customers with similar behavior into clusters.

●​ Modules → Individual .py files containing Python code. Support Vector Machines (SVM) Used for classification tasks. Common Algorithms in Unsupervised Learning
●​ Packages → Collection of modules in a directory.

🚀
●​ Importing Modules → Use import module_name or from module import function. Algorithm Usage
Neural Networks Used in complex problems like image recognition.
●​ Helps in structuring large projects and reusing code efficiently.

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


Python Code for Supervised Learning (Linear Regression)
Q13. Explain the different types of machine learning (Supervised, Unsupervised,
from sklearn.linear_model import LinearRegression
Reinforcement Learning) with examples. Hierarchical Clustering Builds a tree-like structure to group data.

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: Principal Component Analysis (PCA) Reduces dimensions for better visualization.
# Training Data (Area in sq ft vs Price)
1.​ Supervised Learning
X = [[1000], [1500], [2000]] # Input (Features)
2.​ Unsupervised Learning Autoencoders (Neural Networks) Used for anomaly detection and feature extraction.
3.​ Reinforcement Learning y = [200000, 300000, 400000] # Output (Target)

1️⃣ Supervised Learning (Learning with Labels) Python Code for Unsupervised Learning (K-Means Clustering)

●​ Definition: The model is trained using labeled data (input-output pairs). # Create and Train Model
●​ Working: The algorithm learns from past examples and makes predictions on new data. from sklearn.cluster import KMeans
●​ Example: If a dataset contains emails labeled as spam or not spam, the model learns from model = LinearRegression()
this and classifies new emails. import numpy as np
model.fit(X, y)
# Sample Data (Customers' spending habits)
Supervised Learning Example: Predicting House Prices
X = np.array([[20, 1000], [25, 1200], [30, 5000], [35, 5200], [40, 7000]])
Features (X) Price (Y - Output Label) # Predict for new house area
# Create Model with 2 Clusters
prediction = model.predict([[1800]])
Area = 1000 sq ft, Bedrooms = 2 $200,000 kmeans = KMeans(n_clusters=2)
print("Predicted Price:", prediction[0])
kmeans.fit(X)
Area = 1500 sq ft, Bedrooms = 3 $300,000 2️⃣ Unsupervised Learning (Learning Without Labels)

collegebuddy.co.in collegebuddy.co.in collegebuddy.co.in

# Predict Cluster for a new customer Q14. Write a Python program to implement the Minimax algorithm for game playing.

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


1️⃣ What is the Minimax Algorithm?
cluster = kmeans.predict(new_customer) # Define Rewards for Different Actions
The Minimax algorithm is used in game-playing AI to choose the best move by evaluating all
rewards = np.array([10, -5, 15]) # [Move Left, Move Right, Jump] possible future moves. It is widely used in two-player games like Tic-Tac-Toe, Chess, and Connect
print("Customer belongs to Cluster:", cluster[0])
Four.
# Select Best Action (Max Reward)
3️⃣ Reinforcement Learning (Learning Through Rewards) ●​ Min Player (Opponent): Tries to minimize the score.
best_action = np.argmax(rewards) ●​ Max Player (AI): Tries to maximize the score.
●​ Definition: The model learns by interacting with the environment and receiving rewards or ●​ Recursion: Explores all possible moves to make the optimal decision.
penalties. actions = ["Move Left", "Move Right", "Jump"]
●​ Working: An agent performs actions in an environment and gets feedback in the form of
rewards or penalties. print("Best Action to Take:", actions[best_action])
●​ Example: A robot learning to walk by adjusting its movements based on success or failure.
2️⃣ Steps of Minimax Algorithm
Reinforcement Learning Example: Playing a Game 1.​ Generate all possible game states.
✔ The model chooses the action with the highest reward. 2.​ Evaluate each state using a scoring function.
Action Reward/Penalty 3.​ Recursively apply Minimax:
○​ AI (Maximizing Player) chooses the highest score.
○​ Opponent (Minimizing Player) chooses the lowest score.
4️⃣ Comparison of Machine Learning Types 4.​ Backtrack and find the best move.
Move Left +10 (Correct move)
Feature Supervised Learning Unsupervised Reinforcement Learning
Learning
Move Right -5 (Wrong move) 3️⃣ Python Implementation of Minimax for Tic-Tac-Toe

Jump +15 (Avoids obstacle)


Training Data Labeled Data ✅ Unlabeled Data ❌ Interactive Feedback 🎮 import math

Goal Predict outcomes Find patterns Maximize rewards


The model learns from rewards and makes better decisions over time. # Define the Tic-Tac-Toe Board

board = [
Common Algorithms in Reinforcement Learning
🏡 ♟️
🛒
Example Predict house prices Customer AI playing chess
segmentation ['X', 'O', 'X'],
Algorithm Usage
['O', 'X', 'O'],

Common Linear Regression, K-Means, Q-Learning, Deep ['_', '_', '_'] # Empty spaces
Q-Learning Learns an optimal action strategy (robot navigation). Algorithms SVM, Decision Trees Hierarchical Q-Networks
Clustering ]

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


# Function to Check if Moves are Left

def is_moves_left(board):
Policy Gradient Methods Used in real-time strategy games.
for row in board:

if '_' in row:

Python Code for Reinforcement Learning (Q-Learning Example) return True

collegebuddy.co.in collegebuddy.co.in collegebuddy.co.in

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

# Evaluate Board: +10 for AI win, -10 for Opponent win, 0 for draw # If AI wins board[i][j] = 'O' # Opponent makes a move

def evaluate(board): if score == 10: best = min(best, minimax(board, depth + 1, True)) # Recursive call

for row in range(3): return score - depth board[i][j] = '_' # Undo move

# Check rows return best

if board[row][0] == board[row][1] == board[row][2]: # If Opponent wins

if board[row][0] == 'X': return 10 if score == -10: # Function to Find the Best Move

elif board[row][0] == 'O': return -10 return score + depth def find_best_move(board):

best_val = -math.inf

for col in range(3): # If no more moves left (draw) best_move = (-1, -1)

# Check columns if not is_moves_left(board):

if board[0][col] == board[1][col] == board[2][col]: return 0 for i in range(3):

if board[0][col] == 'X': return 10 for j in range(3):

elif board[0][col] == 'O': return -10 # If it's AI's turn (Maximizing) if board[i][j] == '_': # Check if cell is empty

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

# Check diagonals best = -math.inf # Worst case for AI move_val = minimax(board, 0, False) # Calculate move score

if board[0][0] == board[1][1] == board[2][2]: for i in range(3): board[i][j] = '_' # Undo move

if board[0][0] == 'X': return 10 for j in range(3):

elif board[0][0] == 'O': return -10 if board[i][j] == '_': # Check if cell is empty if move_val > best_val:

board[i][j] = 'X' # AI makes a move best_move = (i, j)

if board[0][2] == board[1][1] == board[2][0]: best = max(best, minimax(board, depth + 1, False)) # Recursive call best_val = move_val

if board[0][2] == 'X': return 10 board[i][j] = '_' # Undo move

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

return 0 # No winner # If it's Opponent's turn (Minimizing) # Get AI's Best Move

else: best_move = find_best_move(board)

# Minimax Algorithm best = math.inf # Worst case for Opponent print("Best Move for AI (X):", best_move)

def minimax(board, depth, is_max): for i in range(3):

score = evaluate(board) for j in range(3):

collegebuddy.co.in collegebuddy.co.in collegebuddy.co.in


4️⃣ Explanation of Code Q15. Explain SQL database connectivity in Python. Write a program to connect Python with import mysql.connector
MySQL and retrieve data from a table.
●​ Board Representation: 'X' (AI), 'O' (Opponent), '_' (Empty). # Establish Connection to MySQL
●​ evaluate(): Returns +10 for AI win, -10 for Opponent win, 0 for draw. 1️⃣ What is SQL Database Connectivity in Python?
●​ minimax(): Recursively evaluates best and worst moves. conn = mysql.connector.connect(
●​ find_best_move(): Uses Minimax to find the best move for AI. SQL database connectivity in Python allows programs to interact with databases like MySQL,
host="localhost",
PostgreSQL, SQLite, or Oracle. It enables Python to:​
✔ Store, update, and delete data in a database.​ user="root",
✔ Execute SQL queries directly from Python.​
5️⃣ Example Output ✔ Automate database operations. password="password",

Initial Board: Python uses MySQL Connector, sqlite3, or SQLAlchemy to connect to SQL databases. database="college_db"

X|O|X )

O|X|O 2️⃣ Steps for Connecting Python with MySQL

_|_|_ Install MySQL Connector # Create a cursor object

pip install mysql-connector-python cursor = conn.cursor()

Best Move for AI (X) 1.​ Import the MySQL module in Python.
2.​ Establish a connection to the MySQL database.
Best Move for AI (X): (2, 1) # Execute SQL Query to Fetch Data
3.​ Create a cursor object to execute SQL queries.
4.​ Fetch and display data from the database.
cursor.execute("SELECT * FROM students")
5.​ Close the connection after executing queries.
✔ AI selects position (2,1) as the best move.

# Fetch all rows


3️⃣ Python Program to Connect Python with MySQL and Retrieve Data
rows = cursor.fetchall()
6️⃣ Summary
Table Structure
✔ Minimax Algorithm → Used in AI game-playing to find the best move.​
We assume a MySQL database college_db with a table students.
✔ Evaluates all possible moves and selects the optimal one.​ # Print the retrieved data

🚀
✔ Used in Tic-Tac-Toe, Chess, Checkers, and Strategy Games.​
✔ Backtracking ensures AI always makes the best move. Student_ID Name Age Course print("Student Data:")

for row in rows:


1 Adarsh 20 BCA
print(row)

2 Harshit 21 MCA

# Close the cursor and connection


3 Rohan 22 B.Tech
cursor.close()

conn.close()

collegebuddy.co.in collegebuddy.co.in 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