Problem Statement:
Sunday, 24 November 2024
Write a Python program that demonstrates the use of a recursive function, nested functions (FPP Assignment no 6)
Saturday, 23 November 2024
Why do we require Map, Filter and Lambda Function?
- To avoid repetition of code.
- To improve the code readability.
- To simplifies the code debugging.
- To enables reusability of code.
- To modularize the code.
lambda
, you would have to define or write a separate named function even for small or simple one line of tasks, making the code unnecessarily lengthy.Let's combine this 3 functions map, filter and lambda in one example.
numbers = [11, 22, 33, 44]
# Filter even numbers
evens = filter (lambda x: x % 2 == 0, numbers) # [22, 44]
# Square the even numbers
squared = map (lambda x: x ** 2, evens) # [ 484, 1936]
# Convert to list and print
result = list(squared)
print(result) # Output: [484, 1936]
Tuesday, 19 November 2024
Modules and Regular Expressions in Python.
Everyone knows what function is. A block of reusable code that performs specific task. Through function we can organize the code properly, making it more readable and reusable.
Now, question comes to mind that what is a module? why do we require module? How to create a module?
Let's first start with the question why do we require module?
To enhance the modularity of code or project, you can wrap or define more than one related function together and load these functionalities inside another program as and when required.
what is a module?
A module is a block or file consist of classes, variables, constants, definition of functions or any other python object.
or
A file containing more than one related function you want to include in your program just like a code library.
can any program access this module for reusability?
Yes, all the content available inside this module made available to any other program.
Now, next question comes to our mind is how we can access this in our program but before this How to create a module?
Let's create a simple module:
Step 1: First decide what name you want to give to your module. for example, if i want to create "JSPM" module.
Step 2: Create a file JSPM.py and write all the related code inside this file to make it a module.
def welcome (name):
print ("Hello, "+name+ "Welcome to JSPM University")
# Can we create object of subject's information in module?
Yes,
FPP = {
"Teachername": "Nitin Shivale",
"age": 36,
"Subjectname": "Fundamentals of python programming"
}
Step 3: JSPM Module is created with one welcome () function and one variable FPP of type dictionary in it. As we know we can create variable of all types like array, dictionary, objects etc. Now next task is we want to access all the functionalities available inside JSPM Module in another program. so, how we are going to access it?
Step 4: Suppose i have created the python file of name Admission.py and inside this file i want to write a code to greet all the students who are taking admission in JSPM University. Now we know that functionality is already available inside JSPM Module. no need to write same code once again so simply reuse that code by importing the functionality of that module inside our program.
import JSPM
name = input ("Enter the name of newly admitted student:")
JSPM.welcome (name)
After execution of this code message will display as follows:
Enter the name of newly admitted student: Tejas Bhosale
suppose if you enter the name = "Tejas Bhosale" then it will give us the output: Hello Tejas Bhosale Welcome to JSPM University
Can i create alias of my module and use it to access the functionality of module?
Yes, we can do this it's very simple just use the as keyword to do this.
import JSPM as ju
a = ju.FPP["Teachername"]
print(a)
Here after execution, you will get the output as follows:
Nitin Shivale
Q. Can i import only the required functionalities from the module instead of importing whole module?
Yes, you can suppose from the above example instead of calling all the functionalities i just wanted to import only dictionary variable that is FPP then see how i can do this.
from JSPM import FPP
print (FPP["Teachername"]) #output: Nitin Shivale
print (FPP["age"]) #Output: 36
print (FPP["Subjectname"]) #Output: Fundamentals of python programming
Module Search Path:
When we are importing the module in our program from where exactly it is located and gets loaded in our program is the next question comes to our mind.
Q. How the module search path works in the Python?
When you import module in your program for example, in our above example when we write import JSPM.
What will happen where the python will search that module let's learn this first:
Python will search for the JSPM.py
file from the following sources:
- The current folder from which the program executes.
- A list of folders specified in the PYTHONPATH environment variable, if you set it before.
- An installation-dependent list of folders that you configured when you installed Python.
Python stores the resulting search path in the sys.path
variable that comes from the sys
module.
If we want to check how many paths are there inside sys.path variable, then we can check this by writing following code.
To make sure Python can always find the module.py
, you need to:
- Keep
module.py
in the folder where the program will run. - Include the folder that contains the
module.py
in thePYTHONPATH
environment variable. Or you can keep themodule.py
in one of the folders included in thePYTHONPATH
variable. - Place the
module.py
in one of the installation-dependent folders.
Python allows you to modify the module search path at runtime by modifying the sys.path
variable. This allows you to store module files in any folder of your choice.
Since the sys.path
is a list, you can append a search-path to it.
dir()
function is a built-in function used to list the attributes (methods, properties, and other members like module, string, list, dictionaries, etc.) of an object.- For Class Objects, it returns a list of names of all the valid attributes and base attributes as well.
- For Modules/Library objects, it tries to return a list of names of all the attributes, contained in that module.
- If no parameters are passed it returns a list of names in the current local scope.
# Python3 code to demonstrate dir()
# when no parameters are passed
# Note that we have not imported any modules
print
(
dir
())
# Now let's import two modules
import
sysimport
math
print
(
dir
())
Output['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__']
['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '...
When User Defined Objects are Passed as Parameters
# Creation of a simple class with __dir()__
# method to demonstrate it's working
class
jspmbsiotr:
# Function __dir()___ which list all
# the base attributes to be used.
def
__dir__(
self
):
return [
'college_name'
,
'principal'
,
'intake'
,
'department'
,
'address'
]
# user-defined object of class jspmbsiotr
my_college
=
jspmbsiotr()
# listing out the dir() method
print
(
dir
(my_college))
Output['address', 'college_name', 'department', 'intake', 'principal']
Math Module:
The Math Module in Python provides all variety of mathematical functions including constants and Operations. Following program shows us the basic functionalities provided by the math module.
# Import the math module
import math
# Constants provided by the math module
print ("Math Constants:")
print ("Value of pi:", math.pi) # 3.141592653589793
print ("Value of e:", math.e) # 2.718281828459045
# Basic mathematical functions
print ("\nBasic Functions:")
number = -25
print (f"Absolute value of {number}: {math.fabs(number)}") # Absolute value
number = 16
print (f"Square root of {number}: {math.sqrt(number)}") # Square root
# Trigonometric functions
angle = math.pi / 4 # 45 degrees in radians
print (f"Sine of 45 degrees: {math.sin(angle)}") # Trigonometric sine
print (f"Cosine of 45 degrees: {math.cos(angle)}") # Trigonometric cosine
print (f"Tangent of 45 degrees: {math.tan(angle)}") # Trigonometric tangent
# Logarithmic functions
print ("\nLogarithmic Functions:")
number = 10
print (f"Natural logarithm (ln) of {number}: {math.log(number)}")
print (f"Base-10 logarithm (log10) of {number}: {math.log10(number)}")
# Exponential functions
print ("\nExponential Functions:")
exponent = 2
print (f"e raised to the power of {exponent}: {math.exp(exponent)}")
base = 2
power = 3
print(f"{base} raised to the power of {power}: {math.pow(base, power)}")
# Rounding functions
print ("\nRounding Functions:")
number = 4.7
print (f"Floor of {number}: {math.floor(number)}") # Rounds down
print (f"Ceiling of {number}: {math.ceil(number)}") # Rounds up
# Factorial
print("\nFactorial:")
number = 5
print (f"Factorial of {number}: {math.factorial(number)}")
# GCD (Greatest Common Divisor)
print ("\nGCD (Greatest Common Divisor):")
a = 48
b = 18
print (f"GCD of {a} and {b}: {math.gcd(a, b)}")
# Degrees and Radians Conversion
print ("\nDegree and Radian Conversions:")
angle_in_degrees = 180
angle_in_radians = math.radians(angle_in_degrees)
print(f"{angle_in_degrees} degrees in radians: {angle_in_radians}")
print(f"{angle_in_radians} radians in degrees: {math.degrees(angle_in_radians)}")