1)
Answer:
a)
In Python, data types are divided into two types based on whether we can change their values after
creation or not. These two types are called mutable and immutable datatypes. This concept helps us
understand how data behaves in memory and how our program will work when we try to change
data.
Mutable datatypes are those whose values we can change after the object is created. Think of these
as things like a toy robot whose parts we can keep changing. Some common mutable types in
Python are lists, dictionaries, and sets. For example, if we make a list of our favorite snacks like
snacks = ["chips", "cookies", "juice"], later we can add "cake" to this list or remove "juice" from it.
The same list will change, and we don’t need to create a new one.
Example:
python
funny_list = ["laugh", "joke", "prank"]
funny_list.append("giggle")
print(funny_list)
Output will be: ['laugh', 'joke', 'prank', 'giggle']
See, we added "giggle" to the same list, so the list changed. That is why lists are mutable.
Immutable datatypes are those whose values we cannot change once they are created. Think of
these like a stone sculpture — once it is made, we cannot change its shape. If we want something
different, we have to make a new one. Examples of immutable types are integers, floats, strings, and
tuples. For example, if we have name = "Bob", and we try to change just one letter to make it
"Rob", Python will not change the original string. Instead, it will create a new string.
Example:
‘’’
name = "Bob"
new_name = [Link]("B", "R")
print(name)
print(new_name)
Output will be:
‘’’
Bob
Rob
See, name stayed as "Bob" and new_name became "Rob". That’s why strings are immutable.
b)
Python gives us two useful types of operators called membership operators and identity operators.
These help us in checking certain things easily.
Membership operators are used to check if a value is present inside a sequence like list, string, or
tuple. These are in and not in. They help us answer questions like "Is this item in my bag?" or "Is
this letter in my name?".
Example:
‘’’
funny_bag = ["banana", "clown", "balloon"]
print("banana" in funny_bag) # True
print("apple" not in funny_bag) # True
This tells us if "banana" is in the list (Yes, so True) and "apple" is not (so also True).
Identity operators are used to check whether two variables point to the same object in memory.
These are is and is not. They are like asking, "Are these two people the same person wearing
different hats, or are they completely different people?"
Example:
‘’’
funny_hat1 = ["red", "blue"]
funny_hat2 = funny_hat1
funny_hat3 = ["red", "blue"]
print(funny_hat1 is funny_hat2) # True
print(funny_hat1 is funny_hat3) # False
Here, funny_hat1 and funny_hat2 are actually the same list in memory. But funny_hat3 looks the
same but is a different object.
So, membership operators help us see if something exists inside another, and identity operators help
us know if two things are actually the same object.
2.)
Answer:
a)
In Python, when we create classes and objects, we often use variables inside them. These variables
can be of two types: instance variables and class variables. Both are used to store data, but they
behave differently.
Instance variables are variables that belong to each object separately. If we create two objects from
the same class, each object will have its own separate copy of the instance variable. It’s like if we
have two robots, Robot A and Robot B, and each one has its own favorite color. Robot A’s favorite
color can be red, and Robot B’s favorite color can be blue. Changing one robot’s color will not
affect the other robot.
Example:
‘’’
class Robot:
def __init__(self, color):
[Link] = color # instance variable
robot1 = Robot("red")
robot2 = Robot("blue")
print([Link]) # red
print([Link]) # blue
Class variables are shared among all objects of the class. If we change it from one object or even
from the class itself, it changes for everyone. It’s like a factory where all robots are made with the
same logo on their chest. If we change the logo, all robots will have the new logo.
Example:
‘’’
class Robot:
logo = "RoboCorp" # class variable
robot1 = Robot()
robot2 = Robot()
print([Link]) # RoboCorp
[Link] = "MegaRobo"
print([Link]) # MegaRobo
So, instance variables are like each robot’s own personality, while class variables are like the
company name all robots share.
b)
Python provides us with many easy-to-use functions to work with strings. These functions help us
change or check strings in fun ways.
upper()
This function converts all small letters in the string to capital letters.
Example:
‘’’
word = "hello world"
print([Link]()) # HELLO WORLD
lower()
This function changes all capital letters into small letters.
Example:
‘’’
word = "HELLO WORLD"
print([Link]()) # hello world
isdigit()
This checks if all characters in the string are numbers (digits) or not. It returns True or False.
Example:
‘’’
funny_num = "12345"
print(funny_num.isdigit()) # True
isalpha()
This checks if all characters in the string are alphabets (A-Z, a-z) without any spaces or numbers.
Example:
‘’’
name = "SillyName"
print([Link]()) # True
split()
This breaks a string into parts wherever it finds spaces (or other separators if we tell it). It returns a
list.
Example:
‘’’
sentence = "jokes are funny"
words = [Link]()
print(words) # ['jokes', 'are', 'funny']
join()
This joins the elements of a list into one string, using something (like a space or a dash) between the
words.
Example:
‘’’
words = ["let's", "have", "fun"]
sentence = " ".join(words)
print(sentence) # let's have fun
These functions make it easy for us to play with strings in Python and write programs that handle
text in simple ways.
3.)
Answer:
a)
A list in Python is a collection of items that we can store together in one variable. Lists are very
useful when we want to keep many values like numbers, names, colors, or even silly things like
funny jokes, in a single place. A list can hold different types of data like strings, numbers, or even
another list! Lists are written using square brackets [] and items are separated by commas.
Example of a simple list:
‘’’
funny_things = ["joke", "prank", "giggle", "laugh"]
Python gives us some easy methods to add new items to a list. Two important ones are insert() and
append().
append() method:
This method adds a new item at the end of the list. Think of this like adding another joke at the end
of our list of funny things.
Example:
‘’’
funny_things = ["joke", "prank"]
funny_things.append("giggle")
print(funny_things)
Output: ['joke', 'prank', 'giggle']
insert() method:
This method adds a new item at any position we want in the list, not just at the end. We need to tell
Python the position (using numbers starting from 0) and the item we want to insert.
Example:
‘’’
funny_things = ["joke", "giggle"]
funny_things.insert(1, "prank")
print(funny_things)
Output: ['joke', 'prank', 'giggle']
So, append() always adds to the end, while insert() can add at any position we choose.
b)
When we write classes in Python, sometimes we want to keep some data safe from being changed
or accessed directly from outside the class. For this, Python gives us two special ways to protect
variables: protected and private.
Protected variables:
These are created by writing a single underscore _ before the variable name. This tells other
programmers, “Please treat this as protected and don’t change it from outside unless you really
know what you are doing.” It is not fully private but works like a warning.
Example:
‘’’
class FunnyRobot:
def __init__(self):
self._battery = "80%" # protected variable
Private variables:
These are created by writing two underscores __ before the variable name. This hides the variable
from outside the class. It’s like hiding the robot’s secret joke collection so no one can mess with it
directly.
Example:
‘’’
class FunnyRobot:
def __init__(self):
self.__secret_joke = "Why did the robot laugh? Because it had a tickle bot!"
We cannot access __secret_joke directly from outside the class.
Importance:
These protected and private variables help us follow the good rule of encapsulation. Encapsulation
means keeping data safe inside the class and only allowing access through proper methods. This
helps prevent mistakes, bugs, and unexpected changes. It keeps our class clean and safe, like
locking the important stuff in a funny robot’s secret locker!
4.)
Answer:
a) Working of variable length and keyword arguments
In Python, sometimes we don’t know how many values someone will pass to a function. For
example, we might want to make a function that can greet any number of friends. In such cases,
Python gives us variable length arguments and keyword arguments.
Variable length arguments:
These allow us to pass any number of values to a function. We use a * (single star) before the
argument name. These arguments come into the function as a tuple.
Example:
‘’’
def tell_jokes(*jokes):
for joke in jokes:
print("Here’s a joke:", joke)
tell_jokes("Why did the chicken cross the road?", "Knock knock!", "Doctor, Doctor!")
Output:
‘’’
Here’s a joke: Why did the chicken cross the road?
Here’s a joke: Knock knock!
Here’s a joke: Doctor, Doctor!
See, we can pass 1 joke, 2 jokes, or 10 jokes — the function handles it.
Keyword arguments:
These allow us to pass any number of named values as arguments. We use ** (double star) before
the argument name. These arguments come into the function as a dictionary.
Example:
‘’’
def describe_funny_things(**things):
for key, value in [Link]():
print(f"{key} is {value}")
describe_funny_things(clown="silly", joke="funny", prank="harmless")
Output:
‘’’
clown is silly
joke is funny
prank is harmless
So, *args is for many unnamed values and **kwargs is for many named values.
b) .
In Python, sets are used to store unique items. Sometimes, we need to remove items from a set.
Python gives us three methods for this: remove(), discard(), and pop(). They sound similar but
behave a little differently.
remove():
This removes a specific item from the set. But if the item is not in the set, it gives an error.
Example:
‘’’
funny_set = {"joke", "prank", "giggle"}
funny_set.remove("prank")
print(funny_set)
Output: {'joke', 'giggle'}
If we try funny_set.remove("laugh") and "laugh" is not there, it will give an error.
discard():
This also removes a specific item from the set. But if the item is not there, it will not give any error.
It just quietly does nothing.
Example:
‘’’
funny_set = {"joke", "prank", "giggle"}
funny_set.discard("laugh") # no error
print(funny_set)
Output: {'joke', 'prank', 'giggle'}
pop():
This removes and returns a random item from the set because sets are unordered. We don’t get to
choose which item it will remove.
Example:
‘’’
funny_set = {"joke", "prank", "giggle"}
removed_item = funny_set.pop()
print("Removed:", removed_item)
print(funny_set)
Output could be different each time because sets have no order.
Summary:
remove(): Removes item, gives error if not found.
discard(): Removes item, no error if not found.
pop(): Removes a random item.
5.)
Answer:
When we write programs in Python, sometimes errors can happen while the program is running.
These errors are called exceptions. For example, if we try to divide a number by zero, or if we try to
open a file that does not exist, Python will stop the program and show us an error message. This is
bad because we don’t want our whole program to crash just because of one small mistake.
Exception handling is a way in Python to catch these errors and handle them properly so that the
program does not stop suddenly. It teaches us to write safe and smart programs that can manage
problems easily. Python gives us special words like try, except, else, and finally to handle
exceptions.
The basic idea is simple. We put the risky part of the code inside a try block. If any error happens,
Python will jump to the except block where we can write what we want to do if there is an error.
This way, the program keeps running smoothly.
Here is a fun example. Imagine we are writing a silly program called "Divide the Candies" where
we want to divide candies among friends. But what if the number of friends is zero? That will cause
a division by zero error.
Example:
‘’’
try:
candies = 10
friends = 0
result = candies / friends
except ZeroDivisionError:
print("Oops! Cannot divide candies among zero friends.")
In this example, if we try to divide by zero, Python will catch the error and show the message
instead of crashing.
How to Handle Multiple Exceptions in Python?
Sometimes there can be different types of errors in the same program. For example, maybe
someone gives us a string instead of a number, or maybe we are trying to divide by zero again. We
can handle multiple exceptions by writing multiple except blocks, each one for a different type of
error.
Here is a example called "Funny Calculator" where we try to divide two numbers but someone
might type a wrong input like a word.
Example:
‘’’
try:
num1 = int(input("Enter a number: "))
num2 = int(input("Enter another number: "))
result = num1 / num2
print("The answer is:", result)
except ZeroDivisionError:
print("Haha! Dividing by zero? That’s not allowed.")
except ValueError:
print("Please type numbers only, no funny words.")
except Exception:
print("Something went wrong, but we will not panic.")
In this program, we are handling three things. If someone types zero as the second number, we
catch ZeroDivisionError. If someone types letters instead of numbers, we catch ValueError. If
something else unexpected happens, we catch it with the last Exception block. This keeps our
program safe and friendly.
Exception handling is very important because it helps us make strong programs that do not crash
easily. It also helps us show nice messages to the users instead of scary error messages. It makes our
programs look more professional and easy to use.
6.)
Answer:
When we work with large datasets in Python using the pandas library, sometimes we find that some
data is missing. Missing data can cause problems in our analysis because it is like having
incomplete information. For example, imagine we are making a list of funny circus animals and
their ages, but some animals do not have their age written. If we try to calculate the average age,
this missing data will cause errors.
Pandas gives us some very useful methods to handle this missing data easily. Two of the most
common methods are dropna() and fillna().
dropna() method:
This method helps us remove rows or columns that have missing data. We use it when we think that
the missing data is not useful or it is better to just delete it. This keeps our data clean and simple.
Example:
‘’’
import pandas as pd
circus = [Link]({
'Animal': ['Clownfish', 'Elephant', 'Monkey', 'Parrot'],
'Age': [2, None, 5, None]
})
clean_circus = [Link]()
print(clean_circus)
Output will be:
‘’’
Animal Age
0 Clownfish 2.0
2 Monkey 5.0
Here, it removed rows where the Age was missing.
fillna() method:
This method helps us fill in missing values with something else. We can fill it with a specific
number, like 0, or with an average, or even with some funny word like "unknown". This is useful
when we do not want to lose data but still need to handle the missing parts.
Example:
‘’’
filled_circus = [Link](0)
print(filled_circus)
Output will be:
‘’’
Animal Age
0 Clownfish 2.0
1 Elephant 0.0
2 Monkey 5.0
3 Parrot 0.0
Here, missing ages are replaced with 0.
These methods help us keep our data clean, complete, and ready for further analysis without errors.
b) DDL and DML commands:
In databases, we use SQL (Structured Query Language) to work with data. SQL commands are
divided into different types based on what they do. Two important types are DDL and DML.
DDL (Data Definition Language):
DDL commands are used to define or change the structure of the database. This includes creating
tables, changing their structure, or deleting them. Think of this like building a house, adding new
rooms, or breaking down old walls.
Common DDL commands are:
CREATE: To create a new table.
ALTER: To change an existing table.
DROP: To delete a table.
Example:
‘’’
CREATE TABLE CircusAnimals (Name VARCHAR(50), Age INT);
This command creates a table to store animals and their ages.
DML (Data Manipulation Language):
DML commands are used to work with the data inside the tables. This includes adding new data,
changing it, or removing it. Think of this like moving furniture inside the house, not changing the
house itself.
Common DML commands are:
INSERT: To add new data.
UPDATE: To change existing data.
DELETE: To remove data.
Example:
‘’’
INSERT INTO CircusAnimals VALUES ('Clownfish', 2);
This adds a new animal to our table.
So, DDL helps us create and manage tables, while DML helps us add and manage the data inside
those tables. Both are very important to keep our database well-organized and useful.