0% found this document useful (0 votes)
6 views9 pages

Python Programming

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views9 pages

Python Programming

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Q1)

a)

Python supports various built-in data types, which are essential for defining the kind of data a
variable can hold. These data types are broadly categorized into the following:

1. Numeric Types:

int: Represents integer values (e.g., 5, -10).

float: Represents decimal or floating-point numbers (e.g., 3.14, -0.001).


complex: Represents complex numbers with real and imaginary parts (e.g., 2+3j).

2. Sequence Types:

str: Represents a sequence of characters (e.g., "Hello", 'Python').

list: An ordered, mutable collection of items (e.g., [1, 2, 3]).

tuple: An ordered, immutable collection of items (e.g., (1, 2, 3)).

3. Mapping Type:

dict: A collection of key-value pairs (e.g., {'name': 'Alice', 'age': 25}).


4. Set Types:

set: An unordered collection of unique items (e.g., {1, 2, 3}).

frozenset: An immutable version of a set (e.g., frozenset({1, 2, 3})).

5. Boolean Type:

bool: Represents truth values, either True or False.

6. Binary Types:

bytes: Represents a sequence of bytes (e.g., b'Hello').


bytearray: A mutable version of bytes.

memoryview: Allows direct access to memory of an object.

7. None Type:

None: Represents the absence of a value or a null value.

b) Operator precedence determines the order in which operations are performed in an


expression. Python follows a specific hierarchy for evaluating operators, ensuring that
expressions are computed correctly. For example, multiplication is evaluated before addition.
Common Operator Precedence :
1. Parentheses (): Highest precedence, used to override default order.

2. Exponentiation : Computed next

3. Multiplication *, Division /, Floor Division //, Modulus %: Evaluated from left to


right.

4. Addition +, Subtraction -: Evaluated next.

5. Comparison Operators (==, !=, >, <, etc.): Used to compare values.

6. Logical Operators (not, and, or): not has higher precedence than and, which is
higher than or.

Q2)

a) In Python, the else statement can be used with both for and while loops. When used
with a loop, the else block executes only if the loop completes all iterations without
encountering a break statement.

The else statement in Python can be used with both for and while loops. It executes
only when the loop runs completely without encountering a break statement. If the
loop is interrupted by break, the else block is skipped.

In a for loop, the else block is useful when checking conditions that should apply
only if the loop completes all iterations. In a while loop, it helps execute code after
the loop ends naturally without being stopped prematurely.

For example, if a loop is searching for an item in a list and does not find it, the else
block can display a message saying the item was not found. However, if the item is
found and break is used, the else block will be skipped. This behavior makes else
statements useful for handling cases where loops finish normally versus when they
stop early.

for i in range(5):
if i == 3:
break
print(i)
else:
print("Loop completed without break.")

Output being 0 1 2

The while loop also follows the same behavior. The else block executes only if the
loop terminates normally without break. If break is used inside the loop, the else block
does not run.
b) Python provides several built-in string functions that allow for easy manipulation of
text.
upper(): Converts all characters in a string to uppercase. This is useful when ensuring
uniformity in text comparisons or formatting.
lower(): Converts all characters to lowercase. It is commonly used when performing
case-insensitive comparisons.
isdigit(): Checks if a string consists only of digits. This function is useful when
validating user input, such as checking if a given string is a valid number.
isalpha(): Returns True if the string contains only alphabetic characters and no
numbers or special symbols. This is useful when validating names or words.
split(): Splits a string into a list of words based on a specified delimiter. If no
delimiter is given, it splits by whitespace. This function is helpful in text processing,
such as breaking a sentence into words.
join(): The opposite of split(), it combines a list of words into a single string using a
specified separator. This is commonly used when formatting text, such as converting a
list of words back into a sentence.

Q3)
a) In Python, elements can be deleted from a list using methods like remove(),
pop(), and del. The choice depends on whether you want to delete by value,
index, or the entire list.
Deleting by Value (remove())
Removes the first occurrence of a specified value.
If the value does not exist, an error occurs.
Deleting by Index (pop())
Removes an element at a specified index and returns it.
If no index is given, it removes the last element.
Deleting Using del
Deletes an element at a specific index or removes a slice of elements.
Can also delete the entire list.
Different cases:
Removing a specific element by value
Removing an element by its index
Removing multiple elements using slicing
Clearing all elements

b)

Data Structure Ordered Mutable Allows Duplicates Key-Value Pair


List Yes Yes Yes No
Tuple Yes No Yes No
Set No Yes No No
Dictionary Yes (Python 3.7+) Yes Keys: No, Values: Yes Yes
• List: A dynamic, ordered collection that allows duplicate values and modification.
• Tuple: Similar to a list but immutable, meaning its elements cannot be changed after
creation.
• Set: An unordered collection that does not allow duplicates, making it useful for
unique value storage.
• Dictionary: Stores key-value pairs, allowing fast lookups and modifications but
ensuring unique keys.

Q4)

a) A lambda function is an anonymous, one-line function defined using the lambda


keyword. It is primarily used when a short, simple function is required without
formally defining it using def.
Why is it used?
Reduces code complexity by defining simple functions in a single line.
Useful for quick computations inside functions like map(), filter(), and sorted().
Eliminates the need for separate function definitions when a function is needed only
temporarily.
Example:
square = lambda x: x ** 2
print(square(5)) # Output: 25
Here, lambda x: x ** 2 defines an anonymous function that squares a number.

b)

Removes Specific Throws Error if Element Not Removes Random


Method
Element? Found? Element?

remove() Yes Yes No

discard() Yes No No

No (Removes any
pop() No Yes
element)

remove(x): Removes element x from the set. If x is not found, it raises a KeyError.

discard(x): Also removes x, but does not raise an error if x is missing.


pop(): Removes a random element from the set (since sets are unordered), making it useful
when you don’t need a specific item removed.

Example:
python
s = {1, 2, 3}

s.remove(2) # Removes 2

s.discard(5) # No error even though 5 is not present

s.pop() # Removes a random element


print(s)

Q5)

a) Exception handling is a mechanism in programming that allows a program to


handle runtime errors gracefully instead of crashing. In Python, exceptions
occur when an unexpected condition disrupts the normal flow of a program,
such as dividing by zero or accessing an invalid index in a list. Python
provides a structured way to handle these errors using try, except, else, and
finally blocks. Prevents Program Crashes: Instead of stopping execution, it
allows handling errors smoothly. Enhances Debugging: Helps identify issues
by catching specific errors. Improves User Experience: Provides meaningful
error messages rather than raw system errors. Ensures Continuity: Code
execution can continue even after encountering an error.
• try:
• # Code that may raise an exception
• except ExceptionType:
• # Code to execute if an exception occurs
• else:
• # Code that executes if no exception occurs
• finally:
• # Code that executes regardless of an exception

The try block contains the risky code.

The except block catches specific exceptions and handles them.

The else block executes if no exceptions occur.

The finally block executes whether an exception occurs or not.

b) Program to demonstrate exception handling for negative and zero values

def check_number():
try:

# Taking user input

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

# If the number is zero or negative, raise an exception

if num <= 0:

raise ValueError("Invalid input! Number must be greater than zero.")

# If valid, print the number

print(f"You entered: {num}")

except ValueError as e:
# Handling the exception and printing the error message

print(f"Error: {e}")

finally:

print("Execution completed.")

# Calling the function


check_number()

Breakdown of code:

1. User Input: The program prompts the user to enter a number.

2. Checking the Condition: If the number is less than or equal to zero, a ValueError is
raised using raise.

3. Handling Exception: The except block catches the ValueError and prints an
appropriate error message.

4. Ensuring Execution: The finally block ensures that "Execution completed." is


printed whether an error occurs or not.
Q6) a)

Use of Pandas, NumPy, and Matplotlib Libraries

Python provides powerful libraries for data manipulation, numerical computing, and data
visualization. The three most commonly used libraries in data science are Pandas, NumPy,
and Matplotlib.

1. Pandas

Pandas is a Python library used for data manipulation and analysis. It provides DataFrame
and Series objects to handle structured data efficiently.
Uses:

• Importing and exporting data (CSV, Excel, SQL, JSON).

• Data cleaning (handling missing values, filtering, and transformation).

• Aggregating and summarizing large datasets.

• Merging and joining datasets for better analysis.

Example:
import pandas as pd

df = pd.DataFrame({'Name': ['Alice', 'Bob'], 'Age': [25, 30]})

print(df)

2. NumPy

NumPy (Numerical Python) is used for numerical computing, providing support for multi-
dimensional arrays and mathematical functions.
Uses:

• Handling large datasets efficiently with ndarrays.

• Performing mathematical operations like mean, median, standard deviation.

• Efficient matrix operations, which are useful in machine learning.

Example:

import numpy as np
arr = np.array([1, 2, 3, 4])

print(arr.mean()) # Output: 2.5

3. Matplotlib

Matplotlib is a plotting library used for data visualization in Python. It helps create different
types of graphs like line charts, bar charts, and histograms.
Uses:
• Visualizing trends in data.

• Customizing charts for better readability.

• Creating complex plots for statistical analysis.

Example:
import matplotlib.pyplot as plt

x = [1, 2, 3, 4]

y = [10, 20, 25, 30]

plt.plot(x, y)

plt.show()

c) What Are CRUD Operations?

CRUD stands for Create, Read, Update, and Delete, which are the four fundamental
operations used to manage data in databases or applications.

1. Create (C)

This operation is used to add new records to a database or storage system.


Example (SQL):
INSERT INTO users (name, age) VALUES ('Alice', 25);

Example (Python with Pandas):


import pandas as pd
df = pd.DataFrame(columns=['Name', 'Age'])
df.loc[0] = ['Alice', 25]
print(df)

d) 2. Read (R)
This operation retrieves existing data from a database.
Example (SQL):
SELECT * FROM users;

Example (Python with Pandas)


print(df.loc[df['Name'] == 'Alice'])

e) 3. Update (U)
Used to modify existing records.

Example (SQL):
UPDATE users SET age = 26 WHERE name = 'Alice';

Example (Python with Pandas):


df.loc[df['Name'] == 'Alice', 'Age'] = 26
f) 4. Delete (D)

Removes records from the database.


Example (SQL):

DELETE FROM users WHERE name = 'Alice';

Example (Python with Pandas):

g) df = df[df.Name != 'Alice']

You might also like