PWP_Chapter 4
PWP_Chapter 4
PWP_Chapter 4
MARKS)
4.1 Use of Python built-in functions (e.g. type/data conversion functions,math functions
etc)
1. Explain Data Conversion functions in python.(Question given by sir) (2 Marks)
➢ Data conversion functions are used to convert data from one type to another.
➢ int(): This function converts a value to an integer type.
For example: x = int("10") # Converts the string "10" to an integer.
➢ float(): This function converts a value to a floating-point number.
For example: y = float("3.14") # Converts the string "3.14" to a float.
➢ str(): This function converts a value to a string.
For example: z = str(42) # Converts the integer 42 to a string
➢ bool(): This function converts a value to a boolean.
For example: a = bool(0) # Converts the integer 0 to False.
output :
Maximum value in the list is : 9
➢ Example :
import os
# Specify the directory name
directory_name = "new_directory"
# Create the directory
os.mkdir(directory_name)
print("Directory created successfully!")
7. Explain any four Python’s Built in Function with example ( S 23) (4 Marks)
➢ Python’s Built in Functions are :
i) len() : This function returns the length of an object such as a string, list, tuple, dictionary, etc.
example :
my_list = [1, 2, 3, 4, 5]
print(len(my_list)) # Output: 5
iii) max(): This function returns the maximum value among the arguments provided or the maximum
value in an iterable.
Example :
print(max(10, 20, 30)) # Output: 30
iv) min(): This function returns the minimum value among the arguments provided or the minimum
value in an iterable.
Example :
print(min(10, 20, 30)) # Output: 10
8. Write a python program to demonstrate the use of any six built in mathematical functions (W 23)
(6 Marks)
➢
import math
# 1. Absolute value
num1 = -10
abs_result = abs(num1)
print("Absolute value of", num1, "is:", abs_result)
# 3. Square root
num2 = 25
sqrt_result = math.sqrt(num2)
print("Square root of", num2, "is:", sqrt_result)
output :
Absolute value of -10 is: 10
Exponential of 2 is: 7.38905609893065
Square root of 25 is: 5.0
Sine of 45 degrees is: 0.7071067811865476
Cosine of 45 degrees is: 0.7071067811865476
Tangent of 45 degrees is: 0.9999999999999999
Logarithm base 10 of 1000 is: 3.0
Ceiling of 4.6 is: 5
Floor of 4.6 is: 4
output :
Inside function
3 State the use of keyword global with simple example. (Question Given by sir) ( 2 Marks)
➢ A global keyword is used to create global variables in Python from a non-global scope, i.e. inside
a function.
➢ Example :
x = 10 # global variable
def modify_global():
global x # declaring x as global
x = 20
modify_global()
print(x) # Output will be 20
4. Define function in python (Sample Paper) (2 Marks)
➢ In Python, a function is a block of reusable code that performs a specific task.
➢ Functions allow you to break down your program into smaller, manageable parts, making your
code more organized, readable, and reusable.
➢ Syntax for declaring a function :
def function_name(parameters) :
# Function body
[return value]
➢ Example : Adding two numbers through the function
def add_numbers(a, b):
return a + b
result = add_numbers(3, 5)
print("The sum is:", result)
output :
8
my_function()
➢ Global Variables :-
• Global variables are declared outside of any function or block of code and can be accessed
from any part of the program, including inside functions.
• They can be modified and assigned new values from any part of the program.
• If a variable is modified inside a function without being declared as global, Python treats it
as a new local variable within that function's scope.
• Example :
y = 20 # global variable
def my_function():
print("Inside function:", y)
my_function()
print("Outside function:", y)
6 Write a function that takes single character and prints „character is vowel‟ if it is
vowel,character is not vowel‟ otherwise. (Question given by sir) (4 marks)
➢ def check_vowel():
# Take input from the user
char = input("Enter a single character: ")
# Check if the character is a vowel
if char in ['a', 'e', 'i', 'o', 'u','A','E','I','O','U']:
print("Character is vowel")
else:
print("Character is not vowel")
9. Write a python program to calculate factorial of given number using recursive function. (Question
given by sir) (4 marks)
➢ def factorial(n):
# Base case: factorial of 0 is 1
if n == 0:
return 1
# Recursive case: multiply n by factorial of (n-1)
else:
return n * factorial(n - 1)
8 .Write a python program to find reverse of a given number using user defined function.(Question
given by sir) (4 marks)
➢ def reverse_number(num):
# Initialize a variable to store the reverse of the number
reverse = 0
Output :
Enter a number: 1234
Reverse of the number: 4321
9. Comparing between local and global variable (Sample paper) ( 4 marks)
➢
Comparision Basis Global Variable Local Variable
Definition declared outside the declared within the
functions functions
Lifetime They are created the They are created when the
execution of the program function starts its
begins and are lost when execution and are lost
the program is ended when the function ends
Data Sharing Offers Data Sharing It doesn’t offers Data
Sharing
Scope Can be access throughout Can access only
the code inside the function
Parameters needed parameter passing is not parameter passing is
necessary necessary
Storage A fixed location selected They are kept on the
by the compiler stack
Value Once the value changes it once changed the variable
is reflected throughout the don’t affect other
code functions of the program
output :
Enter 1st Number :10
Enter 2nd Number :20
Addition of 10 and 20 is : 30
output :
Enter a Number :123
Sum of Digits of 123 is : 6
13. Explain how to use user defined function in python with example ( S 22) (4 marks)
➢ i) User-defined functions allow you to create your own functions in Python to perform specific tasks.
ii) syntax for declaring user defined function in python is :
def function_name(parameters):
# Function body
# Perform tasks
return value # (optional)
iii) After declaring a function we need to call the function.
iv) Example :
def fun() :
print(“Inside function”)
fun()
output :
Inside function
14. What is local and global variables? Explain with appropriate example. ( W 22) (4 marks)
(i) Local Variables :-
• Local variables are declared inside a function or block of code and are accessible only within that
specific function or block.
• Once the function or block execution completes, the local variable is destroyed, and its value
cannot be accessed from outside that scope.
• Example :
def my_function():
x = 10 # local variable
print("Inside function:", x)
my_function()
(ii) Global Variables :-
• Global variables are declared outside of any function or block of code and can be accessed from
any part of the program, including inside functions.
• They can be modified and assigned new values from any part of the program.
• If a variable is modified inside a function without being declared as global, Python treats it as a
new local variable within that function's scope.
• Example :
y = 20 # global variable
def my_function():
print("Inside function:", y)
my_function()
print("Outside function:", y)
15. Write a python program to calculate factorial of given number using function ( Sample paper)
(6 Marks)
➢ def factorial(n):
# Base case: factorial of 0 is 1
if n == 0:
return 1
# Recursive case: multiply n by factorial of (n-1)
else:
return n * factorial(n - 1)
# Take input from the user
num = int(input("Enter a number: "))
# Check if the input is non-negative
if num < 0:
print("Factorial is not defined for negative numbers.")
else:
result = factorial(num)
print("Factorial of", num, "is:", result)
Output :
Enter a number: 5
Factorial of 5 is: 120
output :
square root of 25 is : 5
def calculate_area(radius):
return math.pi * math.pow(radius, 2)
radius = 5
area = calculate_area(radius)
print("Area of the circle with radius", radius, "is", area)
output :
Area of the circle with radius 5 is 78.53981633974483
import math
result = math.sqrt(25)
print("Square root of 25:", result) # Output: 5.0
iv) Advantages :
▪ Code Organization: Modules organize code into logical units, enhancing readability and
maintainability.
▪ Code Reusability: Modules facilitate the reuse of functions and classes across different
parts of a project, reducing redundancy.
▪ Namespace Isolation: Each module has its namespace, preventing naming conflicts and
promoting modular development.
▪ Encapsulation: Modules encapsulate functionality, hiding implementation details and
promoting abstraction for easier comprehension.
• Code Reusability: Once you've written code in a module, you can reuse it in different parts of
your program or in other programs altogether. This promotes code reuse and helps in
avoiding redundancy.
• Namespacing: Modules provide a way to create separate namespaces for different parts of
your program. This helps in avoiding naming conflicts between different variables, functions,
or classes.
• Importing: To use code from a module, you need to import it into your program using the import
statement. Once imported, you can access the functions, classes, and variables defined in the
module using dot notation (module_name.item_name).
iv) Example :
Calculating the square root of a number using math module.
import math
result = math.sqrt(25)
print("Square root of 25:", result) # Output: 5.0
11. Write a program for importing module for addition and subtraction of two numbers ( S 22)(4
Mrks)
➢ i) First, create a Python module named math_operations.py # math_operations.py
ii) Then, create another Python script in the same directory and import the math_operations
module to perform addition and subtraction:
# main.py
# Perform addition and subtraction using functions from the imported module
sum_result = math_operations.add(num1, num2)
difference_result = math_operations.subtract(num1, num2)
output :
Enter the first number : 10
Enter the second number :20
Sum : 30
Difference : -10
• Create a second file in the same directory called main file where we can import the module to
the top of the file and call the function.
vi) Example :
Create p1.py file and add the below code in the file
def add(a,b):
result=a+b
return result
def sub(a,b):
result=a-b
return result
def mul(a,b):
result=a*b
return result
def div(a,b):
result=a/b
return result
import p1
print("Addition= ",p1.add(10,20))
print("Subtraction= ",p1.sub(10,20))
print("Multiplication= ",p1.add(10,20))
print("Division= ",p1.add(10,20))
Output:
Addition= 30
Subtraction= -10
Multiplication= 30
Division= 30
In this example, we import NumPy as np, create a one-dimensional array [1, 2, 3, 4, 5], multiply each
element by 2, and print the resulting array [2, 4, 6, 8, 10].
14. List and explain any two standard packages of python (W 23)(2 Marks)
➢ Any Two Standard Packages are :
• Numpy Package : NumPy is a fundamental package for scientific computing with Python. It
provides support for multi-dimensional arrays and matrices, along with a collection of
mathematical functions to operate on these arrays efficiently.
• Pandas Package : This package provides high-performance, easy-to-use data structures and
data analysis tools for the Python programming language. It's particularly well-suited for
working with structured, tabular data, such as CSV files or SQL tables.
15. Define Package? Write the steps to create a package in python? (Question given by sir) ( 4 Marks)
➢ i) A package is a hierarchical file directory structure that defines
a single python application environment that comprises of
modules and subpackages and so on.
ii) Packages allow for a hierarchical structuring of the module
namespace using dot notation.
iii) To create a package in Python, we need to follow these three
simple steps:
1) First, we create a directory and give it a package name, preferably related to its operation.
2) Then we put the classes and the required functions in it.
3) Finally we create an __init__.py file inside the directory, to let Python know that the directory
is a package.
iv) Example :
Create a directory named mypkg and create a __init__.py file and save in the mypkg directory so
that mypkg will be considered as package.
• Create file p1.py in the mypkg directory and add this code
def m1():
print("First Module")
• Create file p2.py in the mypkg directory and add this code
def m2():
print("second module")
• Create file pkgsample.py and add this code
from mypkg import p1,p2
p1.m1()
p2.m2()
Output-
First Module
second module
4. Explain the following package with suitable example (Question given by sir) ( 4 marks)
i)numpy ii) scipy iii) pandas iv) matplotlib
➢ i) NumPy:-
• NumPy is a fundamental package for scientific computing with Python. It provides support for
multi-dimensional arrays and matrices, along with a collection of mathematical functions to
operate on these arrays efficiently.
• Example :
import numpy as np
output :
[ 2 4 6 8 10]
ii) SciPy:-
• SciPy is built on top of NumPy and provides additional functionality for scientific computing. It
includes modules for optimization, interpolation, integration, linear algebra, signal processing,
and more.
• Example :
from scipy.integrate import quad
output :
Result of integration: 0.33333333333333337
Estimated error: 3.700743415417189e-15
iii)pandas :
• Pandas is a powerful data analysis and manipulation library for Python. It provides data structures
like DataFrame and Series, along with tools for reading and writing data from various file formats,
data cleaning, reshaping, and analysis.
• Example :
import pandas as pd
# Create a DataFrame
data = {'Name': ['Alice', 'Bob', 'Charlie', 'David'],
'Age': [25, 30, 35, 40],
'City': ['New York', 'Los Angeles', 'Chicago', 'Houston']}
df = pd.DataFrame(data)
output :
Name Age City
0 Alice 25 New York
1 Bob 30 Los Angeles
2 Charlie 35 Chicago
3 David 40 Houston
iv) matplotlib :
• Matplotlib is a plotting library for Python that produces high-quality visualizations. It provides a
MATLAB-like interface for creating a variety of plots, including line plots, scatter plots, bar plots,
histograms, and more.
• Example :
import matplotlib.pyplot as plt
5.Write a program illustrating use of user defined package in python ( S 22) ( 4 Marks)
➢
1) Create a directory named mypkg1 and create a __init__.py file and save in the mypkg1 directory so
that mypkg1 will be considered as package.
2) Create modules message.py and mathematics.py with following code:
message.py
def sayhello(name):
print("Hello " + name)
return
mathematics.py
def sum(x,y):
return x+y
def average(x,y):
return (x+y)/2
def power(x,y):
return x**y
p1.py
Output
Hello Amit
power(3,2) : 9
import numpy as np
arr=np.array([[1,2,3],[4,5,6]])
a=arr.reshape(3,2)
print(a)
Output:
([[1,2],
[3,4],
[5,6]])