Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Python Unit - 4

This document covers functions and functional programming in Python, including how to create, call, and pass functions, as well as built-in functions like map(), filter(), and reduce(). It also discusses modules, their structure, and how to import them, along with various built-in functions available in Python. Additionally, the document explains class attributes and instances, illustrating their usage with examples.

Uploaded by

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

Python Unit - 4

This document covers functions and functional programming in Python, including how to create, call, and pass functions, as well as built-in functions like map(), filter(), and reduce(). It also discusses modules, their structure, and how to import them, along with various built-in functions available in Python. Additionally, the document explains class attributes and instances, illustrating their usage with examples.

Uploaded by

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

UNIT – 4 Example:

Functions and Functional Programming – Functions – calling functions


– creating functions – passing functions – Built-in Functions: apply( ),
filter( ), map( ) and reduce( ) - Modules – Modules and Files – Modules
built-in functions - classes – class attributes – Instances.

FUNCTION
 Function is a block of code.
 A large program divided into small program is called Output:
function.
 Function is defined using the def keyword.
CREATING FUNCTION
 The functions create using the keyword def.
 Function must end with the colon (:).
 Keyword cannot be used as function name.
 Function name followed by the parenthesis ().
 Parenthesis is used to pass the parameter or argument.
Syntax:
def function_name ():
#statement

V. Naresh Kumar, M.C.A., M.Phil., Page 1


CALLING FUNCTIONS PASSING FUNCTIONS
 Here, passing some value as a parameter to the function.
 To call a function, use the function name followed by
Syntax:
parenthesis:
Function_name (Parameter)
Syntax:
Example:
Function_name ()
Example:

Output:

Output:

V. Naresh Kumar, M.C.A., M.Phil., Page 2


BUILT-IN FUNCTIONS 2. filter ()
1. map()  The filter() function in Python filters elements from an
 Python's map() method applies a specified function to each iterable based on a given condition or function.
item of an iterable (such as a list, tuple, or string).  And returns a new iterable with the filtered elements.
 Then returns a new iterable containing the results. Syntax:
Syntax: filter(function, iterable)
map (function, iterable)  Here also, the first argument passed to the filter function is
 The first argument passed to the map function is itself a itself a function.
function.  And the second argument passed is an iterable (sequence of
 The second argument passed is an iterable (sequence of elements) such as a list, tuple, set, string, etc.
elements) such as a list, tuple, set, string, etc. Example:
Example: data = [1, 2, 3, 4, 5]
data = [1, 2, 3, 4, 5]
evens = filter(lambda x: x % 2 == 0, data)
squares = map(lambda x: x*x, data)
for i in squares: for i in evens:

print(i, end=" ") print(i, end=" ")


squares = list(map(lambda x: x*x, data)) evens = list(filter(lambda x: x % 2 == 0, data))
print(f"Squares: {squares}")
print(f"Evens = {evens}")

V. Naresh Kumar, M.C.A., M.Phil., Page 3


3. reduce()

 Given function to the elements of an iterable, reducing them


to a single value.

Syntax:

reduce(function, iterable[,initializer])

 The function argument is a function that takes two arguments


and returns a single value.
 The first argument is the accumulated value.
 The second argument is the current value from the iterable.

Example:

from functools import reduce

def add(a, b):

return a + b

num_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

as the second argument

sum = reduce(add, num_list)

print(f"Sum of the integers of num_list : {sum}")

sum = reduce(add, num_list, 10)

print(f"Sum of the integers of num_list with initial value 10 :


{sum}")

V. Naresh Kumar, M.C.A., M.Phil., Page 4


MODULES AND FILES IN PYTHON Create packages:
 Python file has the extension of “.py”.  Contains the __init__.py
 Module provides the reusable codes.  Contain initialization code for the package.
Example Example package structure:
Creating Module: my_package/
# File: my_module.py __init__.py
def greet(name): module1.py
print("Hello, {}!".format(name)) To import modules from a package,
def square(x): import my_package.module1
return x ** 2 from my_package import module2
pi = 3.14159 my_package.module1.function ()
module2.function ()
Importing module:
import my_module Imports within a package using dot notation:
my_module.greet("Alice") # Output: Hello, Alice! from . import module1
print(my_module.square(5)) # Output: 25 from .module2 import function module2.py
print(my_module.pi) # Output: 3.14159

Import specific functions or variables from the module:


from my_module import greet, square
greet("Bob") # Output: Hello, Bob!
print(square(3)) # Output: 9

V. Naresh Kumar, M.C.A., M.Phil., Page 5


MODULES BUILT-IN FUNCTIONS 11. open ():
 Opens a file and returns a file object.
1. Print ():
12. input ():
 Prints the given object to the standard output.
 Reads a line of input from the standard input (usually the
2. len():
keyboard).
 Returns the length (number of items) of an object such as a
14. enumerate ():
string, list, tuple, etc.
 Returns an enumerate object that yields pairs of indices and
3. input():
values from an iterable.
 Reads input from the user through the console.
15. zip():
4. int(), float(), str(), bool():
 Returns an iterator that aggregates elements from multiple
 Convert the given value to an integer, floating-point number,
iterables.
string, or boolean, respectively.
5. range():
 Generates a sequence of numbers.
6. type():
 Returns the type of an object.
7. max(), min():
 Returns the maximum or minimum value from a sequence or
set of arguments.
8. sum():

 Returns the sum of all elements in a sequence.

9. abs():
 Returns the absolute value of a number.
10. round():
 Rounds a number to a specified number of decimal places.

V. Naresh Kumar, M.C.A., M.Phil., Page 6


CLASS ATTRIBUTE & INSTANCE Program Explanation:
 Class attributes are attributes that are associated with a class  class_attribute is a class attribute.
rather than with instances (objects) of the class.  instance_attribute is an instance attribute.
 They are shared among all instances of the class.  Class attributes are accessed using the class name
 Class attributes are defined within the class definition but (MyClass.class_attribute)
outside of any methods.
Example:
class MyClass:
class_attribute = 10
def __init__(self, instance_attribute):
self.instance_attribute = instance_attribute
print(MyClass.class_attribute)
obj1 = MyClass(20)
obj2 = MyClass(30)
print(obj1.instance_attribute)
print(obj2.instance_attribute)
print(obj1.class_attribute)
print(obj2.class_attribute)
obj1.class_attribute = 100
print(obj1.class_attribute)
print(MyClass.class_attribute)
MyClass.class_attribute = 200
print(obj2.class_attribute)

V. Naresh Kumar, M.C.A., M.Phil., Page 7

You might also like