Data encryption
• Encryption is the process of encoding the data. i.e converting plain
text into ciphertext. This conversion is done with a key called an
encryption key.
• There are two main types of keys used for encryption and decryption.
They are Symmetric-key and Asymmetric-key.
• Decryption is the process of decoding the encoded data. Converting
the ciphertext into plain text. This process requires a key that we used
for encryption.
• In symmetric-key encryption, the data is encoded and decoded with
the same key.
• In Asymmetric-key Encryption, we use two keys a public key and a
private key. The public key is used to encrypt the data and the private
key is used to decrypt the data.
• Cryptography is a way to keep information safe and secure by encoding it so that
only those who are supposed to see it can understand it.
• We will be using the fernet module in the cryptography package to encrypt and
decrypt data using Python. The fernet module of the cryptography package has
inbuilt functions for the generation of the key.
• Installing cryptography package using pip where pip is a package manager for
Python packages
pip install cryptography
We will be using the fernet module to encrypt and decrypt data. So, let us import it
into the Python script.
from [Link] import Fernet
Generating a Key
In order to start encrypting data, you must first create a fernet key.
key = Fernet.generate_key()
f = Fernet(key)
Encrypting Data
In order to encrypt data from the above key, you must use the encrypt
method.
encrypted_data = [Link](b"This message is being encrypted and
cannot be seen!")
And that’s it, the above sentence has been encrypted.
To view your encrypted message, you must print it.
print(encrypted_data)
Decrypting Data
Now that you have the cipher text, let us see how we can convert it
back to plain readable text.
We can achieve decryption using the decrypt method in the fernet
module.
decrypted_data = [Link](encrypted_data) # f is the variable that has
the value of the key.
print(decrypted_data)
Example
from [Link] import Fernet
key = Fernet.generate_key()
print("Key : ", [Link]())
f = Fernet(key)
encrypted_data = [Link](b"This message is being encrypted and
cannot be seen!")
print("After encryption : ", encrypted_data)
decrypted_data = [Link](encrypted_data)
print(decrypted_data)
print("After decryption : ", decrypted_data.decode())
Output
Key : u4dM7xw8sNNU3Rm_lwDbixudWSeaM0Z4TTDdQNKsouI=
After encryption :
b'gAAAAABgIL3_qbfM_oMgQn653gpk6a7hqxXiR0dl0vrmOmqnr5b6Mq
rsjGkK1IknxMLLtOCq6_YlX4x3nBedbZqtCqy4os55pttrl-pBO6-
dJf6kVP50IpIaKSXbpAsuWl4h_2o_E-4YEqZ5kkgxWrwnqojmkMyuSQ=='
b'This message is being encrypted and cannot be seen!'
After decryption :
This message is being encrypted and cannot be seen!
math module
• The math module is a standard module in Python and is always available. To use mathematical
functions under this module, you have to import the module using import math
• Python offers the math module to carry out different mathematics like trigonometry, logarithms,
probability and statistics, etc. For example,
import math
print([Link]) Output
print([Link]([Link])) 3.141592653589793
pow(2, 3) -1.0
[Link](4) 8.0
print(math.log10(1000)) 2.0
print(math.log2(32)) 3.0
5.0
print([Link](15,30))
30
print([Link](15,30))
15
print([Link](6))
720
String comparison
• We can use ( > , < , <= , <= , == , != ) to compare two strings.
• Python compares string lexicographically i.e using ASCII value of the
characters.
String functions
Converting Strings Between Number Bases
• Binary to Integer: Use int() function with base 2
binary_str = "1010"
decimal_num = int(binary_str, 2)
# Converts binary string to decimal (base 10)
print(decimal_num) # Output: 10
• Octal to Integer: Use int() function with base 8
octal_str = "12"
decimal_num = int(octal_str, 8)
# Converts octal string to decimal (base 10)
print(decimal_num) # Output: 10
• Hexadecimal to Integer: Use int() function with base 16
hex_str = "A"
decimal_num = int(hex_str, 16)
# Converts hexadecimal string to decimal (base 10)
print(decimal_num) # Output: 10
Manipulating String Representations of Numbers
You can also perform operations directly on string representations of numbers, such as
formatting or extracting parts of the string.
Formatting Numeric Strings:
num = 123
num_str = str(num) # Convert number to string
formatted_str = f"The number is {num_str}"
print(formatted_str) # Output: "The number is 123"
Extracting Parts of Numeric Strings:
num_str = "12345"
part_of_str = num_str[1:3] # Slicing to extract a substring
print(part_of_str) # Output: "23"
Converting Between Bases as Strings:
If you need to convert integers to their string representations in different
bases:
num = 10
binary_str = bin(num) # Binary representation as string
octal_str = oct(num) # Octal representation as string
hex_str = hex(num) # Hexadecimal representation as string
print(binary_str, octal_str, hex_str) # Output: '0b1010', '0o12', '0xa'
File
The file is the smallest unit of storage on a computer system. A file is a
sequence of bits, bytes, lines, or records defined by its owner or
creator.
Need for a data file
• To store data in organized manner
• To store data permanently
• To access data faster
• To search data faster
• To easily modify data later on
File Handling
• A file is a sequence of bytes on the disk/permanent storage where a
group of related data is stored. File is created for permanent storage
of data.
• File handling in Python enables us to create, update, read, and delete
the files stored on the file system through our python program.
• The following operations can be performed on a file.
• In Python, File Handling consists of following three steps:
[Link] the file.
[Link] file i.e perform read or write operation.
[Link] the file.
Types of Files
• There are two types of files:
• Text Files- A file whose contents can be viewed using a text editor is
called a text file. A text file is simply a sequence of ASCII or Unicode
characters. Python programs, contents written in text editors are
some of the example of text files.e.g. .txt,.rtf,.csv etc.
• Binary Files-A binary file stores the data in the same way as as stored
in the memory. The .exe files,mp3 file, image files, word documents
are some of the examples of binary [Link] can’t read a binary file
using a text editor.e.g. .bmp,.cdr etc
Opening and Closing Files
• To perform file operation ,it must be opened first then after reading
,writing, editing operation can be performed. To create any new file
then too it must be opened.
• On opening of any file ,a file relevant structure is created in memory as
well as memory space is created to store contents.
• Once we are done working with the file, we should close the file.
• Closing a file releases valuable system resources. In case we forgot to
close the file, Python automatically close the file when program ends or
file object is no longer referenced in the program.
Open Function
• Before any reading or writing operation of any file, it must be opened
first of all.
• Python provide built in function open() for it.
• On calling of this function creates file object for file operations.
Syntax:
file object = open(<file_name>, <access_mode> ,< buffering>)
file_name = name of the file ,enclosed in double quotes.
access_mode = determines the what kind of operations can be
performed with file, like read, write etc.
buffering = small amount of data 0, for text files 1, for huge files >1, for
system default -1.
File opening Modes
File object attributes
• closed: It returns true if the file is closed and false when the file is
open.
• encoding: Encoding used for byte string conversion.
• mode: Returns file opening mode
• name: Returns the name of the file which file object holds.
• newlines: Returns “\r”, “\n”, “\r\n”, None or a tuple containing all the
newline types seen.
Program
#1 open text file
f = open("[Link]", 'a+')
print([Link])
print([Link])
print([Link])
print([Link])
print([Link])
OUTPUT
False
cp1252
a+
None
[Link]
Close a text file
close(): Used to close an open file. After using this method, an opened
file will be closed and a closed file cannot be read or written any more.
E.g. program
f = open("[Link]", 'a+')
print([Link])
print("Name of the file is",[Link])
[Link]() # close text file
print([Link])
OUTPUT
False
Name of the file is [Link]
True
Read/write text file
• The write() method It writes the contents to the file in the
form of string. It does not return value. Due to buffering, the
string may not actually show up in the file until the flush() or
close() method is called.
• The read() method It reads the entire file and returns it
contents in the form of a string. Reads at most size bytes or
less if end of file occurs. if size not mentioned then read the
entire file content.
write() ,read() method based program
f = open("[Link]", 'w')
line1 = 'Welcome to python program'
[Link](line1)
line2="\nPython is a case sensitive language"
[Link](line2)
[Link]()
f = open("[Link]", 'r')
text = [Link]()
print(text)
[Link]()
OUTPUT
Welcome to python program
Python is a case sensitive language
readlines(size) method: Read no of lines from file if size is mentioned or all contents if
size is not mentioned.
f = open("[Link]", 'r')
text = [Link](1)
print(text)
[Link]()
OUTPUT
Welcome to python Program
NOTE – READ ONLY ONE LINE IN ABOVE PROGRAM.
Iterating over lines in a file
f = open("[Link]", 'r')
for text in [Link]():
print(text)
[Link]()
Processing Every Word in a File
f = open("[Link]", 'r')
for text in [Link]():
for word in [Link]( ):
print(word)
[Link]()
OUTPUT
Welcome
to
Python
Program
Python
is
a
Case
Sensitive
Language
Append content to a Text file
f = open("[Link]", 'w')
line = 'Welcome to python\n Python is a case sensitive language'
[Link](line)
[Link]()
f = open("[Link]", 'a+')
[Link]("\nPython is a cross platform language")
[Link]()
f = open("[Link]", 'r')
text = [Link]()
print(text)
[Link]()
OUTPUT
Welcome to python
Python is a case sensitive language
Python is a cross platform language
File Positions
• The tell() method of python tells us the current position within the file, where as The seek(offset[, from]) method
changes the current file position.
• If from is 0, the beginning of the file to seek. If it is set to 1, the current position is used . If it is set to 2 then the
end of the file would be taken as seek position. The offset argument indicates the number of bytes to be moved.
Example:
f = open("[Link]", 'rb+')
print([Link]())
print([Link](7)) # read seven characters
print([Link]())
print([Link]())
print([Link]())
[Link](9,0) # moves to 9 position from begining
print([Link](5))
[Link](4, 1) # moves to 4 position from current location
print([Link](5))
[Link](-5, 2) # Go to the 5th byte before the end
print([Link](5))
[Link]()
Sequences
• In Python programming, sequences are a generic term for
an ordered set which means that the order in which
we input the items will be the same when we access them.
• Lists are the most versatile sequence type. The elements of a
list can be any object, and lists are mutable - they can be
changed. Elements can be reassigned or removed, and new
elements can be inserted.
• Tuples are like lists, but they are immutable - they can't be
changed.
• Strings are a special type of sequence that can only
store characters, and they have a special notation
List
• It is a collections of items and each item has its own index value.
• Index of first item is 0 and the last item is n-1. Here n is number of
items in a list.
Indexing of list
Creating a list
Lists are enclosed in square brackets [ ] and each item is separated by a
comma.
Initializing a list
Passing value in list while declaring list is initializing of a list
e.g.
list1 = [‘English', ‘Hindi', 1997, 2000]
list2 = [11, 22, 33, 44, 55 ]
list3 = ["a", "b", "c", "d"]
Blank list creation
A list can be created without element
List4=[ ]
Basic List Operations
Important methods and functions of List
Function Description
Iterating/Traversing Through A List
List elements can be accessed using looping statement.
e.g.
list =[3,5,9]
for i in range(0, len(list)):
print(list[i])
Output
3
5
9
Add Two Lists
e.g.
list = [1,2]
list2 = [3,4]
list3 = list + list2
print(list3)
Output
[1,2,3,4]
Slicing of A List
List elements can be accessed in subparts.
e.g.
list =['I','N','D','I','A']
print(list[0:3])
print(list[3:])
print(list[:])
Output
['I', 'N', 'D']
['I', 'A']
['I', 'N', 'D', 'I', 'A']
Updating / Manipulating Lists
We can update single or multiple elements of lists by giving
the slice on the left-hand side of the assignment operator.
e.g.
list = ['English', 'Hindi', 1997, 2000]
print ("Value available at index 2 : ", list[2])
list[2:3] = 2001,2002
print ("New value available at index 2 : ", list[2])
print ("New value available at index 3 : ", list[3])
Output
('Value available at index 2 : ', 1997)
('New value available at index 2 : ', 2001)
('New value available at index 3 : ', 2002)
Add Item to A List
append() method is used to add an Item to a List.
e.g.
list=[1,2]
print('list before append', list)
[Link](3)
print('list after append', list)
Output
('list before append', [1, 2])
('list after append', [1, 2, 3])
NOTE :- extend() method can be used to add multiple item at
a time in [Link] - [Link]([3,4])
Delete Item From A List
e.g.
list=[1,2,3]
print('list before delete', list)
del list [1]
print('list after delete', list)
Output
('list before delete', [1, 2, 3])
('list after delete', [1, 3])
e.g.
del list[0:2] # delete first two items
del list # delete entire list
Tuples
• It is a sequence of immutable objects. It is just like list. Difference
between the tuples and the lists is that the tuples cannot be changed
unlike lists. Lists uses square bracket where as tuples use parentheses.
Creating A Tuple
• A tuple is enclosed in parentheses () for creation and each item is
separated by a comma.
e.g.
tup1 = (‘comp science', ‘practices', 2020, 2021)
tup2 = (5,11,22,44)
NOTE:- Indexing of tuple is just similar to indexing of list
Accessing Values from tuples/tuple slicing
Use the square brackets for slicing along with the index or indices to
obtain the value available at that index.
e.g.
tup1 = ("comp sc", "practices", 2020, 2021)
tup2 = (5,11,22,44,9,66)
print ("tup1[0]: ", tup1[0])
print ("tup2[1:5]: ", tup2[1:5])
Output
('tup1[0]: ', 'comp sc')
('tup2[1:5]: ', (11, 22, 44, 9)
Iterating through a Tuple
Element of the tuple can be accessed sequentially using loop.
e.g.
tup = (5,11,22) Output
for i in range(0,len(tup)): 5
print(tup[i]) 11
Updating Tuples 22
Tuples are immutable, that's why we can’t change the content of tuple. It’s alternate
way is to take contents of existing tuple and create another tuple with these contents
as well as new content.
E.g.
tup1 = (1, 2)
tup2 = ('a', 'b')
tup3 = tup1 + tup2
print (tup3)
Output
(1, 2, 'a', 'b')
Delete tuple elements
Direct deletion of tuple element is not possible but shifting of required
content after discard of unwanted content to another tuple.
e.g.
tup1 = (1, 2,3)
tup3 = tup1[0:1] + tup1[2:]
print (tup3)
Output
(1, 3)
NOTE : Entire tuple can be deleted using del statement.
e.g. del tup1
Basic Tuples Operations
Tuple Function
count() - method returns the number of times a specified value appears
in the tuple.
thistuple = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)
x = [Link](5)
print(x)
OUTPUT-> 2
index() – returns the index position of first occurrence of a value in tuple
vowels = ('a', 'e', 'i', 'o', 'i', 'u')
index = [Link]('e')
print('The index of e:', index)
OUTPUT ->1
sum()- sum of tuple elements can be done via list
x = (1,4,6)
r= sum(x)
print('sum of elements in tuple', r)
OUTPUT->11
9
sorted()- returns the sorted elements list
x = (1,4,6)
r= sorted(x)
print(sorted elements in tuple’, r)
max of a tuple elements.
x = (1,4,6)
r= max(x)
print('maximum value in tuple', r)
OUTPUT->6
mean/average of a tuple elements.
x = (1,4,6)
r= sum(x)/len(x)
print(mean of tuple is ', r)
OUTPUT->3.66
Dictionary
• It is an unordered collection of items where each item consist of a key
and a value. It is mutable (can modify its contents ) but Key must be
unique and immutable.
Creating A Dictionary
It is enclosed in curly braces {} and each item is separated from other item by a
comma(,). Within each item, key and value are separated by a colon (:).Passing
value in dictionary at declaration is dictionary initialization.
e.g.
dict = {‘Subject': ‘Informatic Practices', 'Class': ‘11'}
Accessing List Item
dict = {'Subject': 'Informatics Practices', 'Class': 11}
print(dict)
print ("Subject : ", dict['Subject'])
print ("Class : ", [Link]('Class’))
OUTPUT
{'Class': '11', 'Subject': 'Informatics Practices'}
('Subject : ', 'Informatics Practices')
('Class : ', 11)
Iterating / Traversing through A Dictionary
Following example will show how dictionary items can be accessed through loop.
e.g.
dict = {'Subject': 'Informatics Practices', 'Class': 11}
for i in dict:
print(dict[i])
OUTPUT
11
Informatics Practices
Updating/Manipulating Dictionary Elements
We can change the individual element of dictionary.
e.g.
dict = {'Subject': 'Informatics Practices', 'Class': 11}
dict['Subject']='computer science'
print(dict)
OUTPUT
{'Class': 11,'Subject': 'computer science'}
Deleting Dictionary Elements
del, pop() and clear() statement are used to remove elements from the
dictionary.
del e.g.
dict = {'Subject': 'Informatics Practices', 'Class': 11}
print('before del', dict)
del dict['Class'] # delete single element
print('after item delete', dict)
del dict #delete whole dictionary
print('after dictionary delete', dict)
Output
('before del', {'Class': 11, 'Subject': 'Informatics Practices'})
('after item delete', {'Subject': 'Informatics Practices'})
('after dictionary delete', <type 'dict'>)
pop() method is used to remove a particular item in a dictionary. clear()
method is used to remove all elements from the dictionary.
e.g.
dict = {'Subject': 'Informatics Practices', 'Class': 11}
print('before del', dict)
[Link]('Class')
print('after item delete', dict)
[Link]()
print('after clear', dict)
Output
('before del', {'Class': 11, 'Subject': 'Informatics Practices'})
('after item delete', {'Subject': 'Informatics Practices'})
('after clear', {})
Built-in Dictionary Methods
Python functions
• In Python, a function is a group of related statements that performs a specific task. The
definition of this function consists of a header and a body. The header includes the
keyword def as well as the function name and list of parameters. The function’s body
contains one or more statements. Here is the syntax:
def <function name>(<parameter-1>, ..., <parameter-n>):
<body>
• 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.
Creating a Function
In Python a function is defined using the def keyword:
Example
def my_function():
print("Hello from a function")
Calling a Function
To call a function, use the function name followed by parenthesis:
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.
def full_name(fname, lname):
print(fname + " " + lname)
full_name("Raja", "Ram")
Default Parameter Value
• If we call the function without argument, it uses the default value:
def default_function(country = "Norway"):
print("I am from " + country)
default_function("Sweden")
default_function("India")
default_function()
default_function("Brazil")