Python Soln
Python Soln
—--------------------------------------------------------------------------------------------------
—--------------------------------------------------------------------------------------------------
—--------------------------------------------------------------------------------------------------—
In Python, a namespace is a system that assigns a unique name to each
object (such as variables or methods). It ensures isolation and prevents
naming conflicts. Python maintains namespaces using a dictionary. There are
three types: built-in, global, and local. Objects within a namespace have a
specific scope of accessibility.
--------------------------------------------------------------------------------------------------
—--------------------------------------------------------------------------------------------------
—--------------------------------------------------------------------------------------------------
Example:
import pandas as pd
df = pd.read_csv('your_file.csv')
○
2. Separating Values:
○ By default, read_csv() assumes a comma (,) as the delimiter.
To specify a different delimiter (e.g., tab or semicolon), use the sep argument:
df = pd.read_csv('your_file.csv', sep='\t') # For tab-separated values
—--------------------------------------------------------------------------------------------------
In Python, the head() and tail() functions are essential tools for data
analysis, particularly when working with pandas, a popular library for data
manipulation.
1. head() Function:
○ Displays the first few rows of a dataset.
○ Provides an overview of column names, data types, and initial
records.
○ Useful for understanding data structure.
Example:
import pandas as pd
df = pd.DataFrame(data={'Name': ['Ankit', 'Bhavya'], 'Age': [25, 30]})
print(df.head(2)) # Displays top 2 rows
○
2. tail() Function:
○ Shows the last few rows of a dataset.
○ Helpful for verifying data completeness and spotting trends.
Example:
print(df.tail(1)) # Displays last row
—--------------------------------------------------------------------------------------------------
Section-B
In Python, scalar data types represent individual values and are essential for various
programming tasks. Let’s explore some of the key scalar data types:
1. Integer (int):
○ Represents whole numbers (positive, negative, or zero).
○ No limit on the length of integers.
○ Example: 42, -10, 0.
2. Floating Point (float):
○ Represents real numbers with a decimal point.
○ Uses scientific notation (e.g., 1.23, 3.4556789e2).
3. String (str):
○ Represents sequences of characters (text).
○ Enclosed in single or double quotes (e.g., 'hello', "world").
4. Boolean (bool):
○ Represents truth values (True or False).
○ Used for logical operations and control flow.
5. Complex (complex):
○ Represents complex numbers (real part + imaginary part j).
○ Example: 3 + 2j.
6. None (NoneType):
○ Represents absence of a value or uninitialized variables.
○ Used for placeholders or default values
OR
Type casting, also known as type conversion, is the process of changing the data type of
a value or variable. In Python, this can be achieved using functions such as int(),
float(), and str():
b = 3.0
○
○ In implicit type conversion, Python handles the conversion automatically
without user involvement.
2. Explicit Type Conversion:
○ In this method, Python requires user intervention to convert a variable’s data
type explicitly.
○ Examples of explicit type casting:
■
Converting string to int (if the string represents a valid integer):
a = "5"
■
3. Handling Errors:
○ When converting a string to an int, if the string is not a valid number, it will
raise a ValueError.
Example:
a = "5"
b = 't'
# n = int(b)
○
4. Addition of String and Integer Using Explicit Conversion:
b = 't'
#n=a+b
—--------------------------------------------------------------------------------------------------
1. Function Definition:
○ Use the def keyword to define a new function.
Example:
def greet(name):
print(f"Hello, {name}!")
○
2. Function Call:
○ To execute a function, use its name followed by parentheses.
Example:
greet("Alice") # Output: Hello, Alice!
○
3. Parameters and Arguments:
○ Parameters are variables listed inside the function definition.
○ Arguments are the values passed to the function when it is called.
Example:
def add(a, b):
return a + b
○
4. Return Value:
○ Functions can return data using the return statement.
Example:
def multiply(x, y):
return x * y
○
5. Modularity and Reusability:
○ Functions allow you to break down complex tasks into smaller,
manageable parts.
○ Reusing functions across your program improves code readability
and maintainability.
OR
Certainly! Let’s delve into the world of tuples and sets in Python:
1. Tuples:
○ A tuple is an ordered, immutable collection of elements.
○ Created using parentheses ( ).
○ Key characteristics:
■ Ordered: Elements maintain their order.
■ Immutable: Once created, a tuple cannot be modified (you
can’t add, remove, or change elements).
■ Allows duplicates: Tuples can contain repeated values.
Example:
my_tuple = ("apple", 42, True)
○
2. Sets:
○ A set is an unordered, mutable collection of unique elements.
○ Created using curly braces { }.
○ Key characteristics:
■ Unordered: Elements have no specific order.
■ Mutable: You can add or remove elements.
■ No duplicates: Sets automatically remove duplicate
values.
Example:
my_set = {1, 2, 3, 3, 4}
○
3. Use Cases:
○ Tuples: Ideal for representing fixed data (e.g., coordinates, RGB
colors).
○ Sets: Useful for removing duplicates from a list, checking
membership, and performing set operations (union, intersection).
In summary, tuples are like read-only lists, while sets are unique, unordered
collections.
-----------------------------------------------------------------------------------------------
○
3. Example 2: Condition Checking
○
4. Example 3: Using Lambda with map()
○
5. When to Use Lambda Functions?
○ As arguments in higher-order functions like map, filter, and
reduce.
○ For concise operations where a full function definition isn’t
necessary.
○ Remember, readability matters—use comments and descriptions
for clarity.
OR
import random
print(random.randint(0,9))
-----------------------------------------------------------------------------------------------
1. Creating a DataFrame:
○ A DataFrame is a two-dimensional, potentially heterogeneous
tabular data structure with labeled axes (rows and columns).
○ You can create a DataFrame from lists, dictionaries, or by loading
data from existing storage (e.g., CSV files, SQL databases, Excel
files).
2. Dealing with Rows and Columns:
○ Column Selection: Access columns by their names using
df['column_name'].
○ Row Selection: Retrieve rows using df.loc[] or df.iloc[].
These methods allow you to select rows based on labels or
integer locations.
○ Adding and Deleting Rows/Columns: Use methods like
df.append(), df.drop(), and df.insert().
3. Indexing and Selecting Data:
○ Pandas provides powerful indexing capabilities, including
label-based (loc[]) and position-based (iloc[]) indexing.
○ You can slice, filter, and modify data using these methods.
4. Working with Missing Data:
○ Pandas handles missing data (NaN) gracefully. Use methods like
df.dropna(), df.fillna(), and df.interpolate().
5. Iterating over Rows and Columns:
○ Use df.iterrows() to iterate over rows, and
df.iteritems() to iterate over columns.
○ Be cautious with iteration, as vectorized operations are more
efficient.
OR
1. Using pd.DataFrame():
○ The pd.DataFrame() function constructs a DataFrame.
○ Pass data (e.g., lists, dictionaries) to create rows and columns.
○ Specify column names using the columns parameter.
Example:
import pandas as pd
○
2. From Lists of Lists:
○ Create a DataFrame from a list of lists.
○ Each inner list represents a row.
Example:
data = [['Tom', 10], ['Nick', 15]]
○
3. From Dictionaries:
○ Convert a dictionary of lists or arrays into a DataFrame.
○ Keys become column names, and values form the data.
Example:
data = {'Name': ['Alice', 'Bob'],
-----------------------------------------------------------------------------------------------
1. Bar Plots:
○ A bar plot (or bar chart) is a graphical representation that uses
bars to compare different categories of data.
○ It’s suitable for displaying categorical data (e.g., comparing sales
across different months, popularity of programming languages,
etc.).
○ Each bar represents a category, and the height of the bar
corresponds to the value associated with that category.
y = [1, 5, 3]
plt.bar(x, y)
plt.xlabel('Categories')
plt.ylabel('Values')
plt.show()
○
2. Histograms:
○ A histogram represents the frequency distribution of
continuous variables (e.g., numerical measurements, sensor
readings).
○ It divides the data into bins (intervals) and shows how many data
points fall into each bin.
○ The x-axis represents the bin ranges, and the y-axis shows the
frequency (number of data points) in each bin.
plt.xlabel('Values')
plt.ylabel('Frequency')
plt.title('Basic Histogram')
plt.show()
○
3. Key Differences:
○ Bar plots compare discrete categories, while histograms
visualize continuous data distributions.
○ In a bar plot, bars are separated, whereas in a histogram, bins
are adjacent.
○ Bar plots use categorical data, while histograms use numerical
data.
OR
-----------------------------------------------------------------------------------------------
1. Syntax Errors:
○ Syntax errors occur during code compilation.
○ They result from incorrect syntax (e.g., missing colons,
unmatched parentheses, misspelled keywords).
Example:
if x > 10 # Missing a colon
print("Hello")
○
2. Exceptions:
○ Exceptions occur during program execution due to unexpected
events.
○ Common exceptions include:
■ TypeError: Applying an operation to an incompatible data
type.
■ NameError: Using an undefined variable or function.
■ IndexError: Accessing an index out of range.
■ ValueError: Incorrect argument or input.
■ ZeroDivisionError: Attempting to divide by zero.
Example:
try:
result = 10 / 0
except ZeroDivisionError:
○
3. Handling Exceptions:
○ Use try and except blocks to catch exceptions.
○ The try block contains potentially problematic code.
○ The except block handles specific exceptions.
Example:
try:
except ValueError:
○
4. Custom Exceptions:
○ You can create custom exception classes by subclassing
Exception.
○ Useful for handling specific application-related errors.
Example:
class MyCustomError(Exception):
pass
def my_function():
try:
my_function()
except MyCustomError as e:
print(f"Error: {e}")
-----------------------------------------------------------------------------------------------
What is a List?
Example:
my_list = [10, 'apple', 3.14, True]
○
3. Accessing Elements:
○ Elements in a list are indexed starting from 0 (positive indexing).
○ You can access an element using its index.
Example:
print(my_list[1]) # Output: 'apple'
○
4. List Operations and Methods:
○ Appending: Add an element to the end of the list using
append().
○ Inserting: Insert an element at a specific index using insert().
○ Removing: Remove an element by value using remove() or by
index using pop().
○ Length: Get the number of elements using len().
○ Sorting: Sort the list using sort() or sorted().
○ Concatenating: Combine two lists using +.
○ Counting: Count occurrences of an element using count().
○ Copying: Create a shallow copy using copy().
5. List Slicing:
○ List slicing allows you to extract a portion of a list.
○ Syntax: my_list[start:end:step].
Example:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
-----------------------------------------------------------------------------------------------
1. Series:
○ A one-dimensional array-like object.
○ Consists of an array of data values and an associated index
(labels for each value).
Example:
import pandas as pd
○
2. DataFrame:
○ A two-dimensional tabular data structure.
○ Similar to a spreadsheet or SQL table.
○ Consists of rows (observations) and columns (variables).
○ Created from dictionaries, lists, or other data sources.
df = pd.read_csv('my_data.csv')
○
3. Reading CSV Files:
○ The read_csv() function reads data from a CSV file into a
DataFrame.
○ Parameters include filepath_or_buffer, sep (separator),
header, index_col, and more.
Example:
df = pd.read_csv('my_data.csv', sep=',', header=0)
1. isnull():
○ Detects missing (NaN) values in a DataFrame or Series.
○ Returns a Boolean mask indicating where values are missing.
2. dropna():
○ Removes rows or columns with missing values from a
DataFrame.
○ Allows customization based on conditions like threshold or
subset.
3. loc[]:
○ Accesses rows and columns by label (index or column names).
○ Primarily label-based, but can also use boolean arrays.
4. iloc[]:
○ Accesses rows and columns by integer position (0-based index).
○ Useful for selecting specific positions in a DataFrame.
-----------------------------------------------------------------------------------------------
Files are essential for storing and managing data, and Python provides
powerful tools for working with them.
File Modes:
When you work with files in Python, you encounter different modes that
dictate how you interact with the file. These modes determine whether you
can read, write, or append data. Here are the key file modes:
Example:
with open("my_file.txt", "r") as file:
content = file.read()
print(content)
○
2. Write Mode (‘w’):
○ Creates a new file or overwrites an existing one.
○ Use with caution!
Example:
with open("new_file.txt", "w") as file:
file.write("Hello, world!")
○
3. Append Mode (‘a’):
○ Adds new data to the end of an existing file.
○ Useful for log files or continuous data accumulation.
Example:
with open("log.txt", "a") as file:
○
4. Binary Mode (‘b’):
○ Reads or writes the file in binary format (e.g., images,
executables).
○ Useful for non-text files.
Example:
with open("image.jpg", "rb") as file:
image_data = file.read()
○
5. Text Mode (‘t’):
○ Reads or writes the file as text (default mode).
Example:
with open("lyrics.txt", "rt") as file:
lyrics = file.read()
Disadvantages:
1. Error-prone:
○ Be cautious with file permissions and system issues.
2. Security risks:
○ Handle user input carefully to avoid unauthorized file access.
3. Complexity:
○ Advanced file formats or operations can be intricate.
4. Performance:
○ Large files or complex operations may be slower.
-----------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------