Thanks to visit codestin.com
Credit goes to www.scribd.com

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

PWP Chapter-4 Previous Year Question Set

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)
4 views16 pages

PWP Chapter-4 Previous Year Question Set

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/ 16

Chapter-4

Summer-22
[2M]
1.Name different modes of python.
Ans:-
Interactive Mode – Run Python commands one at a time in the Python shell.
Script Mode – Run an entire Python program saved in a .py file.
IDLE Mode – Use Python's built-in GUI to write and run code interactively.
Jupyter Notebook Mode – Run code in cells with outputs shown inline in a web interface.
Command-Line Mode – Execute Python scripts directly from terminal or command prompt.
IDE Mode – Write and run code using development tools like PyCharm or VS Code.
Debug Mode – Execute code step-by-step to identify and fix errors.
Virtual Environment Mode – Isolate project-specific dependencies using venv.
Optimized Mode – Run Python with optimizations using python -O.

2. Explain how to use user defined function in python with example.


3. Write a program for importing module for addition and substraction of two numbers.
Ans:-
Create a module file named mymath.py
# mymath.py
def add(a, b):
return a + b

def subtract(a, b):


return a – b
Create a main program file to use the module
# main.py
import mymath
num1 = 10
num2 = 5

print("Addition:", mymath.add(num1, num2))


print("Subtraction:", mymath.subtract(num1, num2))
4. Explain use of format () method with example.
Ans:-
The format() method in Python is a powerful way to format strings. It allows you to insert
values dynamically into a string at specified places (placeholders) using curly braces {}.
Key Features:
1. Basic String Formatting:
You can use curly braces {} as placeholders, and then use .format() to replace them
with values.
2. Positional Arguments:
You can specify the order of insertion by using positions. For example, {0}, {1}, etc.,
refer to the corresponding argument passed to format().
3. Keyword Arguments:
Instead of using positional arguments, you can use named placeholders and pass the
values as keyword arguments.
4. Reusing Placeholders:
You can reference the same value multiple times within the string using the same
positional or keyword argument.
5. Formatting Numbers:
You can format numbers with a specific precision, padding, alignment, etc., directly
within the string.
6. Advanced Formatting Options:
The format() method provides more advanced formatting like controlling the width,
alignment, and decimal precision.
Syntax:
"string {placeholder}".format(value)

Examples:
Basic Formatting:
name = "Alice"
age = 25
print("My name is {} and I am {} years old.".format(name, age))
Output:
My name is Alice and I am 25 years old.

Positional Arguments:
print("First: {}, Second: {}, Third: {}".format(1, 2, 3))
Output:
First: 1, Second: 2, Third: 3
Keyword Arguments:
print("Name: {name}, Age: {age}".format(name="Bob", age=30))
Output:

Name: Bob, Age: 30


Reusing Arguments:
print("The {0} is {1} years old. {0} likes Python.".format("John", 35))
Output:
The John is 35 years old. John likes Python.

Formatting Numbers:
pi = 3.141592653589793
print("Pi rounded to 2 decimal places: {:.2f}".format(pi))
Output:
Pi rounded to 2 decimal places: 3.14
5. Write a program illustrating use of user defined package in python.(Repeat)
6.Explain package Numpy with example.
Ans:-
NumPy is a powerful Python library used for numerical computing. It provides an
efficient way to work with arrays and matrices, as well as a collection of mathematical
functions to operate on these data structures.
Key Features:
• Efficient Multidimensional Arrays: The core of NumPy is the ndarray object, a
fast, flexible, and memory-efficient array.
• Mathematical Functions: It provides functions for linear algebra, random
number generation, statistics, etc.
• Vectorization: It allows performing element-wise operations on arrays, avoiding
the need for explicit loops, making the code faster and more concise.
• Integration: NumPy integrates well with other scientific libraries such as SciPy,
Pandas, and Matplotlib.

Installation:

• To install NumPy, you can use the following command:

pip install numpy

• Basic Operations with NumPy

1. Importing NumPy:

import numpy as np

2. Creating Arrays:

• NumPy allows you to create arrays in various ways.

#Create a 1D array
arr1 = np.array([1, 2, 3, 4, 5])
print("1D Array:", arr1)

# Create a 2D array (matrix)


arr2 = np.array([[1, 2], [3, 4], [5, 6]])
print("2D Array (Matrix):\n", arr2)
3. Array Operations:

NumPy supports vectorized operations, meaning you can perform element-wise operations on
arrays without the need for explicit loops.

# Element-wise addition
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
sum_arr = arr1 + arr2
print("Array Addition:", sum_arr)

# Scalar multiplication
arr = np.array([1, 2, 3])
result = arr * 2
print("Scalar Multiplication:", result)

4. Array Indexing and Slicing:

You can access individual elements or slices of an array.

# Accessing elements
arr = np.array([10, 20, 30, 40, 50])
print("Element at index 2:", arr[2])

# Slicing
print("Slice from index 1 to 3:", arr[1:4])

5. Mathematical Functions:

NumPy offers a wide range of mathematical functions for statistical and algebraic operations.

arr = np.array([1, 2, 3, 4, 5])

# Sum of all elements


sum_arr = np.sum(arr)
print("Sum:", sum_arr)

# Mean of all elements


mean_arr = np.mean(arr)
print("Mean:", mean_arr)

# Standard deviation
std_arr = np.std(arr)
print("Standard Deviation:", std_arr)
6.Reshaping Arrays:

You can change the shape of an array using reshape().

arr = np.array([1, 2, 3, 4, 5, 6])


reshaped_arr = arr.reshape(2, 3)
print("Reshaped Array:\n", reshaped_arr)

7. Broadcasting:

Broadcasting allows NumPy to perform operations on arrays of different shapes.

arr1 = np.array([1, 2, 3])


arr2 = np.array([10])

result = arr1 + arr2 # Broadcasting arr2 across arr1


print("Broadcasting Result:", result)

8. Random Numbers:

NumPy also includes a random module for generating random numbers.

# Generating random numbers between 0 and 1


rand_arr = np.random.rand(3, 2)
print("Random Array:\n", rand_arr)

# Generating random integers between 0 and 10


rand_int_arr = np.random.randint(0, 10, (3, 2))
print("Random Integer Array:\n", rand_int_arr)
Example: Basic Array Operations

import numpy as np

# Create two arrays


arr1 = np.array([1, 2, 3, 4])
arr2 = np.array([5, 6, 7, 8])

# Array addition
sum_arr = arr1 + arr2
print("Addition of arrays:", sum_arr)

# Array multiplication by scalar


mult_arr = arr1 * 2
print("Multiplying array by scalar:", mult_arr)

# Sum of elements in arr1


arr_sum = np.sum(arr1)
print("Sum of arr1:", arr_sum)

# Mean of arr2
arr_mean = np.mean(arr2)
print("Mean of arr2:", arr_mean)

# Reshape arr1 into a 2x2 matrix


reshaped = arr1.reshape(2, 2)
print("Reshaped array:\n", reshaped)

Output:
Addition of arrays: [ 6 8 10 12]
Multiplying array by scalar: [2 4 6 8]
Sum of arr1: 10
Mean of arr2: 6.5
Reshaped array:
[[1 2]
[3 4]]
Winter-22
[2M]
7.Write use of lambda function in python.

[4M/6M]
8. What is local and global variables? Explain with appropriate example.
Ans:-
In Python, a command line argument is a way to pass information to your script when you
run it from the terminal or command prompt. These arguments allow you to influence the
behavior of your script without changing the code.

These arguments are accessible in the script through the sys.argv list, where:
• sys.argv[0] is the script name.
• sys.argv[1], sys.argv[2], etc., are the arguments passed by the user.

To use them, you must import the sys module.


import sys
num1 = int(sys.argv[1])
num2 = int(sys.argv[2])
total = num1 + num2
print("Sum:", total)

How to Run This Script:


python add.py 10 20
Output:
Sum: 30

9. Example module. How to define module.


Summer-23

[4M/6M]

10.Describe any two data conversion function.

11.Explain any four Python's Built-in Function with example.


12. Explain any four file modes in Python.(Repeat)
13. Explain Module and its use in Python.

Winter-23
[2M]
14. State use of namespace in python.
Ans:
A namespace in Python is a container that holds names (identifiers) and maps them to objects
like variables, functions, classes, etc
Namespaces are used to organize and manage names in a program to avoid naming conflicts.
They ensure that names are unique and do not interfere with each other.
Example:
# Global namespace
x = 10
def my_function():
# Local namespace
y=5
print("Inside function:", y)
my_function()
print("Outside function:", x)

Why Use Namespaces?


• To avoid conflicts between variable/function names.
• To organize code logically.
• To control scope (which variable is accessible where).
[4M/6M]

15. Write python program using module, show how to write and use module by
importing it.
Ans:
A module is simply a Python file (.py) containing functions, variables, or classes that can be
imported and reused in other Python programs.

Step 1: Create a Module File


Create a Python file named mymath.py with the following content:
# mymath.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b

Step 2: Create Another File to Use the Module


Create another Python file named main.py to import and use the module:
# main.py -
import mymath
x = 10
y=5
print("Addition:", mymath.add(x, y))
print("Subtraction:", mymath.subtract(x, y))

Output:
Addition: 15
Subtraction: 5

16.Explain Numpy package in detail.(Repeat)


17.Write a program illustrating use of user defined package in python.
Summer-24
[2M]
18.Write use of matplotlib package in python.
Ans:-
matplotlib is a powerful Python data visualization library used to create static, animated, and
interactive plots.

Uses of matplotlib:
1. Plotting Graphs: Line, bar, pie, scatter, and many other types of charts.
2. Data Analysis: Visualize trends, patterns, and outliers in data.
3. Scientific Research: Create publication-quality plots.
4. Dashboard and Reports: Integrate graphs into apps or exported reports.
5. Educational Tools: Help in teaching concepts with visual aids.

Plot Types in matplotlib:


• plt.plot() – Line chart
• plt.bar() – Bar chart
• plt.scatter() – Scatter plot
• plt.pie() – Pie chart
• plt.hist() – Histogram

Installation:
pip install matplotlib
Example:
import matplotlib.pyplot as plt
# Sample data
x = [1, 2, 3, 4]
y = [10, 20, 25, 30]

# Create a line plot


plt.plot(x, y)

# Add title and labels


plt.title("Sample Line Plot")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")

# Show the plot


plt.show()

[4M/6M]
19. Describe following Standard Packages
i) Numpy(Already Given)
ii) Pandas
Ans:-
Pandas is a powerful and widely-used Python library for data manipulation and analysis. It
provides two main data structures:
• Series (1D) – like a column in a spreadsheet.
• DataFrame (2D) – like an entire table with rows and columns.

Key Uses of Pandas:


1. Data Cleaning – Handle missing data, filter rows, and fix data types.
2. Data Transformation – Sort, group, reshape, and merge datasets.
3. Data Analysis – Perform statistical summaries, aggregations, and operations.
4. Data Input/Output – Read from and write to CSV, Excel, SQL, JSON, etc.

Example:
import pandas as pd

# Create a DataFrame
data = {
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35]
}
df = pd.DataFrame(data)

# Display the DataFrame


print(df)

# Access a column
print("Names:", df['Name'])

# Filter rows
print("Age > 25:\n", df[df['Age'] > 25])

Installation:
pip install pandas
Output:

Name Age
0 Alice 25
1 Bob 30
2 Charlie 35

Names: 0 Alice
1 Bob
2 Charlie
Name: Name, dtype: object

Age > 25:


Name Age
1 Bob 30
2 Charlie 35

20. Write a python program to create a user defined module that will ask your program
name and display the name of the program.
Ans:-
Step 1: Create a Module
# program_info.py
def ask_program_name():
name = input("Enter the name of your program: ")
print("The program name is:", name)

Step 2: Create Main Program


# main.py
import program_info # Importing the custom module
# Call the function from the module
program_info.ask_program_name()
Ouput:
Enter the name of your program: Calculator
The program name is: Calculator

21. Write a program function that accepts a string and calculate the number of
uppercase letters and lower case letters.

Ans:-
def count_case(s):
upper = lower = 0
for c in s:
if c.isupper():
upper += 1
elif c.islower():
lower += 1
print("Uppercase:", upper)
print("Lowercase:", lower)

text = input("Enter a string: ")


count_case(text)

OUTPUT
Enter a string: PyTHon Fun!
Uppercase: 4
Lowercase: 4
Summer-24
[4M/6M]
22.Write a program illustrating use of user defined package in Python.
23. Explain how to use user defined function in Python with example.(repeat)
24. How to write, import and alias modules.

Ans:-
Writing and importing module(Already given)
Aliasing a Module
You can alias a module to give it a shorter name when you import it. This is helpful if the
module name is long or if you want a more convenient name to use in your code.
Example: Aliasing a Module
# main.py
import math_operations as mo # Alias the module

# Using functions from the aliased module


result = mo.add(5, 3)
print("Addition:", result)

result = mo.subtract(5, 3)
print("Subtraction:", result)

You might also like