BCA-502 Python Micro 1
BCA-502 Python Micro 1
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.).
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)
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
(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:
❌
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)
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: ")
'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: ")
# 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:
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
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.
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])
# 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
result[i][j] += A[i][k] * B[k][j] 2️⃣ Importing the re Module print("No match found.")
# 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
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
print("Resultant Matrix:")
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
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
● 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.
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)
# Predict Cluster for a new customer Q14. Write a Python program to implement the Minimax algorithm for game playing.
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 ]
def is_moves_left(board):
Policy Gradient Methods Used in real-time strategy games.
for row in board:
if '_' in row:
# 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
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)
elif board[0][col] == 'O': return -10 # If it's AI's turn (Maximizing) if board[i][j] == '_': # Check if cell is empty
# Check diagonals best = -math.inf # Worst case for AI move_val = minimax(board, 0, False) # Calculate move score
elif board[0][0] == 'O': return -10 if board[i][j] == '_': # Check if cell is empty if move_val > best_val:
if board[0][2] == board[1][1] == board[2][0]: best = max(best, minimax(board, depth + 1, False)) # Recursive call best_val = move_val
return 0 # No winner # If it's Opponent's turn (Minimizing) # Get AI's Best Move
# Minimax Algorithm best = math.inf # Worst case for Opponent print("Best Move for AI (X):", best_move)
Initial Board: Python uses MySQL Connector, sqlite3, or SQLAlchemy to connect to SQL databases. database="college_db"
X|O|X )
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.
🚀
✔ 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:")
2 Harshit 21 MCA
conn.close()
Student Data:
6️⃣ Summary
🚀
● Ensures efficient data management using Python scripts.
● Always close the database connection to free up resources.
collegebuddy.co.in