PY Mod 2
PY Mod 2
Functions in Python
In Python a function is defined using the def keyword:
def my_function():
A function is a set of statements that take inputs, do some specific computation and produces output. The
idea is to put some commonly or repeatedly done task together and make a function, so that instead of
writing the same code again and again for different inputs, we can call the function. Python provides built-
in functions like print(), etc. but we can also create your own functions. These functions are called user-
defined functions.
def evenOdd( x ):
if (x % 2 == 0):
print( "even")
else:
print( "odd")
evenOdd(2)
evenOdd(3)
Output:
even
odd
One important thing to note is, in Python every variable name is a reference. When we pass a variable to a
function, a new reference to the object is created. Parameter passing in Python is same as reference passing
in Java.
Calling a Function
def my_function():
my_function()
Arguments
Arguments are specified after the function name, inside the parentheses. You can add as many arguments
as you want, just separate them with a comma. The following example has a function with one argument
(fname). When the function is called, we pass along a first name, which is used inside the function to print
the full name:
def my_function(fname):
print(fname + " Kapoor")
my_function("Anil")
my_function("Kareena")
my_function("Sonam")
• A parameter is the variable listed inside the parentheses in the function definition.
• Arguments are the values that are sent to the function when it is called.
You can send any data types of argument to a function (string, number, list, dictionary etc.), and it will be
treated as the same data type inside the function.
E.g. if you send a List as an argument, it will still be a List when it reaches the function:
def my_function(food):
for x in food:
print(x)
fruits = ["apple", "banana", "cherry"]
my_function(fruits)
Return Values
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
function definitions cannot be empty, but if you for some reason have a function definition with no content,
put in the pass statement to avoid getting an error.
def myfunction():
pass
Recursion
Python also accepts function recursion, which means a defined function can call itself.
Recursion is a common mathematical and programming concept. It means that a function calls itself. This
has the benefit of meaning that you can loop through data to reach a result.
The developer should be very careful with recursion as it can be quite easy to slip into writing a function
which never terminates, or one that uses excess amounts of memory or processor power. However, when
written correctly recursion can be a very efficient and mathematically-elegant approach to programming.
def fact(i):
if i==1:
return 1
else:
return i*fact(i-1)
a=int(input("Enter a number : "))
print("Factorial of "+str(a)+" is "+str(fact(a)))
Anonymous Functions (Lambda Functions)
Python Lambda Functions are anonymous function means that the function is without a name. As we
already know that the def keyword is used to define a normal function in Python. Similarly,
the lambda keyword is used to define an anonymous function in Python.
This function can have any number of arguments but only one expression, which is evaluated and returned.
One is free to use lambda functions wherever function objects are required. You need to keep in your
knowledge that lambda functions are syntactically restricted to a single expression. It has various uses in
particular fields of programming, besides other types of expressions in functions.
add = lambda x, y: x + y
result = add(3, 4)
print(result) # Output: 7
In this example, we define a lambda function that takes two arguments (x and y) and returns their sum. We
then assign this lambda function to the variable add. We can call add with two numbers, and it will return
their sum.
Lambda functions can take any number of arguments, including zero. Here's an example with zero
arguments:
message = greet()
Lambda functions can also be used in combination with built-in functions like map(), filter(), and reduce().
For instance:
numbers = [1, 2, 3, 4, 5]
In this example, the map() function applies the lambda function (which squares a number) to each element
in the numbers list, resulting in a list of squared numbers.
Lambda functions are particularly useful in situations where you need a simple, short-lived function
without the need for a formal function definition. Keep in mind that they are best suited for small, single-
purpose operations. If your code requires complex logic or readability is a concern, it's usually better to use
a named function.
Example 4
In the example, we defined a lambda function(upper) to convert a string to its upper case using upper().
print(upper(str1))
Example 5
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
mytripler = myfunc(3)
print(mydoubler(11))
print(mytripler(11))
Python modules are individual Python files that can be reused in other Python programs. They allow you
to organize your code into smaller, manageable pieces, making it easier to maintain and understand. A
module can define functions, classes, and variables. A module can also include runnable code. Grouping
related code into a module makes the code easier to understand and use. It also makes the code logically
organized. Modules can be either built-in, provided by Python itself, or created by users.
Built-in Modules
Python comes with a rich set of built-in modules that provide a wide range of functionalities. These modules
cover areas like file I/O, mathematics, system interfaces, and more. Some popular built-in modules include
math, os, random, and datetime.
# Sine of 2 radians
print(math.sin(2))
# 1 * 2 * 3 * 4 = 24
print(math.factorial(4))
# Returns the number of seconds since the Unix Epoch, January 1st 1970
print(time.time())
Creating Modules
Creating your own modules is straightforward. Simply save your Python code in a separate .py file and it
becomes a module. You can then import and use it in other Python scripts.
calc.py
The import statement is used to bring in modules into your current Python script. It allows you to access
the functions, classes, and variables defined in the module.
import module_name
Here, we are importing specific sqrt and factorial attributes from the math module.
The use of * has its advantages and disadvantages. If you know exactly what you will be needing from the
module, it is not recommended to use *, else do so.
print(sqrt(16))
print(factorial(6))
Locating Modules
Python searches for modules in specific directories. These directories are defined in the sys.path variable.
You can add your own directories to this list to make your modules accessible. Whenever a module is
imported in Python the interpreter looks for several locations. First, it will check for the built-in module, if
not found then it looks for a list of directories defined in the sys.path. Python interpreter searches for the
module in the following manner –
Here, sys.path is a built-in variable within the sys module. It contains a list of directories that the interpreter
will search for the required module.
# importing sys.path
print(sys.path)
Modules provide a way to create separate namespaces for your variables and functions. This helps in
avoiding naming conflicts. You can access the items in a module using dot notation, like module_name.item.
A namespace is a system that has a unique name for each and every object in Python. An object might be a
variable or a method. Python itself maintains a namespace in the form of a Python dictionary. Let’s go
through an example, a directory-file system structure in computers. Needless to say, that one can have
multiple directories having a file with the same name inside every
directory. But one can get directed to the file, one wishes, just by specifying
the absolute path to the file.
A lifetime of a namespace depends upon the scope of objects, if the scope of an object ends, the lifetime of
that namespace comes to an end. Hence, it is not possible to access the inner namespace’s objects from an
outer namespace.
Scope refers to the coding region from which a particular Python object is accessible. Hence one cannot
access any particular object from anywhere from the code, the accessing has to be allowed by the scope of
the object.
def some_func():
print("Inside some_func")
def some_inner_func():
var = 10
print("Inside inner function, value of var:",var)
some_inner_func()
print("Try printing var from outer function: ",var)
some_func()
Output:
Inside some_func
Inside inner function, value of var: 10
NameError: name 'var' is not defined
8 Naipunnya School of Management, Cherthala [Jithin Babu]
S5 BCA / BSc Computer Science CS1541/ CP1442: PYTHON PROGRAMMING [2]
dir()
The dir() function is used to get a list of names defined in a module. It returns a sorted list of strings
containing the names of all the attributes in the given module.
import module_name
print(dir(module_name))
dir() tries to return a valid list of attributes of the object it is called upon. Also, dir() function behaves rather
differently with different type of objects, as it aims to produce the most relevant one, rather than the
complete information.
• 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.
# return the module names added to the local namespace including all
# the existing ones as before
print(dir())
Output :
# dir() will return all the available list methods in current local scope
print(dir(nsm))
# Call dir() with the dictionary name "d" as parameter. Return all
# the available dict methods in the current local scope
print(dir(d))
reload()
The reload() function allows you to reload a module that has been previously imported. This can be useful
during development when you want to test changes to a module without restarting your Python
environment.
import importlib
importlib.reload(module_name)
Packages in Python
We usually organize our files in different folders and subfolders based on some criteria, so that they can be
managed easily and efficiently. For example, we keep all our games in a Games folder and we can even
subcategorize according to the genre of the game or something like this.
Packages are a way of organizing related modules into a single directory hierarchy. They allow for a better
organization of modules and avoid naming collisions. Packages are essentially directories with a special
__init__.py file, which can be empty or can contain initialization code for the package.
Modules and packages are fundamental concepts in Python programming. They help in organizing and
reusing code effectively, making your projects more manageable and maintainable. Understanding how to
use and create modules and packages will greatly enhance your proficiency in Python development.
Creating Package
Let’s create a package in Python named mypckg that will contain two modules mod1 and mod2. To create
this module follow the below steps:
Mod1.py
def abc():
print("Welcome to abc")
Mod2.py
__init__.py helps the Python interpreter recognize the folder as a package. It also specifies the resources to
be imported from the modules. If the __init__.py is empty this means that all the functions of the modules
will be imported. We can also specify the functions from each module to be made available.
For example, we can also create the __init__.py file for the above module as:
__init__.py
This __init__.py will only allow the abc and sum functions from the mod1 and mod2 modules to be imported.
We can import these Python modules using the from…import statement and the dot(.) operator.
Syntax:
import package_name.module_name
Example 1:
mod1.abc()
res = mod2.sum(1, 2)
print(res)
Example 2:
File handling is an essential aspect of programming, allowing you to interact with files on your system.
Python provides a straightforward way to perform various operations on files, including opening, reading,
writing, renaming, deleting, and managing directories.
The concept of file handling has stretched over various other languages, but the implementation is either
complicated or lengthy, but like other concepts of Python, this concept here is also easy and short. Python
provides inbuilt functions for creating, writing and reading files. There are two types of files that can be
handled in python, normal text files and binary files (written in binary language, 0s and 1s).
• Text files: In this type of file, Each line of text is terminated with a special character called EOL (End
of Line), which is the new line character (‘\n’) in python by default.
• Binary files: In this type of file, there is no terminator for a line and the data is stored after
converting it into machine-understandable binary language.
Versatility: File handling in Python allows you to perform a wide range of operations, such as creating,
reading, writing, appending, renaming, and deleting files.
Flexibility: File handling in Python is highly flexible, as it allows you to work with different file types (e.g.
text files, binary files, etc.), and to perform different operations on files (e.g. read, write, append, etc.).
User–friendly: Python provides a user-friendly interface for file handling, making it easy to create, read,
and manipulate files.
Cross-platform: Python file-handling functions work across different platforms (e.g. Windows, Mac,
Linux), allowing for seamless integration and compatibility.
f = open(filename, mode)
w: open an existing file for a write operation. If the file already contains some data then it will be
overridden but if the file is not present then it creates the file as well.
a: open an existing file for append operation. It won’t override existing data.
r+: To read and write data into the file. The previous data in the file will be overridden.
a+: To append and read data from the file. It won’t override existing data.
Example
# Open the file "MyFile1.txt" (same directory) in read mode and store its reference in the variable file1
# Open the file "MyFile2.txt" (from D:\Text) in write mode and store its reference in the variable file2
file1.close()
file2.close()
There is more than one way to read a file in Python. Let us see how we can read the content of a file in read
mode.
Example 1: The open command will open the file in the read mode and the for loop will print each line
present in the file.
# a text file named "myfile", will be opened with the reading mode.
print (each)
Example 2: In this example, we will extract a string that contains all characters in the file then we can
use file.read().
print (file.read())
Example 3: Another way to read a file is to call a certain number of characters like in the following code the
interpreter will read the first five characters of stored data and return it as a string:
print (file.read(5))
Example 4: In this example, we will see how we can read a file using the with statement.
The with statement is a replacement for commonly used try/finally error-handling statements. A common
example of using the with statement is opening a file. To open and read a file in Python:
data = file.read()
print(data)
The with statement automatically closes the file after you’ve completed writing it.
Example 5:
We can also split lines while reading files in Python. The split() function splits the variable when space is
encountered. You can also split using any characters as you wish.
data = file.readlines()
word = line.split()
print (word)
3. Writing to Files
write() : Inserts the string str1 in a single line in the text file.
File_object.write(str1)
writelines() : For a list of string elements, each string is inserted in the text file. Used to insert multiple
strings at a single time.
Example
Python os module provides methods that help you perform file-processing operations, such as renaming
and deleting files. To use this module you need to import it first and then you can call any related functions.
The rename() method takes two arguments, the current filename and the new filename.
import os
You can use the remove() method to delete files by supplying the name of the file to be deleted as the
argument.
Syntax : os.remove(file_name)
import os
Directories are a way of storing, organizing, and separating the files on a computer. The directory that does
not have a parent is called a root directory. The way to reach the file is called the path. The path contains
a combination of directory names, folder names separated by slashes and colon and this gives the route to
a file in the system.
• Every process in the computer system will have a directory associated with it, which is known as
Current Working Directory(CWD).
• os.chdir() method is used to change it.
• The parameter passed is the path/name of the desired directory to which one wish to shift.
Renaming a directory:
Removing a directory
file.close()
content = file.read()
print(content)
file.close()