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

Python Soln

Uploaded by

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

Python Soln

Uploaded by

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

1.

Web Development: Used for building websites with frameworks like


Django and Flask.
2. AI and Machine Learning: Widely adopted for data analysis, ML
models, and visualization.
3. Game Development: Supports game engines and 3D games.
4. Desktop GUI Development: Tkinter, WxPython, and others for GUI
apps.
5. Business Applications: Scalable, readable, and extensible for
enterprise solutions.
6. Software Development: Libraries like SCons, Buildbot, and Apache.
7. Educational Purposes: Beginner-friendly syntax and broad community
reach.

—--------------------------------------------------------------------------------------------------

Indentation in Python is a way to define the scope of code blocks, such as


functions, loops, and conditionals. It replaces braces used in other languages,
making code more readable. Incorrect indentation leads to
IndentationError and affects program execution. Always use consistent
spaces or tabs for indentation.

In Python, the pass statement is a null operation. It serves as a placeholder


for future code. When executed, nothing happens, but it prevents errors when
empty code is not allowed (e.g., in loops, function definitions, or class
definitions). Use pass when you need a syntactically valid placeholder.

—--------------------------------------------------------------------------------------------------

A dictionary in Python is a data structure that stores values in key-value


pairs. Unlike lists or arrays, where elements are indexed by position,
dictionaries use keys to access their associated values. Each key must be
unique and immutable. Dictionaries are useful for organizing and retrieving
data efficiently. As of Python 3.7, they are also ordered and cannot contain
duplicate keys12.

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

--------------------------------------------------------------------------------------------------

In Python, an object is an instance of a class. A class acts as a blueprint,


defining attributes (data variables) and methods (functions). Objects
encapsulate data and methods into a single entity. For example, consider a
Car class: each car you create (like an Audi or BMW) is an object with its own
data (model, price) and behavior (methods like setprice() and
getprice()).

—--------------------------------------------------------------------------------------------------

NumPy is a powerful Python library used for array manipulation. It provides


a high-performance multidimensional array object and tools for working with
these arrays. NumPy is essential for scientific computing, offering efficient
calculations with arrays and matrices. It’s like a Swiss Army knife for numerical
tasks!

—--------------------------------------------------------------------------------------------------

Certainly! Here’s a concise explanation of how to read a CSV file in Python


and how to separate its values:

1. Reading a CSV File:


○ Use the pandas library’s read_csv() function.

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

—--------------------------------------------------------------------------------------------------

Certainly! SciPy, a powerful Python library, finds key applications in scientific


computing and data analysis:

1. Integration and Interpolation:


○ Provides functions for numerical integration and interpolation,
essential for solving mathematical problems.
2. Optimization Algorithms:
○ Solves optimization problems, such as finding maximum or
minimum values of functions.
3. Linear Algebra Operations:
○ Handles systems of linear equations, eigenvalue problems, and
matrix operations.
4. Signal and Image Processing:
○ Offers tools for working with audio, image, and video data.
5. Statistical Functions:
○ Supports data analysis, hypothesis testing, and descriptive
statistics.

SciPy enhances Python’s capabilities for scientific research, engineering, and


data science tasks.

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():

1. Implicit Type Conversion:

Python automatically converts data types when needed. For example:


a=7

b = 3.0

c = a + b # Result: 10.0 (float)

d = a * b # Result: 21.0 (float)


○ 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 int to float:


a=5

n = float(a) # Result: 5.0 (float)

Converting float to int:


a = 5.9

n = int(a) # Result: 5 (int)

Converting int to string:


a=5

n = str(a) # Result: '5' (string)

Converting string to float:


a = "5.9"

n = float(a) # Result: 5.9 (float)


Converting string to int (if the string represents a valid integer):
a = "5"

n = int(a) # Result: 5 (int)


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(a) # Result: 5 (int)

# The following line will raise a ValueError:

# n = int(b)


4. Addition of String and Integer Using Explicit Conversion:

Be cautious when combining different data types:


a=5

b = 't'

# The following line will raise a TypeError:

#n=a+b

○ Explicitly convert the variables to compatible types before performing


operations.

Remember, type casting allows you to manipulate data effectively in Python!

—--------------------------------------------------------------------------------------------------

In Python, a function is a block of organized, reusable code that performs a


specific task. Functions allow you to create modular, easy-to-read code by
encapsulating related statements. Here are some key points about Python
functions:

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

result = add(3, 5) # result is 8


4. Return Value:
○ Functions can return data using the return statement.

Example:
def multiply(x, y):

return x * y

product = multiply(2, 4) # product is 8


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

1. What Are Lambda Functions?


○ Lambda functions (also known as anonymous functions) lack a
name.
○ They have a more restrictive syntax than regular Python
functions.
○ Syntax: lambda arguments: expression
○ They’re handy for short, one-line operations.
2. Example 1: Converting Strings to Uppercase

Suppose we want to convert a string to uppercase using the upper()


method:
str1 = 'GeeksforGeeks'

upper = lambda string: string.upper()

print(upper(str1)) # Output: GEEKSFORGEEKS


3. Example 2: Condition Checking

Let’s create a lambda function that checks if a number is even or odd:


calc = lambda num: "Even number" if num % 2 == 0 else "Odd number"

print(calc(20)) # Output: Even number


4. Example 3: Using Lambda with map()

The map() function applies a given operation to every element in a list:


numbers = [1, 2, 3, 4, 5]

squared_numbers = list(map(lambda x: x**2, numbers))

print(squared_numbers) # Output: [1, 4, 9, 16, 25]


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

# Program to generate a random number between 0 and 9

# importing the random module

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

data = {'Name': ['Alice', 'Bob'],

'Age': [25, 30]}

df = pd.DataFrame(data, columns=['Name', 'Age'])


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]]

df = pd.DataFrame(data, columns=['Name', 'Age'])


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'],

'Age': [25, 30]}


df = pd.DataFrame(data)

-----------------------------------------------------------------------------------------------

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.

Example of creating a basic bar plot in Matplotlib:


import matplotlib.pyplot as plt

x = ['A', 'B', 'C']

y = [1, 5, 3]

plt.bar(x, y)

plt.xlabel('Categories')

plt.ylabel('Values')

plt.title('Basic Bar Plot')

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.

Example of creating a basic histogram in Matplotlib:


import numpy as np

data = np.random.randn(1000) # Generate random data


plt.hist(data, bins=30, color='skyblue', edgecolor='black')

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

-----------------------------------------------------------------------------------------------

Certainly! In Python, understanding errors and handling exceptions is crucial


for writing robust and reliable code. Let’s explore the basics:

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:

print("Cannot divide by zero")


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:

num = int(input("Enter a number: "))

except ValueError:

print("Invalid input. Please enter an integer.")


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():

raise MyCustomError("Something went wrong")

try:

my_function()

except MyCustomError as e:

print(f"Error: {e}")

-----------------------------------------------------------------------------------------------

What is a List?

○ A list is a fundamental data structure in Python.


○ It is an ordered, mutable collection of elements.
○ Elements can be of different data types (e.g., integers, strings,
other lists).
○ Lists are enclosed in square brackets [].
2. Creating Lists:
○ You can create a list by enclosing elements in square brackets,
separated by commas.

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]

print(numbers[2:7:2]) # Output: [3, 5, 7]

-----------------------------------------------------------------------------------------------

Certainly! Pandas is a powerful Python library widely used for data


manipulation and analysis. It provides two primary data structures: Series and
DataFrame.

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

my_series = pd.Series([10, 20, 30], index=['A', 'B', 'C'])


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.

Example (reading data from a CSV file):


import pandas as pd

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:

1. Read Mode (‘r’):


○ Opens an existing file for reading.
○ You can’t modify the content.

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:

file.write("New log entry\n")


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

Advantages of File Handling in Python:


1. Versatility:
○ Perform a wide range of operations—create, read, write, append,
rename, and delete files.
2. Flexibility:
○ Work with different file types (text, binary, CSV) and perform
diverse operations.
3. User-friendly:
○ Python provides an intuitive interface for file handling.
4. Cross-platform:
○ Functions work seamlessly across Windows, Mac, and Linux.

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

-----------------------------------------------------------------------------------------------

You might also like