App Dev Using Python-Chapter 2
App Dev Using Python-Chapter 2
Files:
Python File handling is an essential concept in Python's programming framework. It enables you to use your
Python code directly to create, read, write, and manage files. The ability to handle data storage, retrieval,
and modification in a flexible manner facilitates the management and processing of huge datasets.
Types of Files in Python
1. Text files: Typically ending in.txt, these files contain data in a readable format for humans
to access.
Any text editor can be used to edit the plain text that they contain.
Text files can be handled in Python utilizing modes like a for appending, w for writing, and r
for reading.
2. Binary Files: Unlike text files, binary files contain data like pictures, films, or computer programs
that are not readable by humans. .bin or.dat are typical extensions for them.
Python handles similar to text files, binary files with the addition of a b suffix, such as rb for
reading binary files and wb for writing them.
Q) File Objects
A file object is an object in Python that gives access to files. These could be the on-disk files, meaning files
in the hard disk, or files present in other storage and communication devices. Once such a file object is
created, then we can use different methods like read() and write(), to read from
and write to the files, respectively.
Create a file object: We create a file object using the open() built-in function. In the "open()" function, we
also provide certain parameters or values within the parenthesis.
The file object can be closed using the close() method: After the file object has been created and
contents have been read or written to the file, we need to close the file object. The file object can be closed
using the close() method. If you don’t use with and also don’t call .close() then the file object remains
open until Python’s garbage collector eventually destroys it. This can take time. On some systems, too
many open files can cause errors
File Operations in Python
1. Opening Files in Python: To open a file using both relative and absolute paths. Different
file access modes for opening a file read and write mode.
Syntax:
file = open("filename", "mode")
Where, filename is the name of the file to open and mode is the mode in which the file is opened (e.g., 'r'
for reading, 'w' for writing, 'a' for appending).
There are four different methods (modes) for opening a file:
"r" - Read - Default value. Opens a file for reading, error if the file does not exist
"a" - Append - Opens a file for appending, creates the file if it does not exist
"w" - Write - Opens a file for writing, creates the file if it does not exist
"x" - Create - Creates the specified file, returns an error if the file exists
Example:
"r" - Read - Default value. Opens a file for reading, error if the file does not exist
Example:
f=open(“C:\users|download\file.txt”,”r”)
print(f.read())
f.close()
Using with statement
with open("C:/Users/IQAC/Downloads/file.txt","r") as f:
print(f.read())
"a" - Append - Opens a file for appending, creates the file if it does not exist
Example:
with open("C:/Users/IQAC/Downloads/file.txt","a") as f:
f.write("File has added with some extra content")
"w" - Write - Opens a file for writing, creates the file if it does not exist
Example:
with open("Example.txt","a") as f:
f.write("\nFile has added with some extra content")
"x" - Create - Creates the specified file, returns an error if the file exists
Example:
with open("C:/Users/IQAC/Downloads/filedemo.txt","x") as f:
f.write("This file is created using x mode")
Q. File Built-in Function [open()]
Python has a built-in function open() to open a file. Which accepts two arguments, file name and access
mode in which the file is accessed. The function returns a file object which can be used to perform
various operations like reading, writing, etc.
Syntax: Fileobject open (file-name, access-mode)
file-name: It specifies the name of the file to be opened.
access-mode: There are following access modes for opening a file:
Access Descrption
mode
“w” Write – opens a file writing, creates the file it doesnot exist
“r” Read-default value. opens a file for reading error if the file
doesnot exist
“a” Append-open a file for appending , creates the file if doesnot
exist
“x” Create-create the specified file, returns an error if the file exist
“r+” Open a file for updating doesn’t overwrite if the file exists
f.close()
print(f.closed) # True → file is closed
file.mode:
A string representing the access mode with which the file was opened (e.g., 'r' for read, 'w' for write, 'a' for
append, 'r+' for read and write).
Example:
# Open a file in write mode
f = open("example.txt", "w")
print(f.mode) # Output: 'w'
f.close()
Q. Standard Files
Standard files in Python refer to the way Python handles input and output operations. Python treats
every input and output as a file, allowing for a consistent way to interact with various data streams.
When a Python program starts, three standard file objects are automatically opened and available for
use. They correspond to the standard input, output, and error streams of the operating system These
standard files are automatically available when a Python program runs.
These streams provide a way for the program to interact with the external environment, such as the
user's console or other programs. The three standard files are:
Types of Standard Files
Standard Input (stdin)
This is the default input stream, typically connected to the user's keyboard. It allows the program to
receive input from the user. In Python, the input() function reads data from stdin.
Represents the source of input for the program, typically the keyboard. Accessed using
sys.stdin.
Used to read data provided by the user or another program.
We need to import sys to use standard files like sys.stdin, sys.stdout, and sys.stderr in Python.
Example:
import sys
print("Enter your name:")
name=sys.stdin.readline()
print("Hello",name)
Standard Output (stdout)
This is the default output stream, usually connected to the user's console or terminal it allows the
program to display output to the user In Python, the print() function writes data to stdout
Represents the destination for output from the program, typically the console
Accessed using sys.stdout or the print() function.
Example:
import sys
sys.stdout.write("This is standard output.\n")
Standard Error (stderr)
Used to display information to the user or another program Standard Error (stderr)
Used to display error messages separately from normal output.
This is a separate output stream specifically for error messages and diagnostic information. It is also
typically connected to the user's console, but it can be redirected separately from stdout. In Python,
you can write to stderr using the sys.stderr object.
Represents the destination for error messages and diagnostics.
Accessed using sys.stderr
Used to output error information separately from regular output.
Example:
import sys
sys.stderr.write("This is an error message!\n")
a) Using sys.argv:
The simplest way to handle command line arguments is by using the sys module's argy. The argy is a list
in Python, which contains the command-line-arguments pass argument to python script. The first
argument, argv[0], is always the script name itself.
Ex:
import sys
print("Script Name is:", sys.argv[0])
print("Arguments are:", sys.argv[1:])
Command Line Interface:
python generate random.py 1 100 5
Output:
Script Name is generate_random.py
Arguments are:[1,100.5]
Q. File System
In python, the file system contains the files and directories. To handle these files and directories python
supports "os" module. Python has the "os" module, which provides us with many useful methods to
work with directories (and files as well).
The os module provides us the methods that are involved in file processing operations and directory
processing like renaming, deleting, get current directory, changing directory etc.
Renaming the file rename():
The os module provides us the rename() method which is used to rename the specified file to a new
name.
Syntax: os.rename ("current-name", "new-name") Ex:
import os;
#rename file2.txt to file3.txt
os.rename("file2.txt","file3.txt")
Removing the file - remove():
The os module provides us the remove() method which is used to remove the specified file. Syntax:
os.remove("file-name")
Ex:
import os:
#deleting the file named
file3.txt os.remove("file3.txt")
Creating the new directory - mkdir()
The mkdir() method is used to create the directories in the current working directory
Syntax: os.mkdir("directory-name")
Ex: import os;
#creating a new directory with the name new
os.mkdir("dirnew")
Changing the current working directory-chdir()
The chdir() method is used to change the current working directory to a specified directory
Q. File Execution
Python is a well-known high-level programming language. The Python script is a file containing
Python-written code. The file containing Python script has the extension py' or can also have the
extension pyw if it is being run on a Windows 10 machine or various techniques for executing a
Python script...
Running Python Scripts in Terminal:
1. Open a Terminal: If you're using a Linux or macOS system, you can usually find a terminal
application in your applications or through a system search. Commonly used open terminal python
include the GNOME Terminal, Konsole, and macOS's Terminal.
On Windows, you can use the Command Prompt or PowerShell. You can find the Command
Prompt by searching for "cmd" or "Command Prompt" in the Start menu, while PowerShell can be
found similarly.
2. Navigate to Your Script's Directory: Use the ed (change directory) command to navigate to the
directory where your Python script is located. For example, if your script is in a folder called
"my_python_scripts," you can navigate to it like this while learning how to run a python script in
terminal
cd path/to/my_python_scripts
3. Run the Python Script: To run a Python script, use the Python command, followed by the name of
your script. For instance: python my_script.py
To run a python script in Linux
If you're using Linux, running a Python script in Python 3 is quite straightforward. First, open your
terminal. Navigate to the directory where your script is located using the ed command.
For example:
ed path/to/your/script
Once you're in the correct directory, type the following command: python3 script_name.py script
name.py can be replaced with your file name.
Running Python Scripts as Executables
You can also run Python scripts as executables on Unix-like systems. First, add the shebang line at the
top of your script:
#!/usr/bin/env python3
Then, with the following command, you can make the script executable: chmod +x script_name.py
Now simply, type the below command to run your script directly.
/script_name.py
How to Run Python on Windows
On Windows, Command Prompt can be used to run the Python scripts with ease. Just open Command
Prompt and use the cd command to go to your script's directory:
ed path\to\your script
Then, run your script with: python script_name.py
Ensure Python is added to your system PATH to run it from any directory Running Python command
line argument
Sometimes, you'll need to run scripts with command line arguments. Here's how you can do it. In
your script, you can handle arguments using the sys module:
import sys
print(sys.argv)
To run the script with arguments, use the terminal :python script_name.py arg1 arg2 Replace argl and
arg2 with your actual arguments.
Q. Exceptions in Python
In Python, an exception is an event that occurs during the execution of a program and disrupts the normal
flow of the program. It represents an error or an exception condition that the program encounters and
cannot handle by itself.
When an exception occurs, it is "raised" or "thrown" by the Python interpreter The exception then
propagates up the call stack, searching for an exception handler that can catch and handle the
exception. If no suitable exception handler is found, the program terminates, and an error message is
displayed.
Example:
n=10
try:
res=n/0
print(res)
except ZeroDivisionError:
print("cant divide by zero")
In this example, the code within the try block raises a ZeroDivisionError exception when attempting to
divide by zero. The exception is caught by the except block, and the specified error message is printed,
allowing the program to continue execution instead of abruptly terminating.
Different Types of Exceptions in Python:
1. SyntaxError: When the interpreter comes across a syntactic problem in the code, such as a misspelled
word, a missing colon, or an unbalanced pair of parentheses, this exception is raised.
2. TypeError: When an operation or function is done to an object of the incorrect type, such as
by adding a string to an integer, an exception is thrown.
3. NameError: When a variable or function name cannot be found in the current scope, the exception
NameError is thrown.
4. IndexError: This exception is thrown when a list, tuple, or other sequence type's index is outside of
bounds.
5. KeyError: When a key cannot be found in a dictionary, this exception is thrown.
6. ValueError: This exception is thrown when an invalid argument or input is passed to a function or
method. An example would be trying to convert a string to an integer when the string does not
represent a valid integer.
7. AttributeError: When an attribute or method is not present on an object, such as when attempting to
access a non-existent attribute of a class instance, the exception AttributeError is thrown.
8. IOError: This exception is thrown if an input/output error occurs during an I/O operation, such as
reading or writing to a file.
9. ZeroDivisionError: This exception is thrown whenever a division by zero is attempted.
10. ImportError: This exception is thrown whenever a module cannot be loaded or found by an
import statement.
Q. Types of Exceptions
There are two types of exceptions in Python.
1. Built-in Exceptions
2. User-Defined Exceptions
Built-in Python Exceptions
Built-in exceptions are the standard exceptions defined in Python. These exceptions are raised where the
program encounters an illegal operation like semantic errors.
These built-in exceptions are generated either by the interpreter or the built-in functions of Python
The interpreter returns a string indicating the error code and the related information whenever an
exception is raised.
Here is the list of default Python exceptions with descriptions:
1. Assertion Error: raised when the assert statement fails.
2. EOFError: raised when the input() function meets the end-of-file condition.
3. AttributeError: raised when the attribute assignment or reference fails.
4. TabError: raised when the indentations consist of inconsistent tabs or spaces.
5. ImportError: raised when importing the module fails.
6. IndexError: occurs when the index of a sequence is out of range
7. RuntimeError: occurs when an error does not fall into any category.
8. NameError: raised when a variable is not found in the local or global scope.
9. MemoryError: raised when programs run out of memory.
10. ValueError: occurs when the operation or function receives an argument with the
right type but the wrong value.
11. ZeroDivision Error: raised when you divide a value or variable with zero.
12. SyntaxError: raised by the parser when the Python syntax is wrong.
13. IndentationError: occurs when there is a wrong indentation.
14. SystemError: raised when the interpreter detects an internal error.
Ex: FileNotFoundError
This exception is raised when a file or directory is requested, but the specified file or directory
does not exist. When a file that should be read, accessed, or retrieved doesn't exist, Python throws
the FileNotFoundError exception.
#Python program for FileNotFoundError try:
with open(" myfile.txt") as f:
contents =f.read()
except FileNotFoundError as e:
print(" A file not found error occurred: ", e)
Output :A file not found error occurred. [Errno 2] No such file or directory: myfile.txt'
User-Defined Exceptions:
A user defined exception in Python is an exception that is constructed by the user or programmer to
represent a specific error condition or exceptional situation in a program. It is also known as a
custom exception.
Python offers a wide range of standard built-in exceptions to handle common errors. Sometimes,
there may be situations where built-in exceptions are not sufficient to handle the different exceptions
that occur in the application program.
In this situation, users may need to define their own custom exceptions to handle specific errors or to
add more context to error handling.
For example, if the user wants to withdraw greater than its balance from the ATM machine, it leads
to the exception. Any standard inbuilt exception cannot handle such a kind of exception.
In this case, the user can define its own custom exception that will occur when someone will want
to attempt to withdraw the amount greater than its balance. The exception handler in this case may
display a customize message that you cannot withdraw money greater than the account balance.
Try and Except Statement-Catching Exceptions: Try and except statements are used to catch and handle
exceptions in Python. Statements that can raise exceptions are wrapped inside the try block and the
statements that handle the exception are written inside except block.
Example:
a=[1,2, 3]
try:
print ("Second element = ", (a[1]))
print ("Fourth element = %d" %(a[3]))
except:
print ("An error occurred")
Output: Second element = 2
error occurred
In the above example, the statements that can cause the error are placed inside the try statement (second
print statement in our case). The second print statement tries to access the fourth element of the list which
is not there and this throws an exception. This exception is then caught by the except statement.
Catching Specific Exception
A try statement can have more than one except clause, to specify handlers for different exceptions. Please
note that at most one handler will be executed. For example, we can add IndexError in the above code.
Syntax:
try:
#statement(s) except IndexError:
#statement(s) except ValueError:
# statement(s)
Example:
def fun(a):
if a <4 :
b=a/(a-3)
print("Value of b =", b)
try:
fun(3)
fun(5)
except ZeroDivisionError:
print("ZeroDivisionError Occurred and Handled")
except NameError:
print("NameError Occurred and Handled")
#Output: ZeroDivisionError Occurred and Handled
Try with Else Clause: In Python, you can also use the else clause on the try-except block which must be
present after all the except clauses. The code enters the else block only if the try clause does not raise an
exception.
Example:
def AbyB(a, b):
try:
c=((a+b)/(a-b))
except ZeroDivisionError:
print ("a/b result in 0")
else:
print (c)
AbyB(2.0, 3.0)
AbyB(3.0, 3.0)
Q. Exceptions as Strings
Before Python 1.5, exceptions were represented as strings. While this approach was simple, a
lacked the structure and flexibility of classes.
In Python 1.5, standard exceptions were transitioned to classes, offering better organization and
extensibility. Although string exceptions are no longer recommended, understanding their usage
is helpful for working with older code or recognizing them when encountered.
String exceptions were raised using the raise statement followed by a string literal or variable
containing the error message.
Example:
try:
#Code that might raise an exception x=10/0
except "division by zero" :
print("Caught a string exception: division by zero")
String exceptions could be caught using the except clause with the string literal matching the
exception.
Example:
try:
#Code that might raise an exception raise "File not found"
except "File not found":
print("Caught a string exception: File not found")
It's important to note that this approach is outdated and using class-based exceptions is now the
standard practice in Python.
Q. Raising Exceptions
The raise keyword is used to raise an exception. You can define what kind of error to raise, and the
text to print to the user.except is a keyword (case-sensitive) in python, it is used to raise an
Exception/Error with a customized message and stops the execution of the programs.
It is very useful when you want to work with the input validations. For example if you are working
with the positive numbers and someone inputs a negative number, in this case, we can raise an
error and stop the program's execution.
Syntax:
if test_condition:
raise Exception(Message) Ex:
string = "Hello"
if string =="Hello" or string== "Hi" or string =="Bye":
Example:
def divide(a, b):
if b==0:
raise ValueError("Cannot divide by zero") return a/b
try:
result divide(10, 0) except ValueError as e:
print(e)
self.age = age
self.message== message
super(). init (self.message)
def set_age(age):
if age 18 or age > 100:
raise InvalidAgeError(age)
print(f"Age is set to {age}")
try:
set_age(150)
except InvalidAgeError as e:
2. assert statement can also have a condition and a optional error message. If the condition is not
satisfied assert stops the program and gives AssertionError along with the error message.
In Python versions 1.5 and later, the standard exceptions are Python classes, and a few new standard exceptions
have been added. Python supports various built-in exceptions, the commonly used exceptions are
NameError: It occurs when a name is not found.i.e attempt to access an undeclared variable
Example:
a=5
c=a+b
print("Sum =",c)
Output:
Traceback (most recent call last):
File "expdemo.py", line 2, in c=a+b
NameError: name 'b' is not defined
class SpecificError(CustomError):
"""Specific exception type"""
def init (self, message):
self.message= message
super(). _init (self.message)
Initialize the Exception (Optional): Implement the" init "method to initialize any attributes or
provide custom error messages. This allows you to pass specific information about the error when
raising the exception.
class ValueError(Exception):
def init (self, message="Invalid value"):
self.message =message
27
super(). init (self.message)
Raise the Exception: Once you have defined a custom exception, you can raise it in your code to
signify specific error conditions. Raising user-defined exceptions involves using the raise
statement, which can be done with or without custom messages and attributes.
Syntax :
raise Exception Type (args)
Example:
def process data(value):
if not isinstance(value, int):
raise ValueError("Input must be an integer")
return value *2
Handle the Exception: Handling user-defined exceptions in Python refers to using "try-except"
blocks to catch and respond to the specific conditions that your custom exceptions represent. This
allows your program to handle errors gracefully and continue running or to take specific actions
based on the type of exception raised.
Example:
try:
result =process_data("hello")
except ValueError as e:
print(f"Error: (e}")
else:
print(f"Result: (result)")
Example:
class InvalidAgeError(Exception):
def init (self, age, message "Age must be between 18 and 100"):
self.age = age
self.message= message
super(). init (self.message) def
str (self):
return f" {self.message}provided age:{self.age}"
def set_age(age):
if age 18 or age > 100:
raise InvalidAgeError(age) print(f"Age
is set to {age}")
28
try:
set _age(150)
except InvalidAgeError as e:
print(f"Invalid age: (c.age) (e.message)")
Output Invalid age: 150. Age must be between 18 and 100
Q. Exceptions and the sys Module
The sys module in Python contains several methods and variables for manipulating various aspects
of the Python runtime environment. It helps you work with the interpreter since it gives you access
to variables and functions that work closely with it.
Important Variables In The SYS Module
Version: It helps you understand the version of Python being in use.
Example:
import sys
sys.version
Output :’3.9.6 (tags/v3.9.6:db3ff76, Jun 28 2021, 15:26:21)
sys.argv:
In Python, this includes a list of arguments (command prompt) supplied to the script. If you write
len(sys.argv), you'll get a count of how many arguments there are. sys.argv is used by people who
work with command-line arguments. The name of the script is referred to as sys.argv[0]
Example:
import sys
print(sys.argv[0])
print('Number of arguments present=', len(sys.argv))
print('Total argument list:', str(sys.argv))
Output: sys.py
Number of arguments present = 1 Total
argument list: ['sys.py']
sys.path:
This function displays the current system's python path. It's an environmental variable that
contains the search path for all of the python modules.
Example:
import sys
sys.path
Output: [", "C:\\Python39\\Lib\\idlelib']
sys.maxsize: This maxsize function returns the variable's greatest integer
29
Example:
import sys
sys.maxsize
Output: 9223372036854775807
Important Functions in the SYS Module:
1. sys.exit(): The program will exit the python console or the command prompt. It is usually
used to exit the application if an exception is thrown securely.
Example:
import sys
def is_even(list):
if any (i%21 for i in list):
print("ERROR. Odd one is present in the even list! ")
sys.exit()
else:
print("Pure Even List")
list= [2,4,5,6,8,10]
is_even(list)
is_ even(list)
Output: ERROR: Odd one is present in the even list!
2. sys.setdefaultencoding(): This method allows you to adjust the default encoding for strings
in the Python environment.
Example:
import sys
sys.setdefaultencoding('UTF8')
3. sys.getsizeof(): After using this function, the size of an object in bytes is returned. Any object
can be used as an object.
Example:
import sys i=3
print(sys.getsizeof(i))
Output: 28
1. stdin: This stdin can be used to take input from the command line directly. This stdin method
is used for taking standard input. It uses the input() function internally. It also adds a \n that is
a new line at the end of each sentence. Let's understand this with an example given below
Example:
import sys
for words in sys.stdin:
if 'quit' words.rstrip():
break
print(f'Input (words)")
print("Exit!!")
Output:
Hello
Input: Hello
Bye
Input: Bye
quit
Exit
2. stdout: The interpreter's standard output stream in Python is analogous to this built-in file
object. The stdout command sends output to the screen console. The output that comes out
using the print statement, an expression statement, or even a prompt direct for input, might
take many different forms. Streams are set to text mode by default. Whenever a print function
is used in the code, it is written first to sys.stdout, then to the screen. Let's understand this in a
better way from the example that is given below:
Example:
import sys
sys.stdout.write('Learn_To_Code')
Output: Learn_ To_Code
31
Modules: According to the formal definition of Python modules, they are a Python file containing
statements, definitions, Python code, classes, functions, and variables. They are the files with the
py extension. A Python module can also include runnable code.
When we group related code into a module, it makes it easier to understand and use. Also, the
code is more logically organized. A common real-life example is a music store with many sections
containing different types of songs and music.
Features of Modules:
Allows code reusability
Provides flexibility in organizing code logically and segments a larger problem into small
manageable files.
Create a python Module
You can create a Python module by writing the desired code and saving the file using the py
extension.
Example: Creating a module named "mymath" #mymath.py
def add(a, b):
return a + b """Return the sum of two numbers."""
def subtract(a, b):
return a - b Return the difference between two numbers.""
Types of Modules in Python
There are two types of Python modules:
1. In-built modules in Python
2. User-Defined Modules in Python
1. In-built Modules in Python
The Python built-in modules come with a Python standard library, offering a range of
functionalities. So, you don't need to install these modules separately, as they are available in
Python by default. There are several in-built Python modules, such as sys, math, os, random, etc.
Built-In modules like:
math sys OS
random and many more.
2. User-defined Modules in Python
Users create these modules to make their code more organized, modular, and reusable. These are
defined in a different py file, so you must import and use them in your Python scripts.
There are a few other types of Python modules, such as package modules, third-party modules,
32
and extension modules.
Variables in Python Modules
We have already discussed that modules contain functions and classes. But apart from functions
and classes, modules in Python can also contain variables in them. Variables like tuples, lists,
dictionaries, objects, etc.
Example:
#This is variables module
## this is a function in module def factorial(n):
if n1||n=0:
return 1
else:
return n factorial(n-1)
## this is dictionary in module
power = { 1:1, 2:4, 3:9, 4:16, 5:25.}
1 ##This is a list in the module alphabets [a,b,c,d,e,f,g,h]
Q. Namespaces
In Python, a namespace is a collection of names, which can be variables, functions, classes, or
modules. Namespaces provide a way to organize and manage the names in a Python program,
ensuring that each name is unique and can be accessed correctly.
Types of Namespaces in Python
Global Namespace: This is the top-level namespace that contains all the names defined at the
module level.
Local Namespace: This is the namespace that contains the names defined within a function or a
class.
Built-in Namespace: This is the namespace that contains the built-in functions, types, and
constants provided by the Python interpreter.
Accessing Namespaces
In Python, you can access the names in a namespace using the dot notation. For example, to access
a variable x in the global namespace, you would use x, while to access a function my_function in a
module my_module, you would use my_module.my_function.
Example of accessing namespaces
x=10
def my_function():
33
y=20
print(x)
print(y)
my_function()
Namespace Hierarchy: Python's namespace hierarchy follows a specific structure, where the
built-in namespace is the top-level namespace, followed by the global namespace, and then the
local namespaces. This hierarchy determines how names are resolved when they are referenced in
a Python program.
By understanding the concept of namespaces and how they work in Python, you can write more
organized and maintainable code, and avoid naming conflicts that can lead to bugs and errors.
Working with Namespaces in Python
In Python, you can manipulate namespaces using various built-in functions and keywords, such
as:
a) globals(): Returns a dictionary of the names in the global namespace
b) locals(): Returns a dictionary of the names in the current local namespace.
c) dir(): Returns a list of names in the namespace of an object.
d) Import statement: Brings names from a module into the current namespace.
e) As keyword: Allows you to assign a different name to an imported object.
f) name_variable: Provides information about the current namespace
Example:
## Example of namespace manipulation
import math as m
print(globals()) ### Access global namespace
print(locals()) ## Access local namespace .
print(dir(m)) ## Access namespace of the math module
print(__name__) ## Access the current namespace name
Q. Importing Modules
A file is considered as a module in python. To use the module, you have to import it using the
import keyword. The function or variables present inside the file can be used in another file by
importing the module. This functionality is available in other languages, like typescript,
JavaScript, java, ruby, etc.
34
Importing a Module in Python
The most common way to use a module is by importing it with the import statement. This allows
access to all the functions and variables defined in the module.
Example:
import math as pie
print("The value of pi is:", pie.pi)
Output: The value of pi is: 3.141592653589793
Importing Specific Functions
Instead of importing the entire module, we can import only the functions or variables we need
using the “from” keyword. This makes the code cleaner and avoids unnecessary imports.
Example:
from math import pi
print(pi)
Output: 3.141592653589793
Importing Built-in Modules
Python provides many built-in modules that can be imported directly without installation. These
modules offer ready-to-use functions for various tasks, such as random number generation, math
operations and file handling.
Example:
import random
#Generate a random number between 1 and 10
res =random.randint(1, 10)
print("Random Number:", res)
Output: Random Number:7
Importing Modules with Aliases
To make code more readable and concise, we can assign an alias to a module using the as
keyword. This is especially useful when working with long module names.
Example:
import math as m
#Use the alias to call a function result
result=m.sqrt(25)
print("Square root of 25:", result)
Importing Everything from a Module (*)
Instead of importing specific functions, we can import all functions and variables from a module
35
using the symbol. This allows direct access to all module contents without prefixing them with the
module name.
Example:
from math import *
print(pi) #Accessing the constant 'pi'
print(factorial(6)) # Using the factorial function
Output: 3.141592653589793
720
Advantages:
It becomes easy to trace back the modules for code check.
Easy to use and very straight forward.
If the project is moved to a different path, still the imports will remain the same
36
Example:
os.rmdir("d:\\temp")
listdir(): The os module has listdir() function which returns list of all files in specified directory.
os.listdir("c:\\Users")
['acer', 'All Users', 'Default', 'Default User', 'desktop.ini', 'Public']
37
Example:
import time
print(time.time())
Output 1544348359.1183174
localtime(): This function translates time in ticks in a time tuple notation.
Example:
import time
tk = time.time()
time.localtime(tk)
print(tk)
Output :
asctime(): This functions readable format of local time
Example:
import time
tk = time.time() # get ticks (seconds since epoch)
tp = time.localtime(tk) # convert ticks to struct_time (local time)
print(time.asctime(tp))
Output: Mon Sep 8 10:48:03 2025
ctime(): This function returns string representation of system's current time
Example:
import time
print(time.ctime())
Output: Mon Sep 8 10:50:43 2025
sleep(): This function halts current program execution for a specified duration in seconds.
Example:
import time
time.sleep(10) # pause for 10 seconds
print(time.ctime())
Output 'Sun Dec 9 15:19:34 2018'
sys module:
This module provides functions and variables used to manipulate different parts of the Python runtime
environment.
sys.setdefaultencoding(): This method allows you to adjust the default encoding for strings in the
Python environment.
Example:
import sys
sys.setdefaultencoding("UTF8")
38
sys.getsizeof(): After using this function, the size of an object in bytes is returned. Any object can be used as
an object.
Example:
import sys
i=3
print(sys.getsizeof(i))
Output: 28
Q. Packages
A python package is a collection of modules. Modules that are related to each other are mainly put in the
same package. When a module from an external package is required in a program, that package can be
imported and its modules can be put to use.
A package is a directory of Python modules that contains an additional init py file, which distinguishes a
package from a directory that is supposed to contain multiple Python scripts. Packages can be nested to
multiple depths if each corresponding directory contains its own_ init_.py file.
Creating a Package in Python: Creating packages in Python allows you to organize your code into reusable
and manageable modules. Here's a brief overview of how to create packages:
Create a Directory: Start by creating a directory (folder) for your package. This directory will serve as the
root of your package structure.
Add Modules: Within the package directory, you can add Python files (modules) containing your code. Each
module should represent a distinct functionality or component of your package.
Init File: Include an init py file in the package directory. This file can be empty or can contain an
initialization code for your package. It signals to Python that the directory should be treated as a package.
39