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

Unit 3 Python Part1

Uploaded by

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

Unit 3 Python Part1

Uploaded by

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

Modular Programming:- Modular programming is the practice of segmenting a single,

complicated coding task into multiple, simpler, easier-to-manage sub-tasks. We call these
subtasks modules. Therefore, we can build a bigger program by assembling different
modules that act like building blocks.

MODULES IN PYTHON
A Python module is a file containing Python definitions and statements. 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.
A module is a file containing Python code, definitions of functions, statements, or classes.
An example_module.py file is a module we will create and whose name is example_module.
We employ modules to divide complicated programs into smaller, more understandable
pieces. Modules also allow for the reuse of code
Rather than duplicating their definitions into several applications, we may define our most
frequently used functions in a separate module and then import the complete module.

CREATING PYTHON MODULE


To create a Python module, write the desired code and save that in a file with .py extension.
Let’s create a simple calc.py in which we define two functions, one add and another subtract.
# A simple module, calc.py
def add(x, y):
return (x+y)

def subtract(x, y):


return (x-y)
IMPORT MODULE IN PYTHON
We can import the functions, and classes defined in a module to another module using the
import statement in some other Python source file.
When the interpreter encounters an import statement, it imports the module if the module is
present in the search path.
Note: A search path is a list of directories that the interpreter searches for importing a
module.
# importing module calc.py
import calc

print(calc.add(10, 2))

PYTHON IMPORT FROM MODULE


Python’s from statement lets you import specific attributes from a module without importing
the module as a whole.
# importing sqrt() and factorial from the
# module math
from math import sqrt, factorial

# if we simply do "import math", then


# math.sqrt(16) and math.factorial()
# are required.
print(sqrt(16))
print(factorial(6))

Import all Names


The * symbol used with the import statement is used to import all the names from a module
to a current namespace.
Syntax:
from module_name import *
What does import * do in Python?
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.
# module math
from math import *

# if we simply do "import math", then


# math.sqrt(16) and math.factorial()
# are required.
print(sqrt(16))
print(factorial(6))

LOCATING PYTHON MODULES


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 –
 First, it searches for the module in the current directory.
 If the module isn’t found in the current directory, Python then searches each directory
in the shell variable PYTHONPATH. The PYTHONPATH is an environment
variable, consisting of a list of directories.
 If that also fails python checks the installation-dependent list of directories configured
at the time Python is installed.
# importing sys module
import sys

# importing sys.path
print(sys.path)

RENAMING THE PYTHON MODULE


We can rename the module while importing it using the keyword.
Syntax: Import Module_name as Alias_name
# module math
import math as mt

# if we simply do "import math", then


# math.sqrt(16) and math.factorial()
# are required.
print(mt.sqrt(16))
print(mt.factorial(6))

What is a Math Module in Python?


Math Module is an in-built Python library made to simplify mathematical tasks in Python.
It consists of various mathematical constants and functions that can be used after importing
the math module.
Constants in Math Module
The Python math module provides various values of various constants like pi, and tau. We
can easily write their values with these constants. The constants provided by the math
module are :
 Euler’s Number
 Pi
 Tau
 Infinity
 Not a Number (NaN)
1. Euler’s Number
The math.e constant returns the Euler’s number: 2.71828182846.
2. Pi
You all must be familiar with pi. The pi is depicted as either 22/7 or 3.14. math.pi provides a
more precise value for the pi.
3. tau
Tau is defined as the ratio of the circumference to the radius of a circle. The math.tau
constant returns the value tau: 6.283185307179586.
4. Infinity
Infinity basically means something which is never-ending or boundless from both directions
i.e. negative and positive. It cannot be depicted by a number. The Python math.inf constant
returns of positive infinity. For negative infinity, use -math.inf.
5. NaN Values
The Python math.nan constant returns a floating-point nan (Not a Number) value. This value
is not a legal number. The nan constant is equivalent to float(“nan”).
import math
print (math.e)
print (math.pi)
print (math.tau)
print (math.inf)
print (-math.inf)
print (math.nan)

What is a OS Module in Python?


The OS module in Python provides functions for interacting with the operating system. OS
comes under Python’s standard utility modules. This module provides a portable way of
using operating system-dependent functionality.
The *os* and *os.path* modules include many functions to interact with the file system.
Python-OS-Module Functions
Here we will discuss some important functions of the Python os module :
 Handling the Current Working Directory
 Creating a Directory
 Listing out Files and Directories with Python
 Deleting Directory or Files using Python
Handling the Current Working Directory
Consider Current Working Directory(CWD) as a folder, where Python is operating.
Whenever the files are called only by their name, Python assumes that it starts in the CWD
which means that name-only reference will be successful only if the file is in the Python’s
CWD.
Getting the Current working directory
import os
cwd = os.getcwd()
print("Current working directory:", cwd)
Changing the Current working directory
import os
def current_path():
print("Current working directory before")
print(os.getcwd())
print()
current_path()
os.chdir('../')
current_path()

Creating a Directory
There are different methods available in the OS module for creating a directory. These are –
 os.mkdir(‘path’)
 os.makedirs(‘path’)
Listing out Files and Directories with Python
There is os.listdir() method in Python is used to get the list of all files and directories in the
specified directory. If we don’t specify any directory, then the list of files and directories in
the current working directory will be returned.
Deleting Directory or Files using Python
OS module provides different methods for removing directories and files in Python. These
are –
Using os.remove(‘path’) (delete file path)
Using os.rmdir(‘path’) (delete folder)

What is a SYS Module in Python?


The sys module in Python provides various functions and variables that are used to
manipulate different parts of the Python runtime environment. It allows operating on the
interpreter as it provides access to the variables and functions that interact strongly with the
interpreter.
import sys
print(sys.version) #returns python interpreter version
Input and Output using Python Sys
The sys modules provide variables for better control over input or output. We can even
redirect the input and output to other devices. This can be done using three variables –
stdin
import sys
for line in sys.stdin:
if 'q' == line.rstrip():
break
print(f'Input : {line}')

print("Exit")
stdout
import sys
sys.stdout.write('Geeks')

stderr
try:

x = int("not_a_number")

except ValueError as e:

sys.stderr.write(f"Error: {str(e)}\n")

PYTHON JSON
Python JSON JavaScript Object Notation is a format for structuring data. It is mainly used
for storing and transferring data between the browser and the server. Python too supports
JSON with a built-in package called JSON. This package provides all the necessary tools for
working with JSON Objects including parsing, serializing, deserializing, and many more.
Convert from JSON to Python object
import json
# JSON string
employee = '{"id":"09", "name": "Nitin", "department":"Finance"}'
print("This is JSON", type(employee))
print("\nNow convert from JSON to Python")
# Convert string to Python dict
employee_dict = json.loads(employee)
print("Converted to Python", type(employee_dict))
print(employee_dict)

Convert from Python object to JSON


import json
# JSON string
employee_dict = {'id': '09', 'name': 'Nitin', 'department': 'Finance'}
print("This is Python", type(employee_dict))
print("\nNow Convert from Python to JSON")
# Convert Python dict to JSON
json_object = json.dumps(employee_dict, indent=4)
print("Converted to JSON", type(json_object))
print(json_object)

You might also like