0% found this document useful (0 votes)
2 views16 pages

Python Imp 001

The document covers various Python programming concepts including dictionaries, inheritance, string manipulation, MongoDB CRUD operations, file operations, lists, and pandas DataFrames. It also discusses SQL vs NoSQL databases, user-defined exceptions, regular expressions, multithreading, and several short coding problems. Additionally, it provides insights into Python features, scopes, and tuples.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views16 pages

Python Imp 001

The document covers various Python programming concepts including dictionaries, inheritance, string manipulation, MongoDB CRUD operations, file operations, lists, and pandas DataFrames. It also discusses SQL vs NoSQL databases, user-defined exceptions, regular expressions, multithreading, and several short coding problems. Additionally, it provides insights into Python features, scopes, and tuples.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

Q.

1) Dictionaries and Functions


Dictionaries are unordered collections of key-value pairs in Python. They are mutable and indexed by
keys.
# Dictionary examples
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
# i) len() - returns number of key-value pairs
print(len(my_dict)) # Output: 3
# ii) cmp() - Note: cmp() was removed in Python 3, we can use comparison operators
dict1 = {'a': 1, 'b': 2}
dict2 = {'a': 1, 'b': 3}
# To compare dictionaries in Python 3:
print(dict1 == dict2) # False
# iii) update() - merges one dictionary into another
dict1.update({'c': 3})
print(dict1) # {'a': 1, 'b': 2, 'c': 3}
# iv) get() - returns value for given key, or default if key doesn't exist
print(my_dict.get('name')) # 'John'
print(my_dict.get('salary', 'Not Found')) # 'Not Found'
Q.2) Inheritance and super() function
python
# Parent class
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return "Sound"
# Child class inheriting from Animal
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name) # Calls parent class's __init__
self.breed = breed
def speak(self):
return "Bark"
# Child class inheriting from Animal
class Cat(Animal):
def speak(self):
return "Meow"
# Demonstration
dog = Dog("Buddy", "Golden Retriever")
print(dog.name) # Buddy
print(dog.breed) # Golden Retriever
print(dog.speak()) # Bark

cat = Cat("Whiskers")
print(cat.speak()) # Meow
Q.3) Find all indices of a substring
python
def find_all_indices(main_string, sub_string):
indices = []
start_index = 0
while True:
index = main_string.find(sub_string, start_index)
if index == -1:
break
indices.append(index)
start_index = index + 1
return indices

# Example usage
text = "hello hello world hello"
print(find_all_indices(text, "hello")) # [0, 6, 18]
Q.4) MongoDB CRUD operations with Python
python
from pymongo import MongoClient

# Connect to MongoDB
client = MongoClient('mongodb://localhost:27017/')
db = client['example_db']
collection = db['example_collection']

# Create (Insert)
document = {"name": "John", "age": 30, "city": "New York"}
insert_result = collection.insert_one(document)
print("Inserted ID:", insert_result.inserted_id)

# Read (Find)
print("\nAll documents:")
for doc in collection.find():
print(doc)

# Update
update_query = {"name": "John"}
new_values = {"$set": {"age": 31}}
collection.update_one(update_query, new_values)
print("\nAfter update:")
print(collection.find_one({"name": "John"}))

# Delete
delete_query = {"name": "John"}
collection.delete_one(delete_query)
print("\nAfter delete, count:", collection.count_documents({}))
Q.5) File operations
python
# Part a) File modes:
# 'r' - Read (default)
# 'w' - Write (truncates existing file)
# 'a' - Append
# 'x' - Exclusive creation (fails if file exists)
# 'b' - Binary mode
# 't' - Text mode (default)
# '+' - Updating (read/write)

# Part b) File operations


# Writing to a file
with open('example.txt', 'w') as file:
file.write("Hello, World!\n")
file.write("This is a Python file operation example.\n")

# Reading from a file


with open('example.txt', 'r') as file:
content = file.read()
print("File content:")
print(content)

# Appending to a file
with open('example.txt', 'a') as file:
file.write("This line is appended.\n")
Q.6) Lists and List Functions
python
# Lists are ordered, mutable collections of items
my_list = [1, 2, 3, 4]

# insert(index, element) - inserts element at specified position


my_list.insert(1, 'a')
print(my_list) # [1, 'a', 2, 3, 4]

# append(element) - adds element to end of list


my_list.append(5)
print(my_list) # [1, 'a', 2, 3, 4, 5]

# extend(iterable) - adds all elements of iterable to end of list


my_list.extend([6, 7])
print(my_list) # [1, 'a', 2, 3, 4, 5, 6, 7]

# remove(element) - removes first occurrence of element


my_list.remove('a')
print(my_list) # [1, 2, 3, 4, 5, 6, 7]
Q.7) Convert last character of each word to uppercase
python
def last_char_upper(s):
words = s.split()
result = []
for word in words:
if len(word) > 0:
new_word = word[:-1] + word[-1].upper()
result.append(new_word)
return ' '.join(result)

# Example
text = "hello world python programming"
print(last_char_upper(text)) # hellO worlD pythoN programminG
Q.8) Adding index, row or column to pandas DataFrame
python
import pandas as pd

# Create a sample DataFrame


data = {'Name': ['John', 'Anna', 'Peter'],
'Age': [28, 24, 35]}
df = pd.DataFrame(data)

# Adding a column
df['City'] = ['New York', 'London', 'Paris']
print("After adding column:")
print(df)

# Adding a row
new_row = {'Name': 'Mike', 'Age': 40, 'City': 'Berlin'}
df = df.append(new_row, ignore_index=True)
print("\nAfter adding row:")
print(df)

# Setting a new index


df.index = ['A', 'B', 'C', 'D']
print("\nAfter setting new index:")
print(df)
Q.10) Inheritance Types
python
# Multiple Inheritance
class Parent1:
def method1(self):
print("Parent1 method")

class Parent2:
def method2(self):
print("Parent2 method")

class Child(Parent1, Parent2):


def method3(self):
print("Child method")

# Multilevel Inheritance
class Grandparent:
def method(self):
print("Grandparent method")

class Parent(Grandparent):
def method(self):
super().method()
print("Parent method")

class Child(Parent):
def method(self):
super().method()
print("Child method")

# Demonstration
print("Multiple Inheritance:")
c = Child()
c.method1()
c.method2()
c.method3()

print("\nMultilevel Inheritance:")
child = Child()
child.method()
Q.11) NumPy Arrays
python
import numpy as np

# Creating NumPy arrays


# From a list
arr1 = np.array([1, 2, 3, 4])
print("From list:", arr1)

# Array of zeros
arr2 = np.zeros((2, 3))
print("\nArray of zeros:")
print(arr2)

# Array of ones
arr3 = np.ones((3, 2))
print("\nArray of ones:")
print(arr3)

# Array with a range


arr4 = np.arange(10, 20, 2)
print("\nArray with range:")
print(arr4)
# Random array
arr5 = np.random.random((2, 2))
print("\nRandom array:")
print(arr5)
Q.12) Deleting from Pandas DataFrame
python
import pandas as pd
# Create a sample DataFrame
data = {'Name': ['John', 'Anna', 'Peter', 'Linda'],
'Age': [28, 24, 35, 32],
'City': ['NY', 'Paris', 'Berlin', 'London']}
df = pd.DataFrame(data, index=['a', 'b', 'c', 'd'])
# Deleting a column
df_drop_col = df.drop('City', axis=1)
print("After dropping column:")
print(df_drop_col)
# Deleting a row
df_drop_row = df.drop('b')
print("\nAfter dropping row:")
print(df_drop_row)

# Deleting by index
df_reset = df.reset_index(drop=True)
print("\nAfter resetting index:")
print(df_reset)
Q.13) Creating Pandas DataFrames
python
import pandas as pd

# From a dictionary
data = {'Name': ['John', 'Anna'], 'Age': [28, 24]}
df1 = pd.DataFrame(data)
print("From dictionary:")
print(df1)

# From a list of lists


data = [['John', 28], ['Anna', 24]]
df2 = pd.DataFrame(data, columns=['Name', 'Age'])
print("\nFrom list of lists:")
print(df2)

# From a list of dictionaries


data = [{'Name': 'John', 'Age': 28}, {'Name': 'Anna', 'Age': 24}]
df3 = pd.DataFrame(data)
print("\nFrom list of dictionaries:")
print(df3)

# From a CSV file


# df4 = pd.read_csv('data.csv')
Q.14) SQL vs NoSQL
NoSQL Databases are non-relational databases that provide flexible schemas and scale easily with large
amounts of data.

Comparison:

Feature SQL Databases NoSQL Databases


Data Model Table-based, rigid schema Flexible schema (document, key-value, etc.)
Scalability Vertical scaling Horizontal scaling
Transactions ACID compliant BASE model (Basically Available, Soft state, Eventually consistent)
Examples MySQL, PostgreSQL, Oracle MongoDB, Cassandra, Redis
Query Language SQL Varies by database
Best for Complex queries, transactions Large volumes of unstructured data
5 Marks Questions
Q.6) Various Short Questions
a) User-defined exceptions
python
class NegativeNumberError(Exception):
"""Raised when input is negative"""
pass
def sqrt(x):
if x < 0:
raise NegativeNumberError("Cannot compute square root of negative number")
return x ** 0.5
try:
print(sqrt(9))
print(sqrt(-4))
except NegativeNumberError as e:
print("Error:", e)
python
import pandas as pd

data = {'a': 1, 'b': 2, 'c': 3}


series = pd.Series(data)
print(series)
c) Regular expression methods

python
import re

pattern = re.compile(r'\d+') # matches one or more digits

# search() - finds first match anywhere in string


print(pattern.search('abc 123 def 456')) # matches '123'

# match() - matches only at beginning of string


print(pattern.match('123 abc')) # matches '123'
print(pattern.match('abc 123')) # no match

# findall() - returns all non-overlapping matches


print(pattern.findall('123 abc 456 def 789')) # ['123', '456', '789']

python
def fibonacci(n):
a, b = 0, 1
for _ in range(n):
print(a, end=' ')
a, b = b, a + b

fibonacci(10) # 0 1 1 2 3 5 8 13 21 34
e) Sum of odd and even numbers

python
def sum_odd_even(n):
odd_sum = 0
even_sum = 0
for i in range(1, n+1):
if i % 2 == 0:
even_sum += i
else:
odd_sum += i
return odd_sum, even_sum

odd, even = sum_odd_even(10)


print(f"Sum of odd numbers: {odd}, Sum of even numbers: {even}")
f) Leap year check

python
def is_leap_year(year):
if year % 4 != 0:
return False
elif year % 100 != 0:
return True
else:
return year % 400 == 0

print(is_leap_year(2000)) # True
print(is_leap_year(1900)) # False
print(is_leap_year(2020)) # True
g) Multithreading

python
import threading
import time

def print_numbers():
for i in range(5):
time.sleep(1)
print(i)

def print_letters():
for letter in 'abcde':
time.sleep(1)
print(letter)

# Create threads
t1 = threading.Thread(target=print_numbers)
t2 = threading.Thread(target=print_letters)
# Start threads
t1.start()
t2.start()

# Wait for both threads to complete


t1.join()
t2.join()

print("Done!")
h) Modules

python
# mymodule.py
def greet(name):
return f"Hello, {name}!"

def add(a, b):


return a + b

# main.py
import mymodule

print(mymodule.greet("Alice")) # Hello, Alice!


print(mymodule.add(2, 3)) # 5
i) Palindrome check

python
def is_palindrome(n):
original = str(n)
reversed_str = original[::-1]
return original == reversed_str

print(is_palindrome(121)) # True
print(is_palindrome(123)) # False
print(is_palindrome("madam")) # True
j) Matrix multiplication

python
def matrix_multiply(a, b):
return [[sum(i*j for i,j in zip(row, col)) for col in zip(*b)] for row in a]

# 2x2 matrices
matrix1 = [[1, 2], [3, 4]]
matrix2 = [[5, 6], [7, 8]]

result = matrix_multiply(matrix1, matrix2)


print(result) # [[19, 22], [43, 50]]
k) Prime number check

python
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True

print(is_prime(7)) # True
print(is_prime(10)) # False
l) Dictionary operations

python
my_dict = {'name': 'John', 'age': 30}

# Add
my_dict['city'] = 'New York'
print("After add:", my_dict)

# Remove
del my_dict['age']
print("After remove:", my_dict)

# Pop
city = my_dict.pop('city')
print("After pop:", my_dict, "Popped value:", city)

# Update
my_dict.update({'age': 35, 'job': 'Developer'})
print("After update:", my_dict)
Q.7) Short Notes
a) The dir() function

The dir() function returns a list of valid attributes and methods of an object. Without arguments, it re-
turns names in the current local scope.

python
import math
print(dir(math)) # Shows all names in math module

class MyClass:
def __init__(self):
self.x = 10
def method(self):
pass

print(dir(MyClass)) # Shows attributes and methods of MyClass


b) Features of Python

Interpreted: No need for compilation


Dynamic Typing: No need to declare variable types
Object-Oriented: Supports classes and objects
High-Level: Abstracts hardware details
Extensible: Can be extended with C/C++ modules
Large Standard Library: Rich set of built-in modules
Cross-Platform: Runs on Windows, Linux, Mac
Garbage Collected: Automatic memory management
Supports Multiple Paradigms: OOP, procedural, functional
Community Support: Large active community

c) Regular expression methods

Python has 4 variable scopes:


Local: Inside a function
Enclosing: In nested functions
Global: At module level
Built-in: Predefined names in Python

python
x = 'global' # Global scope

def outer():
x = 'enclosing' # Enclosing scope

def inner():
x = 'local' # Local scope
print(x)

inner()
print(x)

outer()
print(x)

d) Tuples

Tuples are immutable sequences, typically used to store collections of heterogeneous data.

python
# Creating tuples
t1 = (1, 2, 3)
t2 = ('a', 'b', 'c')
t3 = (1,) # Single-element tuple needs a comma

# Accessing elements
print(t1[0]) # 1

# Packing and unpacking


a, b, c = t1
print(a, b, c) # 1 2 3

# Immutable (can't change elements)


# t1[0] = 10 # Raises TypeError

# Use cases: returning multiple values from functions, dictionary keys


Very Important Topics

a) Lambda Function

Anonymous functions defined with the lambda keyword.

python
# Simple lambda
square = lambda x: x**2
print(square(5)) # 25

# With multiple arguments


add = lambda a, b: a + b
print(add(3, 4)) # 7

# Common use with map, filter, sort


numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x**2, numbers))
print(squared) # [1, 4, 9, 16]

even = list(filter(lambda x: x % 2 == 0, numbers))


print(even) # [2, 4]
pairs = [(1, 'one'), (2, 'two'), (3, 'three')]
pairs.sort(key=lambda pair: pair[1])
print(pairs) # [(1, 'one'), (3, 'three'), (2, 'two')]
b) Inheritance

c) Polymorphism

The ability to present the same interface for different underlying forms.

python
class Dog:
def speak(self):
return "Bark"

class Cat:
def speak(self):
return "Meow"

def animal_sound(animal):
print(animal.speak())

# Same method name, different behavior


dog = Dog()
cat = Cat()

animal_sound(dog) # Bark
animal_sound(cat) # Meow
d) Iterator and Generator

Iterator: Objects that implement __iter__() and __next__() methods.

python
class CountDown:
def __init__(self, start):
self.current = start

def __iter__(self):
return self

def __next__(self):
if self.current <= 0:
raise StopIteration
self.current -= 1
return self.current + 1

for num in CountDown(5):


print(num) # 5, 4, 3, 2, 1
Generator: Functions that yield values one at a time using yield.

python
def countdown(n):
while n > 0:
yield n
n -= 1

for num in countdown(5):


print(num) # 5, 4, 3, 2, 1
e) Multithreading

k) Matplotlib

python
import matplotlib.pyplot as plt
import numpy as np

# Simple line plot


x = np.linspace(0, 10, 100)
y = np.sin(x)

plt.plot(x, y)
plt.title("Sine Wave")
plt.xlabel("x")
plt.ylabel("sin(x)")
plt.grid(True)
plt.show()

# Bar chart
categories = ['A', 'B', 'C']
values = [10, 20, 15]
plt.bar(categories, values)
plt.show()

# Scatter plot
x = np.random.rand(50)
y = np.random.rand(50)
plt.scatter(x, y)
plt.show()
l) If-else, for, while

python
# if-elif-else
age = 20
if age < 13:
print("Child")
elif age < 20:
print("Teenager")
else:
print("Adult")

# for loop
for i in range(5):
print(i)

words = ['hello', 'world', 'python']


for word in words:
print(word.upper())

# while loop
count = 0
while count < 5:
print(count)
count += 1

You might also like