0% found this document useful (0 votes)
5 views10 pages

Python Module II (1)

This document provides an overview of functions in Python, including their definition, how to define and call them, and the concept of arguments. It also covers advanced topics such as anonymous functions (lambda), recursion, return statements, modules, packages, and file handling. Key examples illustrate the usage of these concepts in Python programming.

Uploaded by

hermonie546
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)
5 views10 pages

Python Module II (1)

This document provides an overview of functions in Python, including their definition, how to define and call them, and the concept of arguments. It also covers advanced topics such as anonymous functions (lambda), recursion, return statements, modules, packages, and file handling. Key examples illustrate the usage of these concepts in Python programming.

Uploaded by

hermonie546
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/ 10

󾠯

python: Module II
Functions
Definition, Calling, and Arguments
A function is a block of code that accomplishes a certain task. Functions are used whenever we need to perform
the same task multiple times without writing the same code again. It can take arguments and returns a value.
There are several types of functions in Python including built-in functions that come along with Python itself such
as range() , id() , type() , input() , eval() etc.

Q. How to Define a function ?


Use the def keyword followed by the function name and a pair of parentheses () .

Include any parameters within the parentheses, separated by commas.

After the parentheses, include a colon : .

Indent the next line to begin the body of the function.

Example:

def greet(name):
print(f"Hello {name}!")

This defines a function named greet that takes one parameter name . When this function is called with an
argument, it will print a greeting message with the given name.

Q. How to Call a Function?


Write the function name followed by parentheses () .

Include any required arguments within the parentheses.

Example:

def greet(name):
print(f"Hello {name}!")

greet("John")

In this example, we call the greet function by writing its name followed by parentheses and passing the
argument "John" within the parentheses. This will print Hello John! .

Q.What are Arguments?


An argument is a value that you pass to a function when calling it.

python: Module II 1
The function can use this value in its code.

Arguments are specified within the parentheses when calling the function.

Multiple arguments are separated by commas.

Example:

def add(a, b):


result = a + b
print(f"{a} + {b} = {result}")

add(3, 5)

In this example, we define a function add that takes two arguments a and b . When we call the add function
with the arguments 3 and 5 , it will add these two numbers together and print the result: 3 + 5 = 8 .
{} ⇒ These are known as placeholders
Placeholders are used to insert values into a string.

In Python, you can use f-strings to embed expressions inside string literals.

The expressions inside the curly braces {} are evaluated and their values are inserted into the
string.

Anonymous Function
An anonymous function in Python is a function that is defined without a name. These functions are also called
lambda functions. They are defined using the lambda keyword rather than the def keyword used for normal
functions. Anonymous functions can take any number of arguments but can only have one expression. They are
commonly used for simple operations that do not require a full function definition, such as filtering or mapping
data.
Here’s an example of an anonymous function that adds two numbers:

sum = lambda arg1, arg2: arg1 + arg2


print(sum(10, 20))

OUTPUT

30

Lambda functions have their own local namespace and cannot access variables other than those in their
parameter list and those in the global namespace. They are often used as arguments to other functions that
expect a function object as one of their arguments.

Recursion
Recursion is a process in which a function calls itself directly or indirectly. It is a way to solve a problem by
breaking it down into smaller and simpler sub-problems. A recursive function must have a base condition that
stops the recursion, or else the function will call itself infinitely.
Here’s an example of a recursive function that calculates the factorial of a number:

def factorial(n):
if n == 1:

python: Module II 2
return 1
else:
return n * factorial(n-1)

In this example, the base condition is n == 1 . When this condition is met, the function returns 1 and stops calling
itself.
Recursive functions can make code look clean and elegant. However, they can be expensive in terms of memory
and time, as each recursive call creates a new stack frame in memory. Additionally, the logic behind recursion
can sometimes be hard to follow.
Recursion can be used to solve many problems in programming. For example, it can be used to generate
sequences, such as the Fibonacci sequence. It can also be used to traverse data structures like trees and
graphs.

Return
The return statement is used in Python functions to send the function’s result back to the caller. It consists of
the return keyword followed by an optional return value. The return value can be any Python object1.
Here’s an example of a function that uses the return statement to return the sum of two numbers:

def add(a, b):


return a + b

In this example, the add function takes two arguments, a and b , and returns their sum. When we call this
function with two numbers as arguments, it will return their sum:

result = add(3, 4)
print(result)

This will output 7 .


A return statement is a powerful tool that allows you to create reusable functions that can perform complex
operations and return their results to the caller. It is an essential part of writing clean and maintainable code in
Python.

Modules and Packages


Built-in Modules
Python has several built-in modules that provide a wide range of functionality. These modules are pre-defined
and loaded automatically when the Python interpreter starts. They are written in C and contain resources for
system-specific functionalities such as OS management, disk IO, networking, database connectivity, etc.
Some commonly used built-in modules include math , os , sys , datetime , random , and re . You can import these
modules into your Python script using the import statement. For example, to use the math module, you would
write:

import math

Once you have imported a module, you can use its functions and attributes by calling them using the dot
notation. For example, to use the sqrt function from the math module, you would write:

python: Module II 3
import math
result = math.sqrt(4)
print(result)

This will output 2.0 .


You can find a full list of Python’s built-in modules in the Python Module Index.

Creating Modules
Creating a module in Python is simple. A module is just a file containing Python code. To create a module, you
can write your code in a text editor and save it with a .py file extension.

Here’s an example of a simple module that defines a function called greet :

# my_module.py

def greet(name):
print(f"Hello, {name}!")

In this example, we’ve created a file called my_module.py that contains a single function called greet . This function
takes one argument, name , and prints a greeting message.

Once you’ve created your module, you can use it in other Python scripts by importing it using
the import statement. For example, to use the greet function from the my_module module in another script, you
would write:

import my_module

my_module.greet("John")

This will output Hello, John! .

Import Statements
The import statement in Python is used to access the code from one module into another module. It is the most
common way of invoking the import machinery, but it is not the only way. Functions such
as importlib.import_module() and built-in __import__() can also be used to invoke the import machinery.
When you use an import statement, Python searches for the named module and, if found, creates a module
object and initializes it. If the named module cannot be found, a ModuleNotFoundError is raised.
Here’s an example that demonstrates how to use the import statement to access the sqrt function from
the math module:

import math

result = math.sqrt(4)
print(result)

This will output 2.0 .

You can also use the from ... import ... syntax to import specific objects from a module. For example, to import
only the sqrt function from the math module, you would write:

python: Module II 4
from math import sqrt

result = sqrt(4)
print(result)

This will also output 2.0 .

Locating Modules
When you import a module in Python, the interpreter searches for the module in a specific order. First, it
searches for the module in the current directory. If the module isn’t found there, Python then searches each
directory in the PYTHONPATH environment variable. If all else fails, Python checks the default path. On UNIX
systems, this default path is normally /usr/local/lib/python/ .
The module search path is stored in the sys.path variable of the sys module. This variable contains a list of
directories that are searched for modules when you use an import statement.

You can use several methods to locate a particular module in Python. One way is to use the __file__ attribute of
the module object. This attribute contains the path to the file from which the module was loaded. Here’s an
example that demonstrates how to use the __file__ attribute to find the location of the os module:

import os

print(os.__file__)

This will output the path to the file from which the os module was loaded.

Namespace and Scope


A namespace is a collection of currently defined symbolic names along with information about the object that
each name references.

The scope of an object determines the parts of a program where that object can be accessed.

Python has four types of scopes: local, enclosing, global, and built-in.

The local scope refers to the innermost scope that contains local names. For example, if you define a
variable inside a function, that variable has local scope and can only be accessed within that function.

The enclosing scope refers to the scope of any enclosing functions. If a variable is defined in an enclosing
function, it can be accessed from within any inner function.

The global scope refers to the top-level scope of a module. If you define a variable at the top level of a
module (i.e., not inside any functions), that variable has a global scope and can be accessed from anywhere
within that module.

The built-in scope refers to the special scope that contains all of Python’s built-in objects. These objects are
available at all times when Python is running.

Example

x = "global"

def outer():
x = "outer"

def inner():
x = "inner"
print("inner:", x)

python: Module II 5
inner()
print("outer:", x)

outer()
print("global:", x)

In this example, we have three variables named x , each with a different scope. The first x has global scope, the
second x has an enclosing scope (within the outer function), and the third x has local scope (within
the inner function).

When we run this code, it will output:

inner: inner
outer: outer
global: global

As you can see, each print statement accesses the x variable from its corresponding scope.

dir()
The dir() function returns a list of names in the current local scope or a specified object.If called without any
argument, it returns the names in the current scope. Here's an example:

# Example 1: Names in the current scope


print(dir())

# Example 2: Names in a specific object


my_list = [1, 2, 3]
print(dir(my_list))

output

# Example 1
['__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'my_list']

#Example 2
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '_

The first example returns a list of names in the current scope, which includes built-in names ( __builtins__ ) and
any names defined by you (such as my_list ).
The second example returns a list of names associated with the list object ( my_list ). It includes both the built-
in attributes and methods of the list class ( __add__ , __class__ , append , clear , etc.), as well as any custom
attributes and methods you might have added.

reload()
The reload() function is used to reload a previously imported module. It is available in the imp module in Python
3.

import mymodule # Import the module

# Make changes to mymodule.py

# Reload the module


import imp
imp.reload(mymodule)

python: Module II 6
The reload() function takes the module object as an argument and reloads it. After reloading, the changes
made to the module will be reflected in your code. Keep in mind that reload() only affects the module you
explicitly reload, not its dependencies.

packages in Python
A Python package is a collection of Python modules that are stored in a directory. The directory must contain a
file named __init__.py in order to be considered a package.
Packages are used to organize and structure Python code. They can also be used to distribute Python code to
others.
To create a Python package, create a directory and add a file named __init__.py to the directory. You can then
add Python modules to the directory.
To import a Python package, use the import statement. For example, to import the package my_package , you
would use the following statement:

import my_package

Once you have imported a package, you can access its modules using the dot notation. For example, to access
the module my_module in the package my_package , you would use the following statement:

my_package.my_module

File Handling
File handling in Python is the process of reading, writing, and manipulating files. Python provides a built-in function
called open() to open a file. The open() function takes two parameters: the file name and the mode. The mode can
be one of the following:

'r' for reading

'w' for writing

'a' for appending

Once a file has been opened, you can use the read() and write() methods to read and write data to the file. The
read() method returns a string containing the contents of the file. The write() method writes a string to the file.

Open()
The open() function in Python is used to open a file. It takes two arguments: the file name and the mode. The
mode can be one of the following:

# opens a file in read mode


file = open('my_file.txt', 'r')

Close()
The close() method in Python is used to close a file. It is important to close files after you are finished with them
to free up system resources and to ensure that the file is properly closed.

python: Module II 7
file.close()

Where file is a file object.


You can also use the with statement to open and close files in Python. The with

statement ensures that the file is closed properly, even if an exception is raised. For example, the following code
opens the file my_file.txt , reads its contents, and then closes the file:

with open('my_file.txt', 'r') as file:


contents = file.read()

write()
The write() method in Python is used to write data to a file. The syntax for the write() method is:

file.write(data)

where file is a file object and data is the data to be written to the file. The data can be a string, a list, or any
other iterable object.
The write() method will write the data to the file at the current position of the file pointer. If the file pointer is at
the beginning of the file, the data will be written at the beginning of the file. If the file pointer is at the end of the
file, the data will be written at the end of the file.
The write() method returns the number of bytes written to the file.
Here is an example of how to use the write() method to write a string to a file:

f = open("myfile.txt", "w")
f.write("This is my text.")
f.close()

This will create a file called myfile.txt and write the string "This is my text." to the file.

Here is an example of how to use the write() method to write a list to a file:

f = open("myfile.txt", "w")
f.writelines(["This is my text.", "This is another line."])
f.close()

This will create a file called myfile.txt and write the two strings "This is my text." and "This is another line." to the
file.

read()
The read() method in Python is used to read data from a file. The syntax for the read() method is:

file.read(size)

where file is a file object and size is the number of bytes to read from the file. If size is not specified, the
entire file will be read.

python: Module II 8
The read() method returns a string containing the data that was read from the file.
Here is an example of how to use the read() method to read a file:

f = open("myfile.txt", "r")
text = f.read()
f.close()

This will open the file myfile.txt and read the entire file into the variable text .
The read() method can also be used to read a specific number of bytes from a file. For example:

f = open("myfile.txt", "r")
text = f.read(10)
f.close()

This will open the file myfile.txt and read the first 10 bytes of the file into the variable text .

The read() method can also be used to read a file line by line. To do this, you can use the readline() method.
The readline() method returns a string containing the next line from the file. For example:

f = open("myfile.txt", "r")
while True:
line = f.readline()
if not line:
break
print(line)
f.close()

rename()
The rename() method in Python is used to rename a file or directory. The syntax for the rename() method is:

os.rename(source, destination)

where source is the path to the file or directory to be renamed and destination is the new path to the file or
directory.
The rename() method returns the new path to the file or directory.
Here is an example of how to use the rename() method to rename a file:

import os

os.rename("myfile.txt", "newfile.txt")

This will rename the file myfile.txt to newfile.txt .

remove()
To delete a file in Python, you can use the os.remove() function from the os module. Here's an example:

import os

# Specify the path of the file to be deleted


file_path = "path/to/file.txt"

python: Module II 9
# Check if the file exists
if os.path.exists(file_path):
# Delete the file
os.remove(file_path)
print("File deleted successfully.")
else:
print("File does not exist.")

In the example above, file_path represents the path to the file you want to delete. You need to provide the
correct file path to the file_path variable.

The os.path.exists() function is used to check if the file exists at the specified path. If the file exists, the
os.remove() function is called to delete it. If the file does not exist, a message is printed indicating that the file
does not exist.

Directories
A directory is a structure that organizes files and subdirectories on a computer. It is 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.
In file handling, directories are used to store and manage files. They can be used to organize files by type,
project, or any other criteria that makes sense for the user. Directories can also be used to share files with other
users.

To create a directory, you can use the mkdir command. For example, to create a directory called my_files , you
would use the following command:

mkdir my_files

To add a file to a directory, you can use the cp command. For example, to copy the file my_file.txt to the
directory my_files , you would use the following command:

cp my_file.txt my_files

To list the contents of a directory, you can use the ls command. For example, to list the contents of the directory
my_files , you would use the following command:

ls my_files

To delete a directory, you can use the rmdir command. For example, to delete the directory my_files , you would
use the following command:

rmdir my_files

python: Module II 10

You might also like