0% found this document useful (0 votes)
2 views

Python

This document provides an overview of Python, highlighting its features such as being free and open-source, easy to read and write, and supporting both object-oriented and procedural programming. It also covers Python's installation, basic syntax, data types, operators, and control structures like conditional statements and loops. Additionally, it explains the concept of variable types and casting in Python.
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

This document provides an overview of Python, highlighting its features such as being free and open-source, easy to read and write, and supporting both object-oriented and procedural programming. It also covers Python's installation, basic syntax, data types, operators, and control structures like conditional statements and loops. Additionally, it explains the concept of variable types and casting in Python.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 131

MODULE 1

Features in Python

Python is a dynamic, high-level, free open source, and interpreted programming language. It
supports object-oriented programming as well as procedural-oriented programming. In
Python, we don’t need to declare the type of variable because it is a dynamically typed
language. For example, x = 10 Here, x can be anything such as String, int, etc. In this article
we will see what characteristics describe the python programming language
1. Free and Open Source
Python language is freely available at the official website and you can download it from the
given download link below click on the Download Python keyword. Download Python Since
it is open-source, this means that source code is also available to the public. So you can
download it, use it as well as share it.

2. Easy to code
Python is a high-level programming language. Python is very easy to learn the language as
compared to other languages like C, C#, Javascript, Java, etc. It is very easy to code in the
Python language and anybody can learn Python basics in a few hours or days. It is also a
developer-friendly language.

3. Easy to Read
As you will see, learning Python is quite simple. As was already established, Python’s syntax
is really straightforward. The code block is defined by the indentations rather than by
semicolons or brackets.

4. Object-Oriented Language
One of the key features of Python is Object-Oriented programming. Python supports object-
oriented language and concepts of classes, object encapsulation, etc.

5. GUI Programming Support


Graphical User interfaces can be made using a module such as PyQt5, PyQt4, wxPython, or
Tk in Python. PyQt5 is the most popular option for creating graphical apps with Python.

6. High-Level Language
Python is a high-level language. When we write programs in Python, we do not need to
remember the system architecture, nor do we need to manage the memory.

7. Large Community Support


Python has gained popularity over the years. Our questions are constantly answered by the
enormous StackOverflow community. These websites have already provided answers to
many questions about Python, so Python users can consult them as needed.
8. Easy to Debug
Excellent information for mistake tracing. You will be able to quickly identify and correct the
majority of your program’s issues once you understand how to interpret Python’s error
traces. Simply by glancing at the code, you can determine what it is designed to perform.

9. Python is a Portable language


Python language is also a portable language. For example, if we have Python code for
Windows and if we want to run this code on other platforms such as Linux, Unix, and Mac
then we do not need to change it, we can run this code on any platform.

10. Python is an Integrated language


Python is also an Integrated language because we can easily integrate Python with other
languages like C, C++, etc.

11. Interpreted Language:


Python is an Interpreted Language because Python code is executed line by line at a time.
like other languages C, C++, Java, etc. there is no need to compile Python code this makes it
easier to debug our code. The source code of Python is converted into an immediate form
called bytecode.

12. Large Standard Library


Python has a large standard library that provides a rich set of modules and functions so you
do not have to write your own code for every single thing.There are many libraries present
in Python such as regular expressions, unit-testing, web browsers, etc.

13. Dynamically Typed Language

Python is a dynamically-typed language. That means the type (for example- int, double,
long, etc.) for a variable is decided at run time not in advance because of this feature we
don’t need to specify the type of variable.

14. Frontend and backend development

With a new project py script, you can run and write Python codes in HTML with the help of
some simple tags <py-script>, <py-env>, etc. This will help you do frontend development
work in Python like javascript. Backend is the strong forte of Python it’s extensively used for
this work cause of its frameworks like Django and Flask.
15. Allocating Memory Dynamically

In Python, the variable data type does not need to be specified. The memory is
automatically allocated to a variable at runtime when it is given a value. Developers do not
need to write int y = 18 if the integer value 15 is set to y. You may just type y=18.

INSTALLATION

Python is a powerful, general-purpose programming language that is widely used for web
development, data science, artificial intelligence, and scientific computing. If you're new to
programming and want to get started with Python, you'll need to install it on your
computer.

BASIC SYNTAX

The Python syntax defines a set of rules that are used to create a Python Program. The
Python Programming Language Syntax has many similarities to Perl, C, and Java
Programming Languages. However, there are some definite differences between the
languages.

print("Hello, World!")
Hello, World!

INDENTATION

Indentation refers to the spaces at the beginning of a code line.

Where in other programming languages the indentation in code is for readability only, the
indentation in Python is very important.

Python uses indentation to indicate a block of code.

Eg:
if 5 > 2:
print("Five is greater than two!")

PYTHON VARIABLES

Variables are containers for storing data values.

Creating Variables:

Python has no command for declaring a variable.

A variable is created the moment you first assign a value to it.


Eg:
x=5
y = "John"
print(x)
print(y)

Variables do not need to be declared with any particular type, and can even change type
after they have been set.

Eg:

x=4 x = "Sally" print(x)

casting

if you want to specify the data type of a variable, this can be done with casting.

eg:

x = str(3)
y = int(3) z = float(3)

Get the Type

You can get the data type of a variable with the type() function.

Eg:
x=5
y = "John"
print(type(x))
print(type(y))

Single or Double Quotes

String variables can be declared either by using single or double quotes:

Eg:X = "John"
x = 'John'

Case-Sensitive

Variable names are case-sensitive.

Eg:

This will create two variables:


a=4
A = "Sally"

DATA TYPES
Built-in Data Types: Variables can store data of different types, and different types can do
different things.Python has the following data types built-in by default, in these categories:

Text Type: str

Numeric Types: int, float, complex

Sequence Types: list, tuple, range

Mapping Type: dict

Set Types: set, frozenset

Boolean Type: bool

Binary Types: bytes, bytearray, memoryview

None Type: NoneType

Getting the Data Type

You can get the data type of any object by using the type() function:

EG: Print the data type of the variable x:x = 5


print(type(x))

Setting the Data Type

In Python, the data type is set when you assign a value to a variable:

Example Data Type


x = "Hello World" str

x = 20 int

x = 20.5 float

x = 1j complex

x = ["apple", "banana", "cherry"] list

x = ("apple", "banana", "cherry") tuple

x = range(6) range

x = {"name" : "John", "age" : 36} dict

x = {"apple", "banana", "cherry"} set

x = frozenset({"apple", "banana", "cherry"}) frozenset

x = True bool
x = b"Hello" bytes

x = bytearray(5) bytearray

x = memoryview(bytes(5)) memoryview

x = None NoneType

Setting the Specific Data Type

If you want to specify the data type, you can use the following constructor functions:

Example Data Type

x = str("Hello World") str

x = int(20) int

x = float(20.5) float

x = complex(1j) complex
x = list(("apple", "banana", "cherry")) list

x = tuple(("apple", "banana", "cherry")) tuple

x = range(6) range

x = dict(name="John", age=36) dict

x = set(("apple", "banana", "cherry")) set

x = frozenset(("apple", "banana", "cherry")) frozenset

x = bool(5) bool

x = bytes(5) bytes

x = bytearray(5) bytearray

x = memoryview(bytes(5)) memoryview

operators est OPEOPERATORS

Operators are used to perform operations on variables and values.In the example below, we
use the + operator to add together two values:

Eg: print(10 + 5)
 Arithmetic operators
 Assignment operators
 Comparison operators
 Logical operators
 Identity operators
 Membership operators
 Bitwise operators

1.Python Arithmetic Operators

Arithmetic operators are used with numeric values to perform common mathematical
operations:

Operator Name Example

+ Addition x+y

- Subtraction x-y

* Multiplication x*y

/ Division x/y

% Modulus x%y

** Exponentiation x ** y

// Floor division x // y

2.Python Assignment Operators

Assignment operators are used to assign values to variables:

Operator Example Same As

= x=5 x=5

+= x += 3 x=x+3

-= x -= 3 x=x-3

*= x *= 3 x=x*3
/= x /= 3 x=x/3

%= x %= 3 x=x%3

//= x //= 3 x = x // 3

**= x **= 3 x = x ** 3

&= x &= 3 x=x&3

|= x |= 3 x=x|3

^= x ^= 3 x=x^3

>>= x >>= 3 x = x >> 3

<<= x <<= 3 x = x << 3

3.Python Comparison Operators

Comparison operators are used to compare two values:

Operator Name Example

== Equal x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y

4.Python Logical Operators

Logical operators are used to combine conditional statements:

Operator Description Example

and Returns True if both statements are true x < 5 and x < 10
or Returns True if one of the statements is true x < 5 or x < 4

not Reverse the result, returns False if the result is true not (x < 5 and x < 10)

5.Python Identity Operators

Identity operators are used to compare the objects, not if they are equal, but if they are
actually the same object, with the same memory location:

Operator Description Example

is Returns True if both variables are the same object x is y

is not Returns True if both variables are not the same object x is not y

6.Python Membership Operators

Membership operators are used to test if a sequence is presented in an object:

Operator Description Example

in Returns True if a sequence with the specified value is present in the object x in y

not in Returns True if a sequence with the specified value is not present in the object x
not in y

7.Python Bitwise Operators

Bitwise operators are used to compare (binary) numbers:

Operator Name Description Example

& AND Sets each bit to 1 if both bits are 1 x&y

| OR Sets each bit to 1 if one of two bits is 1 x|y


^ XOR Sets each bit to 1 if only one of two bits is 1 x^y

~ NOT Inverts all the bits ~x

<< Zero fill left shift Shift left by pushing zeros in from the right and let the
leftmost bits fall off x << 2

>> Signed right shift Shift right by pushing copies of the leftmost bit in from the
left, and let the rightmost bits fall off x >> 2

8.Operator Precedence

Operator precedence describes the order in which operations are performed.

Example:Parentheses has the highest precedence, meaning that expressions inside


parentheses must be evaluated first: print((6 + 3) - (6 + 3))

Example: Multiplication * has higher precedence than addition +, and therefor


multiplications are evaluated before additions: print(100 + 5 * 3)

The precedence order is described in the table below, starting with the highest precedence
at the top:

Operator Description

() Parentheses

** Exponentiation

+x -x ~x Unary plus, unary minus, and bitwise NOT

* / // % Multiplication, division, floor division, and modulus

+ - Addition and subtraction

<< >> Bitwise left and right shifts

& Bitwise AND

^ Bitwise XOR
| Bitwise OR

== != > >= < <= is is not in not in Comparisons, identity, and membership
operators

not Logical NOT

and AND

or OR

If two operators have the same precedence, the expression is evaluated from left to right.

Example: Addition + and subtraction - has the same precedence, and therefor we evaluate
the expression from left to right:

print(5 + 4 - 7 + 3)

CASTING

Specify a Variable Type

There may be times when you want to specify a type on to a variable. This can be done with
casting. Python is an object-orientated language, and as such it uses classes to define data
types, including its primitive types.

Casting in python is therefore done using constructor functions:

 int() - constructs an integer number from an integer literal, a float literal (by
removing all decimals), or a string literal (providing the string represents a whole
number)
 float() - constructs a float number from an integer literal, a float literal or a string
literal (providing the string represents a float or an integer)
 str() - constructs a string from a wide variety of data types, including strings, integer
literals and float literals

EG:Integers:

x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3

eg:Floats:
x = float(1) y = float(2.8) z = float("3") w = float("4.2")

eg:Strings:

x = str("s1") y = str(2z = str(3.0)

CONDITIONAL STATEMENTS

IF STATEMENT

An "if statement" is written by using the if keyword.

EG:If statement:

a = 33
b = 200
if b > a:
print("b is greater than a")

In this example we use two variables, a and b, which are used as part of the if statement to
test whether b is greater than a. As a is 33, and b is 200, we know that 200 is greater than
33, and so we print to screen that "b is greater than a".

if..else Statement
In conditional if Statement the additional block of code is merged as else statement which
is performed when if condition is false.
Syntax:
if (condition):
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false

# if..else statement example

x =3

if x == 4:
print("Yes")

else:

print("No")

Output:
No
Nested If
You can have if statements inside if statements, this is called nested if statements.

EG:x = 41
if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")

LOOPING STATEMENTS

Python For Loops

A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a
string).This is less like the for keyword in other programming languages, and works more like an
iterator method as found in other object-orientated programming languages.

With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.

EG:Print each fruit in a fruit list:

fruits = ["apple", "banana", "cherry"]


for x in fruits:
print(x)

The for loop does not require an indexing variable to set beforehand.

Looping Through a String

Even strings are iterable objects, they contain a sequence of characters:

Example
Loop through the letters in the word "banana":
for x in "banana":
print(x)
The while Loop

With the while loop we can execute a set of statements as long as a condition is
true.

Example:

Print i as long as i is less than 6:

i = 1
while i < 6:
print(i)
i += 1

Nested Loops

A nested loop is a loop inside a loop.The "inner loop" will be executed one time for each
iteration of the "outer loop":

Example:Print each adjective for every fruit:

adj = ["red", "big", "tasty"]

fruits = ["apple", "banana", "cherry"]

for x in adj:

for y in fruits:

print(x, y)

CONTROLSTATEMENTS

Control statements in Python are a powerful tool for managing the flow of execution. They
allow developers to make decisions based on specific conditions and modify the normal
sequential flow of a program. By using control statements effectively, developers can write
more efficient and effective code.

Break Statement in Python

The break statement is used to terminate a loop, i.e., for loop, while loop, or nested loop.
When a break statement executes inside a loop, it immediately terminates the loop and
transfers control to the statement following the loop.

Syntax of Break Statement in Python

The syntax of break statement in Python is as follows:

while condition:
# statements

if condition:

break

# statements after break statement

In this syntax, the break statement is used inside a loop (while loop or for loop). When the condition
specified in the if statement is true, the break statement is executed, and the control is transferred
to the next statement after the loop. This means that the loop is terminated, and the code execution
continues from the statement after the loop.

Example of Break Statement in Python

Here’s an example of the break statement in Python:

list_of_numbers = [1, 3, 7, 9, 11, 12, 13, 15]


for num in list_of_numbers:

if num % 2 == 0:

print("The first even number is:", num)

break

Output:

The first even number is: 12

Continue Statement in Python: The continue statement is used to skip a particular iteration of a
loop when a specific condition is met. When a continue statement is executed inside a loop, it
skips the current iteration of the loop and jumps to the next iteration.

Syntax of Continue Statement in Python

The syntax for the continue statement in Python is as follows:

while condition:

# statements before the continue statement

if condition:

continue
# statements after the continue statement

In this syntax, when the condition specified in the if statement is true, the continue statement is
executed, and the control is transferred to the next iteration of the loop. This means that the current
iteration is skipped, and the loop continues with the next iteration.

Example of Continue Statement in Python

Here’s an example of the continue statement in Python:

numbers = [1, 3, 7, 8, 9, 11, 12, 15]

for num in numbers:

if num % 2 == 0:

continue

print(num)

Output:

1
3
7
9
11
15

Pass Statement in Python

The pass statement is a placeholder statement that does nothing. It is used when a statement is
required syntactically, but you don’t want to execute any code. Pass is mostly used as a placeholder
for functions or conditional statements that have not yet been implemented.

Syntax of Pass Statement in Python

The syntax for the pass statement in Python is as follows:

while condition:

# statements before the pass statement

if condition:

pass

# statements after the pass statement


In this syntax, the pass statement is used inside a loop (while loop or for loop) and inside an if
statement. When the pass statement is executed, it does nothing, and the control is transferred to
the next statement after the loop or the if statement.

Example of Pass Statement in Python

Here’s an example of the pass statement in Python:

x = 25
if x > 15:

pass

else:

print("x is less than or equal to 15")

Explanation: In this example, we have a variable called x that has a value of 10. We want to print a
message when the value of x is greater than 5. We use an if statement to check if the value of x is
greater than 5. Inside the if statement, we use the pass statement as a placeholder for the code that
we haven’t written yet. If the value of x is less than or equal to 5, we print a message.

When we run this program, it will not output anything, as the pass statement does nothing.
However, it serves as a placeholder for the code that we will write in the future.

MODULE2

Reading and Writing to text files in Python


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.
In this article, we will be focusing on opening, closing, reading, and writing data in a text
file.
File Access Modes
Access modes govern the type of operations possible in the opened file. It refers to how
the file will be used once its opened. These modes also define the location of the File
Handle in the file. File handle is like a cursor, which defines from where the data has to be
read or written in the file. There are 6 access modes in python.
1. Read Only (‘r’) : Open text file for reading. The handle is positioned at the beginning of
the file. If the file does not exists, raises the I/O error. This is also the default mode in
which a file is opened.
2. Read and Write (‘r+’): Open the file for reading and writing. The handle is positioned
at the beginning of the file. Raises I/O error if the file does not exist.
3. Write Only (‘w’) : Open the file for writing. For the existing files, the data is truncated
and over-written. The handle is positioned at the beginning of the file. Creates the file
if the file does not exist.
4. Write and Read (‘w+’) : Open the file for reading and writing. For an existing file, data
is truncated and over-written. The handle is positioned at the beginning of the file.
5. Append Only (‘a’): Open the file for writing. The file is created if it does not exist. The
handle is positioned at the end of the file. The data being written will be inserted at
the end, after the existing data.
6. Append and Read (‘a+’) : Open the file for reading and writing. The file is created if it
does not exist. The handle is positioned at the end of the file. The data being written
will be inserted at the end, after the existing data.

How Files are Loaded into Primary Memory

There are two kinds of memory in a computer i.e. Primary and Secondary memory every
file that you saved or anyone saved is on secondary memory cause any data in primary
memory is deleted when the computer is powered off. So when you need to change any
text file or just to work with them in python you need to load that file into primary
memory. Python interacts with files loaded in primary memory or main memory
through “file handlers” ( This is how your operating system gives access to python to
interact with the file you opened by searching the file in its memory if found it returns a
file handler and then you can work with the file ).
Opening a File
It is done using the open() function. No module is required to be imported for this
function.
File_object = open(r"File_Name","Access_Mode")
The file should exist in the same directory as the python program file else, the full address
of the file should be written in place of the filename. Note: The r is placed before the
filename to prevent the characters in the filename string to be treated as special
characters. For example, if there is \temp in the file address, then \t is treated as the tab
character, and an error is raised of invalid address. The r makes the string raw, that is, it
tells that the string is without any special characters. The r can be ignored if the file is in
the same directory and the address is not being placed.

# Open function to open the file "MyFile1.txt"

# (same directory) in append mode and

file1 = open("MyFile1.txt","a")

# store its reference in the variable file1

# and "MyFile2.txt" in D:\Text in file2


file2 = open(r"D:\Text\MyFile2.txt","w+")

Here, file1 is created as an object for MyFile1 and file2 as object for MyFile2

Closing a file

close() function closes the file and frees the memory space acquired by that file. It is used at the
time when the file is no longer needed or if it is to be opened in a different file mode.
File_object.close()

# Opening and Closing a file "MyFile.txt"

# for object name file1.

file1 = open("MyFile.txt","a")

file1.close()

Writing to a file

There are two ways to write in a file.


1. write() : Inserts the string str1 in a single line in the text file.
File_object.write(str1)
1. writelines() : For a list of string elements, each string is inserted in the text file.Used to insert
multiple strings at a single time.
File_object.writelines(L) for L = [str1, str2, str3]
Reading from a file
There are three ways to read data from a text file.
1. read() : Returns the read bytes in form of a string. Reads n bytes, if no n specified, reads the
entire file.
File_object.read([n])
1. readline() : Reads a line of the file and returns in form of a string.For specified n, reads at
most n bytes. However, does not reads more than one line, even if n exceeds the length of the
line.
File_object.readline([n])
1. readlines() : Reads all the lines and return them as each line a string element in a list.
File_object.readlines()
Note: ‘\n’ is treated as a special character of two bytes

# Program to show various ways to read and

# write data in a file.


file1 = open("myfile.txt","w")

L = ["This is Delhi \n","This is Paris \n","This is London \n"]

# \n is placed to indicate EOL (End of Line)

file1.write("Hello \n")

file1.writelines(L)

file1.close() #to change file access modes

file1 = open("myfile.txt","r+")

print("Output of Read function is ")

print(file1.read())

print()

# seek(n) takes the file handle to the nth

# byte from the beginning.

file1.seek(0)

print( "Output of Readline function is ")

print(file1.readline())

print()

file1.seek(0)

# To show difference between read and readline

print("Output of Read(9) function is ")

print(file1.read(9))

print()
file1.seek(0)

print("Output of Readline(9) function is ")

print(file1.readline(9))

file1.seek(0)

# readlines function

print("Output of Readlines function is ")

print(file1.readlines())

print()

file1.close()

Output:
Output of Read function is
Hello
This is Delhi
This is Paris
This is London

Output of Readline function is


Hello

Output of Readline(9) function is


Hello

Output of Readlines function is


['Hello \n', 'This is Delhi \n', 'This is Paris \n', 'This is London \n']

Appending to a file

# Python program to illustrate

# Append vs write mode


file1 = open("myfile.txt","w")

L = ["This is Delhi \n","This is Paris \n","This is London \n"]

file1.writelines(L)

file1.close()

# Append-adds at last

file1 = open("myfile.txt","a")#append mode

file1.write("Today \n")

file1.close()

file1 = open("myfile.txt","r")

print("Output of Readlines after appending")

print(file1.readlines())

print()

file1.close()

# Write-Overwrites

file1 = open("myfile.txt","w")#write mode

file1.write("Tomorrow \n")

file1.close()

file1 = open("myfile.txt","r")

print("Output of Readlines after writing")

print(file1.readlines())

print()
file1.close()

Output:
Output of Readlines after appending
['This is Delhi \n', 'This is Paris \n', 'This is London \n', 'Today \n']

Output of Readlines after writing


['Tomorrow \n']

Python sys Module

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. Let’s
consider the below example.

Python sys.version

In this example, sys.version is used which returns a string containing the version of Python
Interpreter with some additional information. This shows how the sys module interacts with the
interpreter. Let us dive into the article to get more information about the sys module.

import sys

print(sys.version)

Output:
3.6.9 (default, Oct 8 2020, 12:12:24)
[GCC 8.4.0]
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 –

Python Directory Management


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
.
Directory management using Python

Python contains several modules that has a number of built-in functions to manipulate
and process data. Python has also provided modules that help us to interact with the
operating system and the files. These kinds of modules can be used for directory
management also. The modules that provide the functionalities are listed below:
 os and os.path
 filecmp
 tempfile
 shutil

os and os.path module

The os module is used to handle files and directories in various ways. It provides
provisions to create/rename/delete directories. This allows even to know the current
working directory and change it to another. It also allows one to copy files from one
directory to another. The major methods used for directory management is explained
below.
Creating new directory:
 os.mkdir(name) method to create a new directory.
 The desired name for the new directory is passed as the parameter.
 By default it creates the new directory in the current working directory.
 If the new directory has to be created somewhere else then that path has to be
specified and the path should contain forward slashes instead of backward ones.

import os

# creates in current working directory

os.mkdir('new_dir')

# creates in D:\

os.mkdir('D:/new_dir')

Getting Current Working Directory (CWD):


 os.getcwd() can be used.
 It returns a string that represents the path of the current working directory.
 os.getcwdb() can also be used but it returns a byte string that represents the current
working directory.
 Both methods do not require any parameters to be passed.
import os

print("String format :", os.getcwd())

print("Byte string format :", os.getcwdb())

Output:
String format : /home/nikhil/Desktop/gfg
Byte string format : b'/home/nikhil/Desktop/gfg'
Renaming a directory:

 os.rename() method is used to rename the directory.


 The parameters passed are old_name followed by new_name.
 If a directory already exists with the new_name passed, OSError will be raised in case
of both Unix and Windows.
 If a file already exists with the new_name, in Unix no error arises, the directory will be
renamed. But in Windows the renaming won’t happen and error will be raised.
 os.renames(‘old_name’,’dest_dir:/new_name’) method works similar to os.rename() but
it moves the renamed file to the specified destination directory(dest_dir).
For example, consider there is a file named ‘file1.txt’ in current working directory. Now to
just rename it :

import os

os.rename('file1.txt','file1_renamed.txt')

If renaming and moving the file to some other directory is required, then the code snippet
should be:

import os

os.renames('file1.txt', 'D:/file1_renamed.txt')
Changing Current Working Directory (CWD):

 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.
Form example, If we need to change the CWD to my_folder in D:/, then the following code snippet
is used.

import os

print("Current directory :", os.getcwd())

# Changing directory

os.chdir('/home/nikhil/Desktop/')

print("Current directory :", os.getcwd())

Output:
Current directory : /home/nikhil/Desktop/gfg
Current directory : /home/nikhil/Desktop

Listing the files in a directory


 A directory may contain sub-directories and a number of files in it. To list
them, os.listdir() method is used.
 It either takes no parameter or one parameter.
 If no parameter is passed, then the files and sub-directories of the CWD is listed.
 If files of any other directory other than the CWD is required to be listed, then that
directory’s name/path is passed as parameter .

For example: Listing the files in the CWD- GeeksforGeeks (root directory)
import os

print("The files in CWD are :",os.listdir(os.getcwd()))

Output:

The files in CWD are : [‘site folder’, ‘.directory’, ‘proxy.txt’, ‘poem python.txt’, ‘left bar’,
‘images’, ‘Welcome to GeeksforGeeks!\nPosts Add Ne.txt’, ‘trash.desktop’, ‘gfg.py’, ‘Sorry,
you can not update core for some tim.txt’, ‘gfgNikhil Aggarwal.png’, ‘0001.jpg’, ‘gfg’,
‘gfgcerti.png’, ‘raju’, ‘images big’]

Removing a directory

 os.rmdir() method is used to remove/delete a directory.


 The parameter passed is the path to that directory.
 It deletes the directory if and only if it is empty, otherwise raises an OSError.

For example, Let us consider a directory K:/files. Now to remove it, one has to ensure
whether it is empty and then proceed for deleting.

import os

dir_li=os.listdir('k:/files')

if len(dir_li)==0:

print("Error!! Directory not empty!!")

else:

os.rmdir('k:/files')
To check whether it is a directory:
 Given a directory name or Path, os.path.isdir(path) is used to validate whether the path is a
valid directory or not.
 It returns boolean values only. Returns true if the given path is a valid directory
otherwise false.

import os

# current working directory of

# GeeksforGeeks

cwd='/'

print(os.path.isdir(cwd))

# Some other directory

other='K:/'

print(os.path.isdir(other))

Output

True
False
To get size of the directory:
 os.path.getsize(path_name) gives the size of the directory in bytes.
 OSError is raised if, invalid path is passed as parameter.

import os

print(os.path.getsize(os.getcwd()))
Output

4096
Getting access and modification times:
 To get the last accessed time of a directory : os.path.getatime (path)
 To get the last modified time of the directory : os.path.getmtime (path)
 These methods return the number of seconds since the epoch. To format it, datetime
module’s strftime( ) function can be used.

Example : Getting access and modification time of GeeksforGeeks (root) directory

import os

import datetime as dt

print("Before conversion :")

# returns seconds since epoch

print("last access time :",os.path.getatime(os.getcwd()))

print("last modification time :",os.path.getmtime(os.getcwd()))

print("After conversion :")

# formatting the return value

access_time=dt.datetime.fromtimestamp(os.path.getatime(os.getcwd()))
.strftime('%Y-%m-%d %I:%M %p')

modification_time=dt.datetime.fromtimestamp(os.path.getmtime(os.getc
wd())).strftime('%Y-%m-%d %I:%M %p')

print("last access time :",access_time)

print("last modification time :",modification_time)

Output

Before conversion :
last access time : 1596897099.56
last modification time : 1596897099.56
After conversion :
last access time : 2020-08-08 02:31 PM
last modification time : 2020-08-08 02:31 PM

filecmp module

This module provides various functions to perform comparison between files and directories. To
compare the directories, an object has to be created for the class filecmp.dircmp that describes
which files to ignore and which files to hide from the functions of this class. The constructor has to
be invoked before calling any of the functions of this class. The constructor can be invoked as
given below:
d = filecmp . dircmp( dir_1, dir_2, ignore=[a,b,c]/None, hide=[d,e,f]/None )
Functions for comparing directories:
1. d.report() : Compares the two directories given while invoking the constructor and presents a
summary regarding the list of files in both the directories. In case any identical files are found,
they are also listed. Common sub-directories are also printed in the output.

import filecmp as fc

import os

dir_1 = dir_2 = os.getcwd()

# creating object and invoking constructor

d = fc.dircmp(dir_1, dir_2, ignore=None, hide=None)

print("comparison 1 :")

d.report()

2. d.report_partial_closure() : Prints out the comparison between the directories passed and also
the comparisons between the immediate common sub-directories.
import filecmp as fc

import os

dir_1 = dir_2 = os.getcwd()

# creating object and invoking constructor

d = fc.dircmp(dir_1, dir_2, ignore=None, hide=None)

print("comparison 2 :")

d.report_partial_closure()

3. d.report_full_closure() : It is same as the previous one, but does the work recursively. It
compares and displays the common sub-directories, identical files and common funny
cases (the two things do not match in type, ie., one is a directory and another is a file.)

import filecmp as fc

import os

dir_1 = dir_2 = os.getcwd()

# creating object and invoking constructor

d = fc.dircmp(dir_1, dir_2, ignore=None, hide=None)

print("comparison 3 :")

d.report_full_closure()

tempfile module:

 This module is used to create temporary files and directories.


 This creates the temporary files and directories in the temp directories created by the
Operating systems.
 For windows, the temp files can be found at the following path:
profile/AppData/Local/temp

mkdtemp() :
 It is used to create a temporary directory by passing the parameters suffix, prefix and dir.
 The suffix and prefix corresponds to the naming conventions for the created temp directory.
suffix decides how the file name should end and prefix is decides the beginning of the name
and mostly set to ‘tmp‘.
 The dir parameter specifies the path where the temporary directory should be created. By
default the dir is set to the temp directory created by the Operating systems.
 This temporary directories are readable, writable and searchable only by the creator using the
creator’s unique ID.
 The user who created the temp dir is responsible for deleting the temporary directory upon
completion of the work.
 It returns the path of the created new directory.

import tempfile as tf

f = tf.mkdtemp(suffix='', prefix='tmp')

print(f)

Output

/tmp/tmp0ndvk7p_
TemporaryDirectory():
 This function makes use of mkdtemp() to create a temporary directory and the same
parameters are passed here also.
 The main difference is, the object created as a result acts as a context manager.
 The user need not manually delete the created temporary file, it is cleared automatically by
the file system.
 To get the name of the newly created temp directory, object.name can be used.
 To delete the temporary dir explicitly, cleanup( ) function can be used.

import tempfile as tf

f = tf.TemporaryDirectory(suffix='', prefix='tmp')

print("Temporary file :", f.name)

f.cleanup()

Output:Temporary file : /tmp/tmpp3wr65fj


shutil module

This module is concerned with number of high-level operations on files and directories. It
allows copying/moving directories from a source to destination.
shutil.copytree(s, d, symlinks=False, ignore=None, copy_function=copy2,
ignore_dangling_symlinks=False):
 Recursively copies the source directory (s) to the destination directory (d) provided
that ‘d’ does not already exists.
 symlinks are also known as symbolic links which denote some virtual files or reference
folders or folders that located somewhere else. It can take values like true, false or
omitted. If true, the symlinks in source are marked as symlinks in the destination also,
but the associated metadata will not be copied. If the value is false or omitted, the
contents as well as the metadata of the linked file are copied to the destination.
 For ignore, a callable that takes the directory being visited and its contents like the
return value of os.listdir() since, copytree() is a recursive functions. The files to be
ignored while copying can be named using this parameter.
 The copy2 function is used as the default copy_function because it allows copying
metadata. copy(), copystat() can also be used.
shutil.rmtree(path, ignore_errors=False, onerror=None):
 Deletes an entire directory. This overcomes the main disadvantage of os.rmdir() that it
deletes the directory only if it is empty.
 The path should be a valid directory. The symlinks to a directory won’t be accepted.
 If ignore_error is true, then the errors raised while removing the directory will be
ignored. If false or omitted is given, then the raised errors should be handled by the
ones mentioned in onerror parameter.
 onerror is a callable that takes three parameters namely function, path and excinfo.
The first is the function that raises the exception, the next is the path to be passed to
the function and the last is the exception information returned by sys.exc_info().
shutil.move(s,d):
 Recursively moves the source directory to the destination specified.
 The destination is not supposed to exist already, if exists based on the os.rename()
semantics, it will be overwritten.
CSV

CSV (Comma Separated Values) is a simple file format used to store tabular data, such as a
spreadsheet or database. CSV file stores tabular data (numbers and text) in plain text. Each
line of the file is a data record. Each record consists of one or more fields, separated by
commas. The use of the comma as a field separator is the source of the name for this file
format.

Create CSV File

To create a CSV file and write data into it using Python, we have to follow a certain
set of instructions:
 Open the CSV file in writing (w mode) with the help of open() function
 Create a CSV writer object by calling the writer() function of the csv module
 Write data to CSV file by calling either the writerow() or writerows() method of the CSV
writer object
 Finally, close the CSV file

CSV Module Functions

CSV module is used to read/ write CSV files in Python. To use the csv module in our
program we have to first import using the following statement:

Import csv
Before learning about different types of functions let us study in brief about dialects,
Dialects are used to group multiple formatting patterns like delimiter, skipinitialspace,
quoting, and escapechar into a single dialect name, thus removing redundancy when
working with multiple files. We will learn more about dialects later in this article.
Different types of functions in the csv module are as follows:
 csv.field_size_limit - This function returns the current maximum field size allowed by the
parser.
 csv.get_dialect - It returns the dialect associated with a name.
 csv.list_dialects - It returns the names of all registered dialects.
 csv.reader - This function reads the data from a CSV file.
 csv.register_dialect - It associates dialect with a name, and the name must be a string or a
Unicode object.
 csv.writer - This function writes the data to a CSV file.
 csv.unregister_dialect - It deletes the dialect, which is associated with the name from the
dialect registry. If a name is not a registered dialect name, then an error is raised.
 csv.QUOTE_ALL - It instructs the writer objects to quoting all fields. Msc Computer Science
STAS EDAPPALLY 3
 csv.QUOTE_MINIMAL - It instructs the writer to quote only those fields containing special
characters such as quote char, delimiter, etc.
 csv.QUOTE_NONNUMERIC - It instructs the writer objects to quote all the non-numeric
fields.
 csv.QUOTE_NONE - It instructs the writer object never to quote the fields.

Reading from CSV


file Python contains a module called csv for the handling of CSV files. The reader class from
the module is used for reading data from a CSV file. At first, the CSV file is opened using the
open() method in ‘r’ mode(specifies read mode while opening a file) which returns the file
object then it is read by using the reader() method of CSV module that returns the reader
object that iterates throughout the lines in the specified CSV document.

Syntax: ow(fields csv.reader(csvfile, dialect='excel', **fmtparams)

The ‘with‘ keyword is used along with the open() method as it simplifies exception handling
and automatically closes the CSV file.
Writing to CSV file

csv.writer class is used to insert data to the CSV file. This class returns a writer object which
is responsible for converting the user’s data into a delimited string. A CSV file object should
be opened with newline=” otherwise, newline characters inside the quoted fields will not be
interpreted correctly.

Syntax: csv.writer(csvfile, dialect='excel', **fmtparams)

csv.writer class provides two methods for writing to CSV. They are writerow() and writerows().

 writerow(): This method writes a single row at a time. Field row can be written using this method.

Syntax: writerow(fields)

 writerows(): This method is used to write multiple rows at a time. This can be used to write rows
list.
Syntax: writerows(rows)

Python String

A String is a data structure in Python that represents a sequence of characters. It is an


immutable data type, meaning that once you have created a string, you cannot change it.
Strings are used widely in many different applications, such as storing and manipulating
text data, representing names, addresses, and other types of data that can be represented
as text.

What is a String in Python?

Python does not have a character data type, a single character is simply a string with a
length of 1.
Example:
"Geeksforgeeks" or 'Geeksforgeeks' or "a"

print("A Computer Science portal for geeks")

print('A')

Output:
A Computer Science portal for geeks
Creating a String in Python
Strings in Python can be created using single quotes or double quotes or even triple
quotes. Let us see how we can define a string in Python.
Example:
In this example, we will demonstrate different ways to create a Python String. We will
create a string using single quotes (‘ ‘), double quotes (” “), and triple double quotes (“””
“””). The triple quotes can be used to declare multiline strings in Python.

# Python Program for

# Creation of String

# Creating a String

# with single Quotes

String1 = 'Welcome to the Geeks World'

print("String with the use of Single Quotes: ")

print(String1)

# Creating a String

# with double Quotes

String1 = "I'm a Geek"

print("\nString with the use of Double Quotes: ")

print(String1)

# Creating a String

# with triple Quotes

String1 = '''I'm a Geek and I live in a world of "Geeks"'''

print("\nString with the use of Triple Quotes: ")


print(String1)

# Creating String with triple

# Quotes allows multiple lines

String1 = '''Geeks

For

Life'''

print("\nCreating a multiline String: ")

print(String1)

Accessing characters in Python String

In Python, individual characters of a String can be accessed by using the method of Indexing.
Indexing allows negative address references to access characters from the back of the String,
e.g. -1 refers to the last character, -2 refers to the second last character, and so on.
While accessing an index out of the range will cause an IndexError. Only Integers are allowed to
be passed as an index, float or other types that will cause a TypeError.

Python String indexing

Example:
In this example, we will define a string in Python and access its characters using positive and
negative indexing. The 0th element will be the first character of the string whereas the -1th
element is the last character of the string.

# Python Program to Access

# characters of String
String1 = "GeeksForGeeks"

print("Initial String: ")

print(String1)

# Printing First character

print("\nFirst character of String is: ")

print(String1[0])

# Printing Last character

print("\nLast character of String is: ")

print(String1[-1])

BASIC OPERATIONS IN STRING

Python | Extract words from given string


In Python, we sometimes come through situations where we require to get all the words
present in the string, this can be a tedious task done using the native method. Hence
having shorthand to perform this task is always useful. Additionally, this article also
includes the cases in which punctuation marks have to be ignored.
Input: GeeksForGeeks is the best Computer Science Portal
Output: ['GeeksForGeeks', 'is', 'the', 'best', 'Computer', 'Science', 'Portal']
Explanation: In this, we are extracting each word from a given string
Python Extract Words From String

Python String replace() Method

The replace() method replaces a specified phrase with another specified phrase.

Note: All occurrences of the specified phrase will be replaced, if nothing else is specified.
Syntax:string.replace(oldvalue, newvalue, count)

Parameter Values

Parameter Description

oldvalue Required. The string to search for

newvalue Required. The string to replace the old value with

count Optional. A number specifying how many occurrences of the old value you want to replac
occurrences

Example:

Replace the word "bananas":

txt = "I like bananas"

x = txt.replace("bananas", "apples")

print(x)

Python len() Function

The len() function returns the number of items in an object.When the object is a string,
the len() function returns the number of characters in the string.

Syntax:len(object)

Parameter Values

Parameter Description

object Required. An object. Must be a sequence or a collection


Example

Return the number of items in a list:

mylist = ["apple", "banana", "cherry"]


x = len(mylist)

Python String lower() Method

The lower() method returns a string where all characters are lower case.Symbols and Numbers are
ignored.

Syntax:string.lower()

Parameter Values

No parameters

Example

Lower case the string:

txt = "Hello my FRIENDS"

x = txt.lower()

print(x)

Python String upper() Method

The upper() method returns a string where all characters are in upper case.

Symbols and Numbers are ignored.

Syntax:string.upper()
Parameter Values

No parameters

Example

Upper case the string:

txt = "Hello my friends"


x = txt.upper()

print(x)

Python String split() Method

The split() method splits a string into a list.You can specify the separator, default separator is any
whitespace.

Note: When maxsplit is specified, the list will contain the specified number of elements plus one.

Syntax:string.split(separator, maxsplit)

Parameter Values

Parameter Description

separator Optional. Specifies the separator to use when splitting the string. By default any whitespa

maxsplit Optional. Specifies how many splits to do. Default value is -1, which is "all occurrences"

Python | Get the substring from given string using list slicing

What is substring?
A substring is a portion of a string. Python offers a variety of techniques for producing
substrings, as well as for determining the index of a substring and more.
String Slicing in Python
How String slicing in Python works

For understanding slicing we will use different methods, here we will cover 2 methods of string
slicing, one using the in-build slice() method and another using the [:] array slice. String slicing in
Python is about obtaining a sub-string from the given string by slicing it respectively from start to
end.

Python slicing can be done in two ways:

 Using a slice() method


 Using the array slicing [:: ] method
Index tracker for positive and negative index: String indexing and slicing in python. Here, the
Negative comes into consideration when tracking the string in reverse.

Method 1: Using the slice() method

The slice() constructor creates a slice object representing the set of indices specified by
range(start, stop, step).
Syntax:
 slice(stop)
 slice(start, stop, step)
Parameters: start: Starting index where the slicing of object starts. stop: Ending index where the
slicing of object stops. step: It is an optional argument that determines the increment between
each index for slicing. Return Type: Returns a sliced object containing elements in the given range
only.
Example:
# Python program to demonstrate

# string slicing

# String slicing

String = 'ASTRING'

# Using slice constructor

s1 = slice(3)

s2 = slice(1, 5, 2)

s3 = slice(-1, -12, -2)

print("String slicing")

print(String[s1])

print(String[s2])

print(String[s3])

Output:

String slicing
AST
SR
GITA

Method 2: Using the List/array slicing [ :: ] method

In Python, indexing syntax can be used as a substitute for the slice object. This is an easy and
convenient way to slice a string using list slicing and Array slicing both syntax-wise and execution-
wise. A start, end, and step have the same mechanism as the slice() constructor.
Below we will see string slicing in Python with examples.

Syntax:arr[start:stop] # items start through stop-1


arr[start:] # items start through the rest of the array
arr[:stop] # items from the beginning through stop-1
arr[:] # a copy of the whole array
arr[start:stop:step] # start through not past stop, by step
Example 1:
In this example, we will see slicing in python list the index start from 0 indexes and ending with a
2 index(stops at 3-1=2 ).

# Python program to demonstrate

# string slicing

# String slicing

String = 'GEEKSFORGEEKS'

# Using indexing sequence

print(String[:3])

Output:
GEE

Advantages of String in Python:


 Strings are used at a larger scale i.e. for a wide areas of operations such as storing and
manipulating text data, representing names, addresses, and other types of data that
can be represented as text.
 Python has a rich set of string methods that allow you to manipulate and work with
strings in a variety of ways. These methods make it easy to perform common tasks
such as converting strings to uppercase or lowercase, replacing substrings, and
splitting strings into lists.
 Strings are immutable, meaning that once you have created a string, you cannot
change it. This can be beneficial in certain situations because it means that you can be
confident that the value of a string will not change unexpectedly.
 Python has built-in support for strings, which means that you do not need to import
any additional libraries or modules to work with strings. This makes it easy to get
started with strings and reduces the complexity of your code.
 Python has a concise syntax for creating and manipulating strings, which makes it easy
to write and read code that works with strings.
Drawbacks of String in Python:
 When we are dealing with large text data, strings can be inefficient. For instance, if you
need to perform a large number of operations on a string, such as replacing substrings
or splitting the string into multiple substrings, it can be slow and consume a lot
resources.
 Strings can be difficult to work with when you need to represent complex data
structures, such as lists or dictionaries. In these cases, it may be more efficient to use a
different data type, such as a list or a dictionary, to represent the data.

Python Strings

Strings in python are surrounded by either single quotation marks, or double quotation
marks.

'hello' is the same as "hello".

You can display a string literal with the print() function:

Example
print("Hello")
print('Hello')

Assign String to a Variable

Assigning a string to a variable is done with the variable name followed by an equal sign and the
string:

Example
a = "Hello"
print(a)

Multiline Strings

You can assign a multiline string to a variable by using three quotes:

Example

You can use three double quotes:

a = """Lorem ipsum dolor sit amet,


consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""

Strings are Arrays

Like many other popular programming languages, strings in Python are arrays of bytes
representing unicode characters.However, Python does not have a character data type, a
single character is simply a string with a length of 1.Square brackets can be used to access
elements of the string.
Example

Get the character at position 1 (remember that the first character has the position 0):

a = "Hello, World!"
print(a[1])

Looping Through a String

Since strings are arrays, we can loop through the characters in a string, with a for loop.

Example

Loop through the letters in the word "banana":

for x in "banana":
print(x)

Check String

To check if a certain phrase or character is present in a string, we can use the keyword in.

Example

Check if "free" is present in the following text:

txt = "The best things in life are free!"


print("free" in txt)

Use it in an if statement:

Example

Print only if "free" is present:

txt = "The best things in life are free!"


if "free" in txt:
print("Yes, 'free' is present.")

Check if NOT

To check if a certain phrase or character is NOT present in a string, we can use the keyword not in.

Example

Check if "expensive" is NOT present in the following text:

txt = "The best things in life are free!"


print("expensive" not in txt)
Use it in an if statement:

Example

print only if "expensive" is NOT present:

txt = "The best things in life are free!"


if "expensive" not in txt:
print("No, 'expensive' is NOT present.")

Number System in Python


The arithmetic value which is used for representing the quantity and used in making
calculations are defined as NUMBERS. The writing system for denoting numbers using digits
or symbols in a logical manner is defined as a Number system. Number System is a system
that defines numbers in different ways to represent numbers in different forms.

Types of Number System


The number system in python is represented using the following four systems:

 Binary Number System (base or radix =2)


 Octal Number System (base or radix = 8)
 Decimal Number System (base or radix = 10)
 Hexadecimal Number System (base or radix = 16)

Binary Number System


A number system with base or radix 2 is known as a binary number system. Only 0 and 1 are used to
represent numbers in this system.

1) Binary to Decimal

For Binary to Decimal conversion, the binary number uses weights assigned to each bit position. like

a=1001
a = 1*23 +0*22+0*21+1*20
a= (8+0+0+1) = 9

Output:

Binary to Decimal 1001 : 9

2) Binary to Octal

First convert binary number to decimal number by assigning weight to each binary bit.

a = 1 0 0 1
a =1*23 + 0*22+ 0*21 +1*20
a= (8+0+0+1) = 9
Now, 9 can be converted into octal by dividing it by 8 until we get the
remainder between (0-7).
(1001)2 = (9)10 = (11)8

Output:

Binary to Octal 9 : 0o11

3) Binary to Hexadecimal

First convert binary number to decimal number by assigning weight to each binary bit.

a = 100101
a =1*25+0*24+0*23+1*22+0*21+1*20
a= (32+0+0+4+0+1) = 37
As 100101 in binary is represented as 37 in decimal we can convert 37 into Hexadecimal by dividing
it by 16.

a = (100101)2= (37)10 = (25)16

Output:

Binary to Hexadecimal 37 : 0x25

Octal Number System


Octal Number System is one in which the base value is 8. It uses 8 digits i.e. 0-7 for the creation of
Octal Numbers. It is also a positional system i.e weight is assigned to each position.

1) Octal to Binary:

Octal numbers are converted to binary numbers by replacing each octal digit with a three-bit binary
number. In python bin( ) function is used to convert octal number to binary number. The value is
written with ‘0o’ as a prefix which indicates that the value is in the octal form.

eg. (123)8 = (001 010 011)2 = (1010011)2

Output:

Octal to Binary 0o123 : 0b1010011

2) Octal to Decimal:

An octal number can be converted into a decimal number by assigning weight to each position. In
python int( ) function is used to convert octal to decimal numbers. Two arguments are get passed,
the first is a string of octal numbers, and the second is the base of the number system specified in
the string.
(342)8 = 3* 82 + 4*81 + 2*80
= 3*64 + 4*8 + 2*1
= 226
(342)8 = (226)1

Output:

Octal to Decimal 342 : 226

3) Octal to Hexadecimal:

An Octal number can be converted into a hexadecimal number by converting the number into a
decimal and then a decimal number to hexadecimal. In python hex( ) function is used to convert
octal to hexadecimal numbers.

Let’s first convert b into a decimal number.

b = (456)8
(456)8 = 4*82 + 5*81+ 6*80
(456)8 = (302)10 = (12E)16

Output:

Octal to Hexadecimal 302 : 0x12e

Hexadecimal Number System


A number system with a base of 16 is called a hexadecimal number system. It is represented using
numbers between 0 to 9 and the alphabets between A to F. As both numeric digits and alphabets are
used in this system, it is also called an alphanumeric system.

1) Hexadecimal to Binary:

The hexadecimal number is converted into a Binary number by replacing each hex digit with its
binary equivalent number.

a = FACE
F = (15)10 = (1111)2
A = (1)10 = (0001)2
C = (12)10 = (1100)2
E =(14)10 = (1110)2
(FACE)16 = (1111000111001110)2

Output:

Hexadecimal to Binary 64206 : 0b1111101011001110


2) Hexadecimal to Octal:

The hexadecimal number is converted to an octal number by first converting that number to its
equivalent binary number and then to a binary number to an octal number.

Eg.)
(94AB)16 = (1001 0100 1010 1011)2
= 001 001 010 010 101 011
= (112253)8
a
Output:

Hexadecimal to Octal 38059 : 0o112253

3) Hexadecimal to Decimal:

Hexadecimal number is converted into decimal number by assigning weight (16) to each hex digit.

(94AB)16 = 9*163 + 4*162 + A*161+ B* 160


= 9* 4096 + 4*256 + 10*16 + 11*1
= (38059)10

Output:

Hexadecimal to Decimal 0x94AB : 38059

Python String Methods

Python has a set of built-in methods that you can use on strings.

Note: All string methods returns new values. They do not change the original string.

Method Description

capitalize() Converts the first character to upper case

casefold() Converts string into lower case

center() Returns a centered string

count() Returns the number of times a specified value occurs in a string


encode() Returns an encoded version of the string

endswith() Returns true if the string ends with the specified value

expandtabs() Sets the tab size of the string

find() Searches the string for a specified value and returns the position of where it was found

format() Formats specified values in a string

format_map() Formats specified values in a string

index() Searches the string for a specified value and returns the position of where it was found

isalnum() Returns True if all characters in the string are alphanumeric

isalpha() Returns True if all characters in the string are in the alphabet

isascii() Returns True if all characters in the string are ascii characters

isdecimal() Returns True if all characters in the string are decimals

isdigit() Returns True if all characters in the string are digits


isidentifier() Returns True if the string is an identifier

islower() Returns True if all characters in the string are lower case

isnumeric() Returns True if all characters in the string are numeric

isprintable() Returns True if all characters in the string are printable

isspace() Returns True if all characters in the string are whitespaces

istitle() Returns True if the string follows the rules of a title

isupper() Returns True if all characters in the string are upper case

join() Converts the elements of an iterable into a string

ljust() Returns a left justified version of the string

lower() Converts a string into lower case

lstrip() Returns a left trim version of the string

maketrans() Returns a translation table to be used in translations


partition() Returns a tuple where the string is parted into three parts

replace() Returns a string where a specified value is replaced with a specified value

rfind() Searches the string for a specified value and returns the last position of where it was found

rindex() Searches the string for a specified value and returns the last position of where it was found

rjust() Returns a right justified version of the string

rpartition() Returns a tuple where the string is parted into three parts

rsplit() Splits the string at the specified separator, and returns a list

rstrip() Returns a right trim version of the string

split() Splits the string at the specified separator, and returns a list

splitlines() Splits the string at line breaks and returns a list

startswith() Returns true if the string starts with the specified value

strip() Returns a trimmed version of the string


swapcase() Swaps cases, lower case becomes upper case and vice versa

title() Converts the first character of each word to upper case

translate() Returns a translated string

upper() Converts a string into upper case

zfill() Fills the string with a specified number of 0 values at the beginning

Note: All string methods returns new values. They do not change the original string.

MODULE 3

LIST

mylist = ["apple", "banana", "cherry"]

Lists are used to store multiple items in a single variable.Lists are one of 4 built-in data types
in Python used to store collections of data, the other 3 are Tuple, Set, and Dictionary, all
with different qualities and usage. Lists are created using square brackets:

Create a List:
thislist = ["apple", "banana", "cherry"]
print(thislist)

List Items

List items are ordered, changeable, and allow duplicate values.List items are indexed, the
first item has index [0], the second item has index [1] etc.
Ordered

When we say that lists are ordered, it means that the items have a defined order, and that order will
not change.If you add new items to a list, the new items will be placed at the end of the list.

Note: There are some list methods that will change the order, but in general: the order of the items
will not change.

Changeable

The list is changeable, meaning that we can change, add, and remove items in a list after it has been
created.

Allow Duplicates

Since lists are indexed, lists can have items with the same value:

Example

Lists allow duplicate values:

thislist = ["apple", "banana", "cherry", "apple", "cherry"]


print(thislist)

List Length

To determine how many items a list has, use the len() function:

Example

Print the number of items in the list:

thislist = ["apple", "banana", "cherry"]


print(len(thislist))

List Items - Data Types

Example

String, int and boolean data types:

list1 = ["apple", "banana", "cherry"]


list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]

A list can contain different data types:Example

A list with strings, integers and boolean values:


list1 = ["abc", 34, True, 40, "male"]

type()

From Python's perspective, lists are defined as objects with the data type 'list':

<class 'list'>

Example

What is the data type of a list?

mylist = ["apple", "banana", "cherry"]


print(type(mylist))

The list() Constructor

It is also possible to use the list() constructor when creating a new list.

Example

Using the list() constructor to make a List:

thislist = list(("apple", "banana", "cherry")) # note the double round-brackets


print(thislist)

LIST OPERATORS

The list is a data structuring method that allows storing the integers or the characters in an order
indexed by starting from 0. List operations are the operations that can be performed on the data in
the list data structure. A few of the basic list operations used in Python programming are extend(),
insert(), append(), remove(), pop(), slice, reverse(), min() & max(), concatenate(), count(), multiply(),
sort(), index(), clear(), etc.

 The Python List is one of the built-in data types of Python and the most flexible one.
These are involved in the storage of the collection of data sets.

 The elements of a list are in a defined order, and you can modify these elements.
Either add, remove, or change the elements in the list.
 It is easy to create the Python list; add some elements in square brackets, separating
each element by comma and assigning it to a variable.
 Python Lists allow you to perform various functions apart from simple operations
like adding or deleting. You can remove any element irrespective of the position,
reverse the order of the list, print the results in a specific sequence, and sort or even
empty the elements in the list.
List Operations in Python
Some of the most widely used list operations in Python include the following:

1. append()
The append() method adds elements at the end of the list. This method can only add a
single element at a time. You can use the append() method inside a loop to add multiple
elements.

Code: myList = [1, 2, 3, 'EduCBA', 'makes learning fun!']

myList.append(4)

myList.append(5)

myList.append(6)

for i in range(7, 9):

myList.append(i)

print(myList)

2. extend()

The extend() method adds more than one element at the end of the list. Although it can add
more than one element, unlike append(), it adds them at the end of the list like append().

Code:

myList = [1, 2, 3, 'EduCBA', 'makes learning fun!']

myList.extend([4, 5, 6]

for i in range(7, 11):

myList.append(i)

print(myList)
3. insert()

The insert() method can add an element at a given position in the list. Thus, unlike append(),
it can add elements at any position, but like append(), it can add only one element at a time.
This method takes two arguments. The first argument specifies the position, and the second
argument specifies the element to be inserted.

Code:

myList = [1, 2, 3, 'EduCBA', 'makes learning fun!']


myList.insert(3, 4)
myList.insert(4, 5)
myList.insert(5, 6)
print(myList)

4. remove()
The remove() method removes an element from the list. Only the first occurrence of the same
element is removed in the case of multiple occurrences.

Code:

myList = [1, 2, 3, 'EduCBA', 'makes learning fun!']


myList.remove('makes learning fun!')
print(myList)

5. pop()

The method pop() can remove an element from any position in the list. The parameter supplied to
this method is the element index to be removed.

Code:

myList = [1, 2, 3, 'EduCBA', 'makes learning fun!']


myList.pop(3)
print(myList)

6. slice

The slice operation is used to print a section of the list. The slice operation returns a specific range of
elements. It does not modify the original list.
Code:

myList = [1, 2, 3, 'EduCBA', 'makes learning fun!']


print(myList[:4]) # prints from beginning to end index
print(myList[2:]) # prints from start index to end of list
print(myList[2:4]) # prints from start index to end index
print(myList[:]) # prints from beginning to end of list

7. reverse()

You can use the reverse() operation to reverse the elements of a list. This method modifies the
original list. We use the slice operation with negative indices to reverse a list without modifying the
original. Specifying negative indices iterates the list from the rear end to the front end of the list.

Code:

myList = [1, 2, 3, 'EduCBA', 'makes learning fun!']


print(myList[::-1]) # does not modify the original list
myList.reverse() # modifies the original list

print(myList)

8. len()
The len() method returns the length of the list, i.e., the number of elements in the list.

Code:

myList = [1, 2, 3, 'EduCBA', 'makes learning fun!']


print(len(myList))

9. min() & max()

The min() method returns the minimum value in the list. The max() method returns the maximum
value in the list. Both methods accept only homogeneous lists, i.e., lists with similar elements.

Code:

myList = [1, 2, 3, 4, 5, 6, 7]
print(min(myList))
print(max(myList))
Output:
10. count()

The function count() returns the number of occurrences of a given element in the list.

Code:

myList = [1, 2, 3, 4, 3, 7, 3, 8, 3]
print(myList.count(3))

11. concatenate

The concatenate operation merges two lists and returns a single list. The concatenation is performed
using the + sign. It’s important to note that the individual lists are not modified, and a new combined
list is returned.

Code:

myList = [1, 2, 3, 'EduCBA', 'makes learning fun!']


yourList = [4, 5, 'Python', 'is fun!']
print(myList+yourList)

12. multiply

Python also allows multiplying the list n times. The resultant list is the original list iterated n times.

Code:

myList = ['EduCBA', 'makes learning fun!']


print(myList*2)

13. index()

The index() method returns the position of the first occurrence of the given element. It takes two
optional parameters – the beginning index and the end index. These parameters define the start and
end position of the search area on the list. When you supply the begin and end indices, the element
is searched only within the sub-list specified by those indices. When not supplied, the element is
searched in the whole list.

Code:

myList = [1, 2, 3, 'EduCBA', 'makes learning fun!']


print(myList.index('EduCBA')) # searches in the whole list
print(myList.index('EduCBA', 0, 2)) # searches from 0th to 2nd position
14. sort()
The sort method sorts the list in ascending order. You can only perform this operation on
homogeneous lists, which means lists with similar elements.

Code:

yourList = [4, 2, 6, 5, 0, 1]
yourList.sort()
print(yourList)

15. clear()
This function erases all the elements from the list and empties them.

Code:

myList = [1, 2, 3, 'EduCBA', 'makes learning fun!']


myList.clear()
16. copy()
The copy method returns the shallow copy list. Now the created list points to a different memory
location than the original one. Hence any changes made to the list don’t affect another one.

Syntax:

list.copy()
Code:

even_numbers = [2, 4, 6, 8]
value = even_numbers.copy()
print('Copied List:', value)

TUPLE
mytuple = ("apple", "banana", "cherry")

Tuples are used to store multiple items in a single variable.Tuple is one of 4 built-in data types in
Python used to store collections of data, the other 3 are List, Set, and Dictionary, all with different
qualities and usage.A tuple is a collection which is ordered and unchangeable.Tuples are written
with round brackets.

Eg:
Create a Tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple)

Tuple Items
Tuple items are ordered, unchangeable, and allow duplicate values.Tuple items are indexed, the first
item has index [0], the second item has index [1] etc.

Ordered

When we say that tuples are ordered, it means that the items have a defined order, and that order
will not change.

Unchangeable

Tuples are unchangeable, meaning that we cannot change, add or remove items after the tuple has
been created.

Allow Duplicates

Since tuples are indexed, they can have items with the same value:

Example
Tuples allow duplicate values:

thistuple = ("apple", "banana", "cherry", "apple", "cherry")


print(thistuple)

Tuple Length

To determine how many items a tuple has, use the len() function:

Example
Print the number of items in the tuple:

thistuple = ("apple", "banana", "cherry")


print(len(thistuple))

Create Tuple With One Item

To create a tuple with only one item, you have to add a comma after the item, otherwise Python will
not recognize it as a tuple.
Example
One item tuple, remember the comma:

thistuple = ("apple",)
print(type(thistuple))
thistuple = ("apple")
print(type(thistuple))

Tuple Items - Data Types

Tuple items can be of any data type:

Example
String, int and boolean data types:

tuple1 = ("apple", "banana", "cherry")


tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False, False)

A tuple can contain different data types:

Example
A tuple with strings, integers and boolean values:

tuple1 = ("abc", 34, True, 40, "male")

type()

From Python's perspective, tuples are defined as objects with the data type 'tuple':

<class 'tuple'>

Example
What is the data type of a tuple?

mytuple = ("apple", "banana", "cherry")


print(type(mytuple))

The tuple() Constructor

It is also possible to use the tuple() constructor to make a tuple.

Example
Using the tuple() method to make a tuple:
thistuple = tuple(("apple", "banana", "cherry")) # note the double round-brackets
print(thistuple)

Python Tuple is a collection of objects separated by commas. In some ways, a tuple is similar to a
Python list in terms of indexing, nested objects, and repetition but the main difference between
both is Python tuple is immutable, unlike the Python list which is mutable.

Creating Python Tuples

There are various ways by which you can create a tuple in Python. They are as follows:
 Using round brackets
 With one item
 Tuple Constructor
Create Tuples using Round Brackets ()
To create a tuple we will use () operators.

var = ("Geeks", "for", "Geeks")

print(var)

DICTIONARY
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

Dictionaries are used to store data values in key:value pairs.A dictionary is a collection which is
ordered*, changeable and do not allow duplicates.Dictionaries are written with curly brackets, and
have keys and values:

Example
Create and print a dictionary:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
Dictionary Items

Dictionary items are ordered, changeable, and does not allow duplicates.Dictionary items are
presented in key:value pairs, and can be referred to by using the key name.

Example
Print the "brand" value of the dictionary:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])

Ordered or Unordered?

When we say that dictionaries are ordered, it means that the items have a defined order, and that
order will not change.Unordered means that the items does not have a defined order, you cannot
refer to an item by using an index.

Changeable

Dictionaries are changeable, meaning that we can change, add or remove items after the dictionary
has been created.

Duplicates Not Allowed

Dictionaries cannot have two items with the same key:

Example
Duplicate values will overwrite existing values:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(thisdict)

Dictionary Length

To determine how many items a dictionary has, use the len() function:

Example
Print the number of items in the dictionary:

print(len(thisdict))

Dictionary Items - Data Types

The values in dictionary items can be of any data type:

Example
String, int, boolean, and list data types:

thisdict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
}

type()

From Python's perspective, dictionaries are defined as objects with the data type 'dict':

<class 'dict'>

Example
Print the data type of a dictionary:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(type(thisdict))

The dict() Constructor

It is also possible to use the dict() constructor to make a dictionary.

Example
Using the dict() method to make a dictionary:

thisdict = dict(name = "John", age = 36, country = "Norway")


print(thisdict)
Dictinary literals
A dictionary literal can contain one or more pairs of key/item values.
The first expression in a dictionary literal entry is the key value and the second expression is the item
value. In a dictionary literal, all key values must be the same type and all item values must the same
type. Both must be of a type that matches the types specified in the dictionary variable's definition.
A dictionary literal must contain at least one key/item pair except when the dictionary literal is in an
initializer. For example, the following statement is valid:

myDictionary := {};
The following statement is not valid:
takesADictionaryArgument({});
Example:

{1:"One", 2:"Two", 3:"Three"}


The dictionary stores the data in the key-value pair. It is enclosed by curly braces ‘{}‘ and each pair
is separated by the commas(,). We can store different types of data in a dictionary. Dictionaries
are mutable.

ADDING KEYS: To insert new keys/values into a Dictionary, use the square brackets and the
assignment operator. With that, the update() method can also be used. Remember, if the
key is already in the dictionary, its value will get updated, else the new pair gets inserted.

Insert new key value pair in the Dictionary

Let us now insert new key:value into the Dictionary. We have first displayed the Dictionary before
updating the values. Here, we have inserted a new key:value pair

programming, web development, and AI/ML programming as well, making it

Method 1: Remove a Key from a Dictionary using the del


The del keyword can be used to in-place delete the key that is present in the dictionary
in Python. One drawback that can be thought of using this is that it raises an exception if
the key is not found and hence non-existence of the key has to be handled. Demonstrating
key-value pair deletion using del.

Method 2: Remove a Key from a Dictionary using pop()


The pop() can be used to delete a key and its value inplace. The advantage over using del
is that it provides the mechanism to print desired value if tried to remove a non-existing
dict. pair. Second, it also returns the value of the key that is being removed in addition to
performing a simple delete operation. Demonstrating key-value pair deletion using pop()

Method 3: Using items() + dict comprehension to Remove a Key from a Dictionary


items() coupled with dict comprehension can also help us achieve the task of key-value
pair deletion but, it has the drawback of not being an in-place dict. technique. Actually, a
new dict is created except for the key we don’t wish to include. Demonstrating key-value
pair deletion using items() + dict comprehension.

Python Functions

A function is a block of code which only runs when it is called.You can pass data, known as
parameters, into a function.A function can return data as a result. Python functions are techniques
used to combine a set of statements within a program. Functions also let programmers compute a
result-value and give parameters that serve as function inputs that may change each time the code
runs. Functions prove to be a useful tool when the operations are coded in it and can be used in a
variety of scenarios.Functions are an alternative method of cutting-and-pasting codes rather than
typing redundant copies of the same instruction or operation, which further reduces the future work
for programmers. They are the most basic structure of a program, and so Python provides this
technique for code re-use. The keyword 'def' introduces a function definition. The statements that
form the body of the function starts from the next line of function definition and needs indentation.
The execution of the function introduces a new symbol table that is used for the function's local
variable. In other words, all the variables that are assigned to the function store their value in the
local symbol table. So global variables cannot be assigned with a value within a function; unless it is
named under 'global' statement. To accept any number of keyword arguments, the arguments have
to start with *. A * argument can appear only in the last position of function's argument. A fine
concept of a function definition is that arguments can still appear after the * argument.

Creating a Function

In Python a function is defined using the def keyword:

EG:

def my_function():
print("Hello from a function")

Calling a Function

To call a function, use the function name followed by parenthesis:

EG:def my_function():
print("Hello from a function")

my_function()
Arguments

Information can be passed into functions as 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:

EG:def my_function(fname):
print(fname + " Refsnes")

my_function("Emil")
my_function("Tobias")
my_function("Linus")

Number of Arguments

By default, a function must be called with the correct number of arguments. Meaning that if your
function expects 2 arguments, you have to call the function with 2 arguments, not more, and not
less.

EG:

This function expects 2 arguments, and gets 2 arguments:

def my_function(fname, lname):


print(fname + " " + lname)

my_function("Emil", "Refsnes")

If you try to call the function with 1 or 3 arguments, you will get an error:

EG:

This function expects 2 arguments, but gets only 1:

def my_function(fname, lname):


print(fname + " " + lname)

my_function("Emil")
Arbitrary Arguments, *args

If you do not know how many arguments that will be passed into your function, add a * before
the parameter name in the function definition.This way the function will receive a tuple of
arguments, and can access the items accordingly:

EG:If the number of arguments is unknown, add a * before the parameter name:

def my_function(*kids):
print("The youngest child is " + kids[2])

my_function("Emil", "Tobias", "Linus")

Arbitrary Arguments are often shortened to *args in Python documentations.

Keyword Arguments

You can also send arguments with the key = value syntax.

This way the order of the arguments does not matter.

Eg:
def my_function(child3, child2, child1):
print("The youngest child is " + child3)

my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")

The phrase Keyword Arguments are often shortened to kwargs in Python documentations.

Arbitrary Keyword Arguments, **kwargs

If you do not know how many keyword arguments that will be passed into your function, add
two asterisk: ** before the parameter name in the function definition.This way the function will
receive a dictionary of arguments, and can access the items accordingly:

Eg:If the number of keyword arguments is unknown, add a double ** before the parameter
name:

def my_function(**kid):
print("His last name is " + kid["lname"])

my_function(fname = "Tobias", lname = "Refsnes")


Arbitrary Kword Arguments are often shortened to **kwargs in Python documentations.

Return Values

To let a function return a value, use the return statement:

EG:

def my_function(x):
return 5 * x

print(my_function(3))
print(my_function(5))
print(my_function(9))

RECURSIVE FUNCTION

In Python, we know that a function can call other functions. It is even possible for
the function to call itself. These types of construct are termed as recursive
functions.
The following image shows the working of a recursive function called recurse .

1. Actual Parameters :
The arguments that are passed in a function call are called actual arguments. These arguments are
defined in the calling function. These are the variables or expressions referenced in the parameter
list of a subprogram call. There is no need to specify datatype in actual parameter.
Example :
// X and Y NUMBER ARE ACTUAL PARAMETERS
SQL> CREATE OR REPLACE FUNCTION FUNC1(X NUMBER,
Y NUMBER)
2 RETURN NUMBER IS
3 R NUMBER;
4 BEGIN
5 R:=X+Y;
6 RETURN(R);
7 END;
8 /
FUNCTION CREATED.

SQL>|
2. Formal Parameters :
These are the variables or expressions referenced in the parameter list of a subprogram
specification. The datatype of the receiving value must be defined. The scope of formal arguments
is local to the function definition in which they are used.
Example :
SQL> DECLARE
2 N1 NUMBER:=10;
3 N2 NUMBER:=20;
4 S NUMBER;
5 BEGIN
6 S:=FUNC1(N1, N2);
7 DBMS_OUTOUT.PUT_LINE('RESULT IS: '||S);
8 END;
9 /

OUTPUT: RESULT IS: 30


PL/SQL PROCEDURE SUCCESSFULLY COMPLETED.
SQL>|

Difference between Actual and Formal Parameters :


Actual Parameters Formal Parameters

When a function is called, the values The parameter used in function


(expressions) that are passed in the definition statement which contain data
function call are called the arguments or type on its time of declaration is called
actual parameters. formal parameter.

These are the variables or expressions These are the variables or expressions
referenced in the parameter list of a referenced in the parameter list of a
subprogram call. subprogram specification.

Actual Parameters are the parameters Formal Parameters are the parameters
which are in calling subprogram. which are in called subprogram.

There is no need to specify datatype in The datatype of the receiving value must
actual parameter. be defined.
Actual Parameters Formal Parameters

The parameters are written in function


The parameters are written in function
definition are known as formal
call are known as actual parameters.
parameters.

Formal Parameters can be treated as


Actual Parameters can be constant
local variables of a function in which
values or variable names.
they are used in the function header.
MODULE4
MODULES& PACKAGES

What is a Module?

Consider a module to be the same as a code library.A file containing a set of functions you want to
include in your application.

Create a Module

To create a module just save the code you want in a file with the file extension .py:

EG:Save this code in a file named mymodule.py

def greeting(name):
print("Hello, " + name)

Use a Module

Now we can use the module we just created, by using the import statement:

Example
Import the module named mymodule, and call the greeting function:

import mymodule

mymodule.greeting("Jonathan")

Note: When using a function from a module, use the syntax: module_name.function_name.

Variables in Module

The module can contain functions, as already described, but also variables of all types (arrays,
dictionaries, objects etc):

Example
Save this code in the file mymodule.py

person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}

Example
Import the module named mymodule, and access the person1 dictionary:
import mymodule

a = mymodule.person1["age"]
print(a)

Naming a Module

You can name the module file whatever you like, but it must have the file extension .py

Re-naming a Module

You can create an alias when you import a module, by using the as keyword:

Example
Create an alias for mymodule called mx:

import mymodule as mx

a = mx.person1["age"]
print(a)

Built-in Modules

There are several built-in modules in Python, which you can import whenever you like.

Example
Import and use the platform module:

import platform

x = platform.system()
print(x)

Using the dir() Function

There is a built-in function to list all the function names (or variable names) in a module.
The dir() function:

Example
List all the defined names belonging to the platform module:

import platform

x = dir(platform)
print(x)

Note: The dir() function can be used on all modules, also the ones you create yourself.
Import From Module

You can choose to import only parts from a module, by using the from keyword.

Example
The module named mymodule has one function and one dictionary:

def greeting(name):
print("Hello, " + name)

person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
Example

Import only the person1 dictionary from the module:

from mymodule import person1

print (person1["age"])

Locating the Modules in Python

When the modules are imported by the users, the Python interpreter will search for the module in
the current directory. If the module is not found in the directory, the interpreter will search every
directory present in the shell variable known as PYTHONPATH. If the interpreter is unable to find it in
the shell, then it will check the default path. In UNIX, this default path is: /usr/local/lib/python/.The
search path of the module is stored in the system module sys as the sys.path variable. This variable
contains the current directory, that is, PYTHONPATH, and the installation-dependent default.

Namespaces and Scope in Python


What is namespace: 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 .

Types of namespaces :

When Python interpreter runs solely without any user-defined modules, methods, classes, etc.
Some functions like print(), id() are always present, these are built-in namespaces. When a user
creates a module, a global namespace gets created, later the creation of local functions creates
the local namespace. The built-in namespace encompasses the global namespace and the global
namespace encompasses the local namespace.
The built-in namespace: contains the names of all of Python’s built-in objects. These are
available at all times when Python is running.
The Global Namespace

The global namespace contains any names defined at the level of the main program. Python creates
the global namespace when the main program body starts, and it remains in existence until the
interpreter terminates.Strictly speaking, this may not be the only global namespace that exists. The
interpreter also creates a global namespace for any module that your program loads with
the import statement.

The Local and Enclosing Namespaces

As you learned in the previous tutorial on functions, the interpreter creates a new namespace
whenever a function executes. That namespace is local to the function and remains in existence until
the function terminates.

The lifetime of a namespace :

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.

Variable Scope
The existence of multiple, distinct namespaces means several different instances of a particular
name can exist simultaneously while a Python program runs. As long as each instance is in a
different namespace, they’re all maintained separately and won’t interfere with one another.
The scope of a name is the region of a program in which that name has meaning. The interpreter
determines this at runtime based on where the name definition occurs and where in the code the
name is referenced.

Python Packages
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. The same analogy
is followed by the packages in Python.
What is a Python Package?
Python modules may contain several classes, functions, variables, etc. whereas Python packages
contain several modules. In simpler terms, Package in Python is a folder that contains various
modules as files.

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:

 Create a folder named mypckg.


 Inside this folder create an empty Python file i.e. __init__.py
 Then create two modules mod1 and mod2 in this folder.

Mod1.py

Mod1.py
def gfg():
print("Welcome to GFG")

Mod2.py

def sum(a, b):


return a+b

Understanding __init__.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

from .mod1 import gfg


from .mod2 import sum

This __init__.py will only allow the gfg and sum functions from the mod1 and mod2 modules to be
imported.

Import Modules from a Package

We can import these Python modules using the from…import statement and the dot(.) operator.

Syntax:

import package_name.module_name
Example 1:

We will import the modules from the above-created package and will use the functions inside those
modules.

from mypckg import mod1


from mypckg import mod2
mod1.gfg()
res = mod2.sum(1, 2)
print(res)

Python datetime module


In Python, date and time are not data types of their own, but a module named DateTime can be
imported to work with the date as well as time. Python Datetime module comes built into Python,
so there is no need to install it externally.

Python DateTime module


Python Datetime module supplies classes to work with date and time. These classes provide a
number of functions to deal with dates, times, and time intervals. Date and DateTime are an object
in Python, so when you manipulate them, you are actually manipulating objects and not strings or
timestamps.

The DateTime module is categorized into 6 main classes –

 date – An idealized naive date, assuming the current Gregorian calendar always was, and always
will be, in effect. Its attributes are year, month, and day.
 time – An idealized time, independent of any particular day, assuming that every day has exactly
24*60*60 seconds. Its attributes are hour, minute, second, microsecond, and tzinfo.
 datetime – Its a combination of date and time along with the attributes year, month, day, hour,
minute, second, microsecond, and tzinfo.
 timedelta – A duration expressing the difference between two date, time, or datetime instances
to microsecond resolution.
 tzinfo – It provides time zone information objects.
 timezone – A class that implements the tzinfo abstract base class as a fixed offset from the UTC
(New in version 3.2).

Python Date Class


The date class is used to instantiate date objects in Python. When an object of this class is
instantiated, it represents a date in the format YYYY-MM-DD. The constructor of this class needs
three mandatory arguments year, month, and date.

Python Date class Syntax:class datetime.date(year, month, day)

The arguments must be in the following range –

 MINYEAR <= year <= MAXYEAR


 1 <= month <= 12
 1 <= day <= number of days in the given month and year
Note – If the argument is not an integer it will raise a TypeError and if it is outside the range a
ValueError will be raised.

Date object representing data in Python

Initializing the constructor and passing arguments in the format year, month, and date.

# Python program to

# demonstrate date class

# import the date class

from datetime import date

my_date = date(1996, 12, 11)

print("Date passed as argument is", my_date)

# Uncommenting my_date = date(1996, 12, 39)

# will raise an ValueError as it is

# outside range

# uncommenting my_date = date('1996', 12, 11)

# will raise a TypeError as a string is

# passed instead of integer

Get the Current Date

To return the current local date today() function of the date class is used. today() function comes
with several attributes (year, month, and day). These can be printed individually.

# Python program to
# print current date
from datetime import date
# calling the today
# function of date class
today = date.today()
print("Today's date is", today)

Get Today’s Year, Month, and Date

We can get the year, month, and date attributes from the date object using the year, month and
date attribute of the date class. from datetime import date
# date object of today's date
today = date.today()
print("Current year:", today.year)
print("Current month:", today.month)
print("Current day:", today.day)

Get Date from Timestamp

We can create date objects from timestamps y=using the fromtimestamp() method. The timestamp
is the number of seconds from 1st January 1970 at UTC to a particular date.

from datetime import datetime


# Getting Datetime from timestamp
date_time = datetime.fromtimestamp(1887639468)
print("Datetime from timestamp:", date_time)

Convert Date to String

We can convert date object to a string representation using two functions isoformat() and strftime().

from datetime import date


# calling the today
# function of date class
today = date.today()
# Converting the date to the string
Str = date.isoformat(today)
print("String Representation", Str)
print(type(Str))

List of Date Class Methods

Function Name Description

ctime() Return a string representing the date

fromisocalendar() Returns a date corresponding to the ISO calendar

fromisoformat() Returns a date object from the string representation of the date

Returns a date object from the proleptic Gregorian ordinal, where January
fromordinal()
1 of year 1 has ordinal 1
Function Name Description

fromtimestamp() Returns a date object from the POSIX timestamp

isocalendar() Returns a tuple year, week, and weekday

isoformat() Returns the string representation of the date

isoweekday() Returns the day of the week as an integer where Monday is 1 and Sunday is 7

replace() Changes the value of the date object with the given parameter

strftime() Returns a string representation of the date with the given format

timetuple() Returns an object of type time.struct_time

today() Returns the current local date

Return the proleptic Gregorian ordinal of the date, where January 1 of year
toordinal()
1 has ordinal 1

weekday() Returns the day of the week as integer where Monday is 0 and Sunday is 6

Python Time class


The time class creates the time object which represents local time, independent of any day.

Constructor Syntax:class datetime.time(hour=0, minute=0, second=0, microsecond=0,


tzinfo=None, *, fold=0)

All the arguments are optional. tzinfo can be None otherwise all the attributes must be integer in the
following range –

 0 <= hour < 24


 0 <= minute < 60
 0 <= second < 60
 0 <= microsecond < 1000000
 fold in [0, 1]

List of Time class Methods

Description
Function Name

dst() Returns tzinfo.dst() is tzinfo is not None

fromisoformat() Returns a time object from the string representation of the time
Description
Function Name

isoformat() Returns the string representation of time from the time object

replace() Changes the value of the time object with the given parameter

strftime() Returns a string representation of the time with the given format

tzname() Returns tzinfo.tzname() is tzinfo is not None

utcoffset() Returns tzinfo.utcffsets() is tzinfo is not None

Python Datetime class


The DateTime class contains information on both date and time. Like a date object, datetime
assumes the current Gregorian calendar extended in both directions; like a time object, datetime
assumes there are exactly 3600*24 seconds in every day.

Constructor Syntax: class datetime.datetime(year, month, day, hour=0, minute=0, second=0,


microsecond=0, tzinfo=None, *, fold=0)

The year, month, and day arguments are mandatory. tzinfo can be None, rest all the attributes must
be an integer in the following range –

 MINYEAR <= year <= MAXYEAR


 1 <= month <= 12
 1 <= day <= number of days in the given month and year
 0 <= hour < 24
 0 <= minute < 60
 0 <= second < 60
 0 <= microsecond < 1000000
 fold in [0, 1]

Note – Passing an argument other than integer will raise a TypeError and passing arguments outside
the range will raise ValueError.

DateTime object representing DateTime in Python

Current date and time

You can print the current date and time using the Datetime.now() function. now() function returns
the current local date and time.
Convert Python Datetime to String

We can convert Datetime to string in Python using the datetime.strftime and datetime.isoformat
methods.

List of Datetime Class Methods

Function Name Description

astimezone() Returns the DateTime object containing timezone information.

combine() Combines the date and time objects and return a DateTime object

ctime() Returns a string representation of date and time

date() Return the Date class object

fromisoformat() Returns a datetime object from the string representation of the date and time

Returns a date object from the proleptic Gregorian ordinal, where January 1 of
fromordinal()
year 1 has ordinal 1. The hour, minute, second, and microsecond are 0

fromtimestamp() Return date and time from POSIX timestamp

isocalendar() Returns a tuple year, week, and weekday

isoformat() Return the string representation of date and time

isoweekday() Returns the day of the week as integer where Monday is 1 and Sunday is 7

now() Returns current local date and time with tz parameter

replace() Changes the specific attributes of the DateTime object

strftime() Returns a string representation of the DateTime object with the given format

strptime() Returns a DateTime object corresponding to the date string

time() Return the Time class object

timetuple() Returns an object of type time.struct_time

timetz() Return the Time class object

today() Return local DateTime with tzinfo as None

Return the proleptic Gregorian ordinal of the date, where January 1 of year 1
toordinal()
has ordinal 1
Function Name Description

tzname() Returns the name of the timezone

utcfromtimestamp() Return UTC from POSIX timestamp

utcoffset() Returns the UTC offset

utcnow() Return current UTC date and time

weekday() Returns the day of the week as integer where Monday is 0 and Sunday is 6

Python Timedelta Class


Python timedelta class is used for calculating differences in dates and also can be used for date
manipulations in Python. It is one of the easiest ways to perform date manipulations.

Constructor syntax:

class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0,


weeks=0)
Returns : Date

Add days to DateTime object

The timedelta function demonstration

Difference between two date and times

Date and Time differences can also be found using this class.

Operations supported by Timedelta Class

Operator Description

Addition (+) Adds and returns two timedelta objects

Subtraction (-) Subtracts and returns two timedelta objects

Multiplication
Multiplies timedelta object with float or int
(*)

Division (/) Divides the timedelta object with float or int

Floor division Divides the timedelta object with float or int and return the int of floor value of the
(//) output

Modulo (%) Divides two timedelta object and returns the remainder
Operator Description

+(timedelta) Returns the same timedelta object

-(timedelta) Returns the resultant of -1*timedelta

abs(timedelta) Returns the +(timedelta) if timedelta.days > 1=0 else returns -(timedelta)

str(timedelta) Returns a string in the form (+/-) day[s], HH:MM:SS.UUUUUU

repr(timedelta) Returns the string representation in the form of the constructor call

Format DateTime in Python

Formatting DateTime can be very necessary as the date representation may differ from place to
place. In some countries, it can be yyyy-mm-dd and in other countries, it can be dd-mm-yyyy. To
format Python Datetime strptime and strftime functions can be used.

Python Datetime strftime

A strftime() method converts the given date, time, or DateTime object to the string representation
of the given format.

Python Datetime format

Python program to demonstrate strftime() function

Python DateTime strptime

The strptime() creates a DateTime object from the given string.

Python DateTime.tzinfo()
The datetime.now() function contains no information regarding time zones. It only makes use of the
current system time. Tzinfo is an abstract base class in Python. It cannot be directly instantiated. A
concrete subclass must derive from this abstract class and implement the methods offered by it.

List of Python DateTime.tzinfo() Objects

Function Name Description

dst() Returns tzinfo.dst() is tzinfo is not None

The purpose of this function is to adjust the date time data,


fromutc()
returning an equivalent DateTime in self’s local time.

tzname() Returns tzinfo.tzname() is tzinfo is not None


Function Name Description

utcoffset() Returns tzinfo.utcffsets() is tzinfo is not None

Example

The tzinfo class instance can be provided to the DateTime and time object constructors. It is used in
scenarios such as converting local time to UTC or accounting for daylight savings time.

import datetime as dt
from dateutil import tz
tz_string = dt.datetime.now(dt.timezone.utc).astimezone().tzname()
print("datetime.now() :", tz_string)
NYC = tz.gettz('Europe / Berlin')
dt1 = dt.datetime(2022, 5, 21, 12, 0)
dt2 = dt.datetime(2022, 12, 21, 12, 0, tzinfo=NYC)
print("Naive Object :", dt1.tzname())
print("Aware Object :", dt2.tzname())

Python DateTime timezone

Timezones in DateTime can be used in the case where one might want to display time according to
the timezone of a specific region. This can be done using the pytz module of Python. This module
serves the date-time conversion functionalities and helps users serving international client bases.

from datetime import datetime


from pytz import timezone
format = "%Y-%m-%d %H:%M:%S %Z%z"
# Current time in UTC
now_utc = datetime.now(timezone('UTC'))
print(now_utc.strftime(format))
timezones = ['Asia/Kolkata', 'Europe/Kiev', 'America/New_York']
for tzone in timezones:
# Convert to Asia/Kolkata time zone
now_asia = now_utc.astimezone(timezone(tzone))
print(now_asia.strftime(format))

Turtle Programming in Python


Turtle” is a Python feature like a drawing board, which lets us command a turtle to draw all over
it! We can use functions like turtle.forward(…) and turtle.right(…) which can move the turtle
around. Commonly used turtle methods are :

Method Parameter Description

Turtle() None Creates and returns a new turtle object


Method Parameter Description

forward() amount Moves the turtle forward by the specified amount

backward() amount Moves the turtle backward by the specified amount

right() angle Turns the turtle clockwise

left() angle Turns the turtle counterclockwise

penup() None Picks up the turtle’s Pen

pendown() None Puts down the turtle’s Pen

up() None Picks up the turtle’s Pen

down() None Puts down the turtle’s Pen

color() Color name Changes the color of the turtle’s pen

fillcolor() Color name Changes the color of the turtle will use to fill a polygon

heading() None Returns the current heading

position() None Returns the current position

goto() x, y Move the turtle to position x,y

begin_fill() None Remember the starting point for a filled polygon

end_fill() None Close the polygon and fill with the current fill color

dot() None Leave the dot at the current position

stamp() None Leaves an impression of a turtle shape at the current location

shape() shapename Should be ‘arrow’, ‘classic’, ‘turtle’ or ‘circle’


Plotting using Turtle
To make use of the turtle methods and functionalities, we need to import turtle.”turtle” comes
packed with the standard Python package and need not be installed externally. The roadmap for
executing a turtle program follows 4 steps:
1. Import the turtle module
2. Create a turtle to control.
3. Draw around using the turtle methods.
4. Run turtle.done().
from turtle import *
# or
import turtle

After importing the turtle library and making all the turtle functionalities available to us, we need
to create a new drawing board(window) and a turtle. Let’s call the window as wn and the turtle as
skk. So we code as:

wn = turtle.Screen()
wn.bgcolor("light green")
wn.title("Turtle")
skk = turtle.Turtle()

Now that we have created the window and the turtle, we need to move the turtle. To move
forward 100 pixels in the direction skk is facing, we code:
skk.forward(100)
We have moved skk 100 pixels forward, Awesome! Now we complete the program with the done()
function and We’re done!
turtle.done()
So, we have created a program that draws a line 100 pixels long. We can draw various shapes and
fill different colors using turtle methods. There’s plethora of functions and programs to be coded
using the turtle library in python. Let’s learn to draw some of the basic shapes.

Shape 1: Square

# Python program to draw square


# using Turtle Programming
import turtle
skk = turtle.Turtle()

for i in range(4):
skk.forward(50)
skk.right(90)

turtle.done()

Output:
Shape 2: Star

# Python program to draw star


# using Turtle Programming
import turtle
star = turtle.Turtle()

star.right(75)
star.forward(100)

for i in range(4):
star.right(144)
star.forward(100)

turtle.done()

Output:

Shape 3: Hexagon

# Python program to draw hexagon


# using Turtle Programming
import turtle
polygon = turtle.Turtle()

num_sides = 6
side_length = 70
angle = 360.0 / num_sides

for i in range(num_sides):
polygon.forward(side_length)
polygon.right(angle)

turtle.done()

Output:
Shape 4: parallelogram

import turtle

# Initialize the turtle


t = turtle.Turtle()

# Set the turtle's speed


t.speed(1)

# Draw the parallelogram


for i in range(2):
t.forward(100)
t.left(60)
t.forward(50)
t.left(120)

Output:

Shape 5 : Circle

import turtle

# Set up the turtle screen and set the background color to white
screen = turtle.Screen()
screen.bgcolor("white")

# Create a new turtle and set its speed to the fastest possible
pen = turtle.Turtle()
pen.speed(0)

# Set the fill color to red


pen.fillcolor("red")
pen.begin_fill()

# Draw the circle with a radius of 100 pixels


pen.circle(100)

# End the fill and stop drawing


pen.end_fill()
pen.hideturtle()

# Keep the turtle window open until it is manually closed


turtle.done()

Draw Color Filled Shapes in Turtle – Python

turtle is an inbuilt module in python. It provides drawing using a screen (cardboard) and turtle (pen).
To draw something on the screen, we need to move the turtle. To move turtle, there are some
functions i.e forward(), backward(), etc.

To fill the colors in the shapes drawn by turtle, turtle provides three functions –

fillcolor(): This helps to choose the color for filling the shape. It takes the input parameter as the
color name or hex value of the color and fills the upcoming closed geographical objects with the
chosen color. Color names are basic color names i.e. red, blue, green, orange.The hex value of color
is a string(starting with ‘#’) of hexadecimal numbers i.e. #RRGGBB. R, G, and B are the hexadecimal
numbers (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F).

begin_fill(): This function tells turtle that all upcoming closed graphical objects needed to be filled by
the chosen color.

end_fill(): this function tells turtle to stop the filling upcoming closed graphical objects.

Drawing Color Filled Square:

# draw color-filled square in turtle

import turtle

# creating turtle pen


t = turtle.Turtle()

# taking input for the side of the square


s = int(input("Enter the length of the side of the square: "))

# taking the input for the color


col = input("Enter the color name or hex value of color(# RRGGBB): ")

# set the fillcolor


t.fillcolor(col)

# start the filling color


t.begin_fill()

# drawing the square of side s


for _ in range(4):
t.forward(s)
t.right(90)

# ending the filling of the color


t.end_fill()
Input :

200

Drawing Color Filled Triangle:

# draw color filled triangle in turtle

import turtle

# creating turtle pen

t = turtle.Turtle()

# taking input for the side of the triangle

s = int(input("Enter the length of the side of the triangle: "))

# taking the input for the color

col = input("Enter the color name or hex value of color(# RRGGBB): ")

# set the fillcolor

t.fillcolor(col)

# start the filling color

t.begin_fill()

# drawing the triangle of side s


for _ in range(3):

t.forward(s)

t.right(-120)

# ending the filling of the color

t.end_fill()

Drawing Color Filled Hexagon:

# draw color-filled hexagon in turtle

import turtle

# creating turtle pen

t = turtle.Turtle()

# taking input for the side of the hexagon

s = int(input("Enter the length of the side of the hexagon: "))

# taking the input for the color

col = input("Enter the color name or hex value of color(# RRGGBB): ")

# set the fillcolor

t.fillcolor(col)

# start the filling color

t.begin_fill()

# drawing the hexagon of side s

for _ in range(6):

t.forward(s)

t.right(-60)

# ending the filling of the color

t.end_fill()

Input :
100

#113300

Draw Shape inside Shape in Python Using Turtle

Turtle is a Python feature like a drawing board, which let us command a turtle to draw all over it!
We can use many turtle functions which can move the turtle around. Turtle comes in the turtle
library. The turtle module can be used in both object-oriented and procedure-oriented ways.
Some of the commonly used methods which are also used here are:
 forward(length): moves the pen in the forward direction by x unit.
 backward(length): moves the pen in the backward direction by x unit.
 right(angle): rotate the pen in the clockwise direction by an angle x.
 left(angle): rotate the pen in the anticlockwise direction by an angle x.
 penup(): stop drawing of the turtle pen.
 pendown(): start drawing of the turtle pen.
In this article, we will draw various shape inside a similar shape like drawing triangles inside
triangle.
Triangle inside Triangle
Follow the below steps:
 Define an instance for turtle.
 For a square execute a loop 3 times (sides).
 In every iteration move turtle 120 units forward.
 This will make up a Triangle.
 This is made multiple times to form triangles inside the triangle using a function.
Below is the python implementation.

# import the turtle modules

import turtle

# define the function

# for triangle

def form_tri(side):

for i in range(3):

my_pen.fd(side)
my_pen.left(120)

side -= 10

# Forming the window screen

tut = turtle.Screen()

tut.bgcolor("green")

tut.title("Turtle")

my_pen = turtle.Turtle()

my_pen.color("orange")

tut = turtle.Screen()

# for different shapes

side = 300

for i in range(10):

form_tri(side)

side -= 30

Square inside Square

Follow the below steps:


 Define an instance for turtle.
 For a square execute a loop 4 times (sides).
 In every iteration move turtle 90 units forward.
 This will make up a Square.
 This is made multiple times to form squares inside squares using a function.
Below is the python implementation.
Hexagon inside Hexagon

Follow the below steps:


 Define an instance for turtle.
 For a hexagon execute a loop 6 times (sides).
 In every iteration move turtle 300 units forward.
 This will make up a Hexagon.
 This is made multiple times to form hexagons inside the hexagon using a function.
Below is the python implementation.

Image Formats
Image Format describes how data related to the image will be stored. Data can be stored in
compressed, Uncompressed, or vector format. Each format of the image has a different advantage
and disadvantage. Image types such as TIFF are good for printing while JPG or PNG, are best for
the web.
 TIFF(.tif, .tiff) Tagged Image File Format this format store image data without losing any data.
It does not perform any compression on images, and a high-quality image is obtained but the
size of the image is also large, which is good for printing, and professional printing.
 JPEG (.jpg, .jpeg) Joint Photographic Experts Group is a loss-prone (lossy) format in which data
is lost to reduce the size of the image. Due to compression, some data is lost but that loss is
very less. It is a very common format and is good for digital cameras, nonprofessional prints, E-
Mail, Powerpoint, etc., making it ideal for web use.
 GIF (.gif) GIF or Graphics Interchange Format files are used for web graphics. They can be
animated and are limited to only 256 colors, which can allow for transparency. GIF files are
typically small in size and are portable.
 PNG (.png) PNG or Portable Network Graphics files are a lossless image format. It was
designed to replace gif format as gif supported 256 colors unlike PNG which support 16 million
colors.
 Bitmap (.bmp) Bit Map Image file is developed by Microsoft for windows. It is same as TIFF
due to lossless, no compression property. Due to BMP being a proprietary format, it is
generally recommended to use TIFF files.
 EPS (.eps) Encapsulated PostScript file is a common vector file type. EPS files can be opened in
applications such as Adobe Illustrator or CorelDRAW.
 RAW Image Files (.raw, .cr2, .nef, .orf, .sr2) These Files are unprocessed and created by a
camera or scanner. Many digital SLR cameras can shoot in RAW, whether it be a .raw, .cr2, or
.nef. These images are the equivalent of a digital negative, meaning that they hold a lot of
image information. These images need to be processed in an editor such as Adobe Photoshop
or Lightroom. It saves metadata and is used for photography.
What is meant by image saved with transparency? Images saved with transparency look good on
colored background whereas images without transparency will have a white background which
will be visible on colored background.
Python Image Manipulation Tools
The world of today is brimming with data, and images are the bulk of this data. But in order
to be utilized in any way, the digital images need to be processed and analysed to enhance
the quality of their images or gain information that could be utilized.

Common image processing tasks comprise display; simple manipulations such as flipping,
cropping, etc. Image segmentation, feature extractions, classification images restoration,
also image recognition. Python is a great option for these kinds of tasks in image processing
because of its rising popularity as a science-based programming language, as well as the
open access to a variety of state-of-the-art image processing tools within its library.

This article examines the top 10 most frequently utilized Python libraries to perform image
manipulation tasks. These libraries offer a simple and intuitive method to alter images and
comprehend the data behind them.

1. scikit-image

Scikit-image can be described as an open-source Python program that uses NumPy arrays. It is a tool
for implementing algorithms and utilities that can be used in research, education as well as industrial
applications. It's an easy and simple library, even for those unfamiliar with the Python ecosystem.
The code is of high-quality that and has been peer-reviewed and written by a large group of
volunteers.

Resources

Scikit-image is thoroughly explained with plenty of examples and real-world use instances.

Usage

It is loaded in the skimage, and the majority of functions are contained in submodules.

1. import matplotlib.pyplot as mplot


2. %matplotlib inline
3.
4. from skimage import data
5. from skimage import filters
6.
7. image1 = data.coins() # ... or any other NumPy array!
8. edges1 = filters.sobel(image)
9. mplot.imshow(edges, cmap = 'gray')

2.NumPy
NumPy is one of the most important libraries used in Python programming. It also supports arrays.
An image is essentially an array of NumPy that is standard and contains the pixels that makeup data.
Thus, by using standard NumPy techniques, like cutting, masking, or fancy indexing, it is possible to
alter the pixel values in an image. It can also be loaded with the skimage program and displayed with
Matplotlib.

Usage

Use Numpy to mask images:

import numpy as nmp


from skimage import data
import matplotlib.pyplot as mplot
%matplotlib inline

image1 = data.camera()
type(image1)
nmp.ndarray
#Image is a NumPy array:

mask = image < 87


image[mask] = 255
mplot.imshow(image1, cmap ='gray')

3. SciPy

SciPy SciPy is another one of Python's primary science modules (like NumPy) and can be utilized to
perform basic operations on images and for processing. Particularly it is a submodule called
scipy.ndimage (in SciPy v1.1.0) that provides functions that operate on the n-dimensional NumPy
arrays. The package is currently stocked with functions for non-linear and linear filtering, B-spline
interpolation, binary morphology as well as the measurement of objects.

Usage

Make use of SciPy to blur the image by using a Gaussian filter:

4. PIL/Pillow
PIL (Python Imaging Library) is a library that is free for Python. It is a library for Python programming
language that provides support for opening, manipulating and saving various formats for images.
However, its development has slowed, and its last release was in 2009. There is, however, an
alternative, Pillow, which is an actively developed alternative to PIL, which is simpler to install, works
on all the major platforms, and also supports Python 3. The library provides basic image processing
functions that include points, filters, the convolution kernels built-in, as well as colour space
conversions.

Usage

Enhancing images by putting them in a Pillow by using ImageFilter


5. OpenCV-Python
The OpenCV (Open Source Computer Vision Library) is among the most frequently used programs
for computers using computer vision. OpenCV-Python is the Python API for OpenCV. OpenCV-Python
isn't only efficient because the background is composed of code that is written using C/C++.
However, it is also simple to program and implement (due to the Python wrapper, which is present
in the foreground). This makes it an excellent choice for running computationally intensive computer
vision applications.

Usage

Making use of Blending of Images using Pyramids within OpenCV Python, you can create the
"Orapple":

6. SimpleCV
SimpleCV is a different open-source framework for creating applications for computer vision. It
provides access to a variety of powerful computer vision software libraries like OpenCV, but you
don't need to know bit depths and colour spaces, file formats, as well as colour spaces. The learning
curve of SimpleCV is significantly less than that of OpenCV and (as its tagline states), "its computer
vision made easy." A few advantages of SimpleCV include:

Even novice programmers can write basic machine vision tests.


Cameras, video files, videos, and images are all interoperable.

7. Mahotas

Mahotas can be described as yet another software for image and computer vision available for
Python. It has traditional image processing tools like filtering and morphological processes in
addition to modern computer vision tools for feature computation, including interest point
detection and local descriptors. The interface is Python which is suitable for development speed.
However, the algorithms are written using C++ and tuned to speed. Mahotas library is extremely
fast, with minimal code and minimal dependencies. Read the official publication to gain more
insight.

Resources

This documentation includes installation instructions as well as examples and some guides to help
you start using Mahotas quickly.

Usage

The Mahotas library relies on simple code to complete tasks. For instance, it does an excellent job of
solving the finding Wally problem, using only a small quantity of programming.
8. SimpleITK
ITK (Insight Segmentation and Registration Toolkit) is "open-source, cross-platform software that
offers developers an extensive collection of tools to aid in the analysis of images. SimpleITK is an
esoteric layer built on the top of ITK designed to ease quick prototyping and education and
[andinterpreters." The toolkit also includes image analysis, with various components supporting
general filtering functions such as image segmentation, image filtering, and registration. SimpleITK
was written in C++, but it's compatible with a vast number of programming languages like Python.

Resources

There are many Jupyter Notebooks showing how SimpleITK can be used in research and education.
Notebooks show how to use SimpleITK to perform interactive image analysis with it Python as well
as R Programming languages.

Usage

Visualization of a strict CT/MR registration procedure created with Python and SimpleITK. Python:

9. pgmagick

The pgmagick is a Python-based wrapper that is compatible with the GraphicsMagick


library. It is the GraphicsMagick imaging processing system is often described as"the Swiss
Army Knife in the field of processing images. Its reliable and powerful collection of libraries
and tools allows reading, writing and manipulating images in more than 88 formats, which
include DPX, GIF, JPEG, JPEG-2000, PNG, PDF, PNM, and TIFF.

Resources

Pgmagick's GitHub repository includes installation instructions as well as specifications. It


also has a comprehensive user guide.

10. Pycairo

Pycairo Pycairo HTML0 is an array of Python bindings for the Cairo graphics library. Cairo is
a 2D graphics library that allows the creation of vector graphics. Vector graphics are
attractive since they don't lose clarity when resized or altered. Pycairo can invoke Cairo
commands using Python.

Resources

Its Pycairo GitHub repository is a useful resource that provides detailed instructions
regarding installation and use. It also has a starting guide that includes an overview of
Pycairo.

Usage

The drawing of lines and basic forms and radial gradients using Pycairo:
MODULE 5

File Operations:Python | Reading .ini Configuration Files

This article aims to read configuration files written in the common .ini configuration file format.
The configparser module can be used to read configuration files.
Code #1 : Configuration File

abc.ini ;
Sample configuration file
[installation]
library = %(prefix)s/lib
include = %(prefix)s/include
bin = %(prefix)s/bin
prefix = /usr/local
# Setting related to debug configuration
[debug]
pid-file = /tmp/spam.pid
show_warnings = False
log_errors = true
[server]
nworkers: 32
port: 8080
root = /www/root
signature:

Code #2 : Reading the file and extracting values.

from configparser import ConfigParser


configur = ConfigParser()
print (configur.read('config.ini'))
print ("Sections : ", configur.sections())
print ("Installation Library : ", configur.get('installation','library'))
print ("Log Errors debugged ? : ", configur.getboolean('debug','log_errors'))
print ("Port Server : ", configur.getint('server','port'))
print ("Worker Server : ", configur.getint('server','nworkers'))

Output :
['config.ini']
Sections : ['installation', 'debug', 'server']
Installation Library : '/usr/local/lib'
Log Errors debugged ? : True
Port Server : 8080
Worker Server : 32
One can also modify the configuration and write it back to a file using the cfg.write() method.
 Configuration files are well suited to specify configuration data to your program. Within each
config file, values are grouped into different sections (e.g., “installation”, “debug” and
“server”).
 Each section then has a specific value for various variables in that section. For the same
purpose, there are some prominent differences between a config file and using a Python
source file.
 First, the syntax is much more permissive and “sloppy.”
Names used in a config file are also assumed to be case-insensitive as shown in the code below –

configur.get('installation','PREFIX')
configur.get('installation','prefix')

When parsing values, methods such as getboolean() look for any reasonable value. For example,
these are all equivalent.
log_errors = true
log_errors = TRUE
log_errors = Yes
log_errors = 1
The most noteworthy contrast between a config record and Python code is that, in contrast to
scripts, configuration files are not executed in a top-down way. Rather, the file is read completely.
On the off chance that variable substitutions are made, they are done later after the fact. For
instance, it doesn’t make a difference that the prefix variable is allocated after different variables
that happen to utilize it.
[installation]
library = %(prefix)s/lib
include = %(prefix)s/include
bin = %(prefix)s/bin
prefix = /usr/local
Multiple configuration files can be read together and their results can be merged into a single
configuration using ConfigParser, which makes it so special to use.
Example – A user made their own configuration file that looks as.
; ~/.config.ini
[installation]
prefix = /Users/beazley/test
[debug]
log_errors = False
This file can be merged with the previous configuration by reading it separately
How To Write Logs To A File With Python?
You can use basic config. If you configure the attribute filename, logs will be automatically saved to
the file you specify. You can also configure the attribute filemode. Setting the value to w will
overwrite the file after every entry.

import logging
logging.basicConfig(filename="logs.log", filemode="w", format="%(name)s → %(levelname)s:
%(message)s")
logging.warning("warning")

OUTPUT
root → WARNING: warning

Using Provided Classes

You can also use the provided classes - loggers and handlers:

logger = logging.getLogger(__name__)
FileOutputHandler = logging.FileHandler('logs.log')
logger.addHandler(FileOutputHandler)
logger.warning("Warning.")

You will create a logger and a handler. When creating a handler, assign the class FileHandler and a
file name as an attribute. Then set the handler to a logger:

Output

Warning.
Python File Operations - Read and Write to files with Python

WORKING WITH FILES IN PYTHON

In the previous tutorial, we used console to take input. Now, we will be taking input using a file. That
means, we will read from and write into files. To do so, we need to maintain some steps. Those are
1. Open a file
2. Take input from that file / Write output to that file
3. Close the file

We will also learn some useful operations such as copy file and delete file.

Why are file operations in Python needed?


When working with large datasets in machine learning problems, working with files is a basic
necessity. Since Python is a majorly used language for data science, you need to be proficient with
the different file operations that Python offers.

So, let’s explore some of the Python file operations here.

1. Open a file in Python with the open() function


The first step to working with files in Python is to learn how to open a file. You can open files using
the open() method.

The open() function in Python accepts two arguments. The first one is the file name along with the
complete path and the second one is the file open mode.

Below, I’ve listed some of the common reading modes for files:
 ‘r’ : This mode indicate that file will be open for reading only
 ‘w’ : This mode indicate that file will be open for writing only. If file containing containing that name
does not exists, it will create a new one
 ‘a’ : This mode indicate that the output of that program will be append to the previous output of
that file
 ‘r+’ : This mode indicate that file will be open for both reading and writing

Additionally, for the Windows operating system, you can append ‘b’ for accessing the file in binary.
This is is because Windows differentiates between a binary text file and a regular text file.

Suppose, we place a text file name ‘file.txt’ in the same directory where our code is placed. Now we
want to open that file.However, the open(filename, mode) function returns a file object. With that
file object you can proceed your further operation.

#directory: /home/imtiaz/code.py
text_file = open('file.txt','r')

#Another method using full location


text_file2 = open('/home/imtiaz/file.txt','r')
print('First Method')
print(text_file)

print('Second Method')
print(text_file2)

Copy

The output of the following code will be

================== RESTART: /home/imtiaz/code.py ==================


First Method

Second Method

>>>
Copy

2. Read and write to files in Python

Python offers various methods to read and write to files where each functions behaves differently.
One important thing to note is the file operations mode. To read a file, you need to open the file in
the read or write mode. While to write to a file in Python, you need the file to be open in write
mode.

Here are some of the functions in Python that allow you to read and write to files:
 read() : This function reads the entire file and returns a string
 readline() : This function reads lines from that file and returns as a string. It fetch the line n, if it is
been called nth time.
 readlines() : This function returns a list where each element is single line of that file.
 readlines() : This function returns a list where each element is single line of that file.
 write() : This function writes a fixed sequence of characters to a file.
 writelines() : This function writes a list of string.
 append() : This function append string to the file instead of overwriting the file.
Let’s take an example file “abc.txt”, and read individual lines from the file with a for loop:
#open the file
text_file = open('/Users/pankaj/abc.txt','r')

#get the list of line


line_list = text_file.readlines();

#for each line from the list, print the line


for line in line_list:
print(line)

text_file.close() #don't forget to close the file


Copy
Output:

Now, that we know how to read a file in Python, let’s move ahead and perform a write operation
here with the writelines() function.

#open the file


text_file = open('/Users/pankaj/file.txt','w')

#initialize an empty list


word_list= []

#iterate 4 times
for i in range (1, 5):
print("Please enter data: ")
line = input() #take input
word_list.append(line) #append to the list

text_file.writelines(word_list) #write 4 words to the file

text_file.close() #don’t forget to close the file


Copy

Output

3. Copy files in Python using the shutil() method

We can use the shutil module to copy files in Python. This utility allows us to perform copy and
move operations in Python on different files. Let’s work on this with an example:
import shutil

shutil.copy2('/Users/pankaj/abc.txt', '/Users/pankaj/abc_copy2.txt')

#another way to copy file

shutil.copyfile('/Users/pankaj/abc.txt', '/Users/pankaj/abc_copyfile.txt')

print("File Copy Done")

Copy

4. Delete files in Python with the shutil.os.remove() method

Python’s shutil module offers the remove() method to delete files from the file system. Let’s take a
look at how we can perform a delete operation in Python.

import shutil
import os

#two ways to delete file


shutil.os.remove('/Users/pankaj/abc_copy2.txt')

os.remove('/Users/pankaj/abc_copy2.txt')
Copy

5. Close an open file in Python with the close() method

When you open a file in Python, it’s extremely important to close the file after you make the
changes. This saves any changes that you’ve previously made, removes the file from the memory,
and prevents any further reads or writes within the program.

Syntax to close an open file in Python:


fileobject.close()
Copy

If we continue on from our previous examples where we read files, here’s how you’d close the file:

text_file = open('/Users/pankaj/abc.txt','r')
# some file operations here

text_file.close()
Copy

Additionally, you can avoid closing files manually if you use the with block. As soon as the with block
is executed, the files are closed and are no longer available for reading and writing.
6. Python FileNotFoundError

It’s common to receive the FileNotFoundError when working with files in Python. It can be easily
avoided by providing complete file paths when creating the file object.

File "/Users/pankaj/Desktop/string1.py", line 2, in <module>


text_file = open('/Users/pankaj/Desktop/abc.txt','r')
FileNotFoundError: [Errno 2] No such file or directory: '/Users/pankaj/Desktop/abc.txt'

Copy

To fix the FileNotFoundError, you simply need to verify that the path you’ve mentioned for the file
open method is correct.

Python File Seek(): Move File Pointer Position

Python offers several methods for file handling. In addition to the standard operations like reading
and writing to the files, there are methods to manipulate the file pointer effectively.

In this tutorial, you’ll learn how to use the seek() function to move the position of a file
pointer while reading or writing a file.

Goals of this lesson:

 Learn to use the seek() method to move the file cursor ahead or backward from the current
position
 Learn to move the file pointer to that start or end of the file
 Learn to move the file pointer backward from the end of the file
 Get the current position of the file handle

What is seek() in Python

The seek() function sets the position of a file pointer and the tell() function returns the current
position of a file pointer.

A file handle or pointer denotes the position from which the file contents will be read or written.
File handle is also called as file pointer or cursor.

For example, when you open a file in write mode, the file pointer is placed at the 0th position, i.e., at
the start of the file. However, it changes (increments) its position as you started writing content into
it.

Or, when you read a file line by line, the file pointer moves one line at a time.
Sometimes we may have to read only a specific portion of the file, in such cases use
the seek() method to move the file pointer to that position.

For example, use the seek() function to do the file operations like: –

 Read a file from the 10th character.


 Directly jump to the 5th character from the end of the file.
 Add new content to file after a particular position.

How to Use seek() Method

To change the file handle’s position use seek() method. As we discussed, the seek() method sets the
file’s current position, and then we can read or write to the file from that position.

Syntax:

f.seek(offset, whence)

How many points the pointer will move is computed from adding offset to a reference point; the
reference point is given by the whence argument.

The allowed values for the whence argument are: –

 A whence value of 0 means from the beginning of the file.


 A whence value of 1 uses the current file position
 A whence value of 2 uses the end of the file as the reference point.
The default value for the whence is the beginning of the file, which is 0

Refer to the below table for clear understanding.

Seek Operation Meaning

f.seek(0) Move file pointer to the beginning of a File

f.seek(5) Move file pointer five characters ahead from the beginning of a file.

f.seek(0, 2) Move file pointer to the end of a File

f.seek(5, 1) Move file pointer five characters ahead from the current position.

f.seek(-5, 1) Move file pointer five characters behind from the current position.

f.seek(-5, 2) Move file pointer in the reverse direction. Move it to the 5th character from the end of the file
File seek function

Example

Consider the following example where we are reading a text file contents with the offset as 6. It
means we will start reading the file directly from the 6th character.

text file

with open(r'E:\demos\files_demos\sample.txt', "r") as fp:


# Moving the file handle to 6th character
fp.seek(6)
# read file
print(fp.read())

Output

line

Second line

Third line

Fourth line

Fifth line

Sixth line

Seventh line

Eighth line

You might also like