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

Lab Manual python

The document is a lab manual for a Programming in Python course, detailing various experiments and objectives for students to learn Python programming. It includes a list of experiments covering topics such as data types, arithmetic operations, string manipulation, and more, along with experimental procedures and expected outcomes. The manual emphasizes the importance of understanding basic data types and operations in Python for effective programming.

Uploaded by

inurture.su
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Lab Manual python

The document is a lab manual for a Programming in Python course, detailing various experiments and objectives for students to learn Python programming. It includes a list of experiments covering topics such as data types, arithmetic operations, string manipulation, and more, along with experimental procedures and expected outcomes. The manual emphasizes the importance of understanding basic data types and operations in Python for effective programming.

Uploaded by

inurture.su
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 113

LAB MANUAL

Subject: Programming in Python Lab


Subject Code: BTCS 513-18
Class: B. Tech 5th Semester
Programming in Python Lab (BTCS 513-18)

Prerequisites: Students should install Python.


List of Experiments:
1. Write a program to demonstrate different number data types in Python
2. Write a program to perform different Arithmetic Operations on numbers in Python.
3. Write a program to create, concatenate and print a string and accessing substring from
a given string.
4. Write a python script to print the current date in the following format “Sun May 29
02:26:23 IST 2017”
5. Write a program to create, append, and remove lists in python.
6. Write a program to demonstrate working with tuples in python.
7. Write a program to demonstrate working with dictionaries in python.
8. Write a python program to find largest of three numbers.
9. Write a Python program to convert temperatures to and from Celsius, Fahrenheit.
[Formula: c/5 = f-32/9]
10. Write a Python program to construct the following pattern, using a nested for Loop
*
**
***
****
***
**
**
*
11. Write a Python script that prints prime numbers less than 20.
12. Write a python program to find factorial of a number using Recursion.
13. Write a program that accepts the lengths of three sides of a triangle as inputs. The
program output should indicate whether or not the triangle is a right triangle (Recall
from the Pythagorean Theorem that in a right triangle, the square of one side equals
the sum of the squares of the other two sides).
14. Write a python program to define a module to find Fibonacci Numbers and import the
module to another program.
15. Write a python program to define a module and import a specific function in that
module to another program.
16. Write a script named copyfile.py. This script should prompt the user for the names of
two text files. The contents of the first file should be input and written to the second
file.
17. Write a program that inputs a text file. The program should print all of the unique
words in the file in alphabetical order.
18. Write a Python class to convert an integer to a roman numeral.
19. Write a Python class to implement pow(x, n)
20. Write a Python class to reverse a string word by word.
Experiment 1

Experiment name: Write a program to demonstrate different number data types in


Python
Objectives: To learn various basic data types and how to input and output.
Prerequisites: Algorithm and logics, basic knowledge of C++

Key terms: print, Data Types

Experimental set-up/Equipment/Apparatus/Tools: -
1. Computer System
2. Google Colab /python Installed on system with editor (like pycharm,
jupyter)

Theory and application

Standard Data Types


The data stored in memory can be of many types. For example, a person's age is stored as a
numeric value and his or her address is stored as alphanumeric characters. Python has
various standard data types that are used to define the operations possible on them and the
storage method for each of them.
Python has five standard data types −

 Numbers
 String
 List
 Tuple
 Dictionary
Python Numbers
Number data types store numeric values. Number objects are created when you assign a
value to them. For example −
var1 = 1
var2 = 10
You can also delete the reference to a number object by using the del statement. The syntax
of the del statement is −
del var1[,var2[,var3[....,varN]]]]
You can delete a single object or multiple objects by using the del statement. For example −
del var
del var_a, var_b
Python supports four different numerical types −

 int (signed integers)


 long (long integers, they can also be represented in octal and hexadecimal)
 float (floating point real values)
 complex (complex numbers)

Experimental Procedure-

1. Start Google Colab /python Installed on system with editor (like pycharm, jupyter)
2. Type a python program using input, output and calculations
3. Save the program
4. Execute it.

# Python program to
# demonstrate numeric value

a=5
print("Type of a: ", type(a))

b = 5.0
print("\nType of b: ", type(b))

c = 2 + 4j
print("\nType of c: ", type(c))

Precaution and sources of error:

The devices either computers or any other networking device should be handled
with due care and preserved carefully.
Results

Type of a: <class 'int'>

Type of b: <class 'float'>

Conclusions
We should know all the basic data types of python to start with it. Also to perform any
operation Input and output are very important so through this experiment we learnt to do the
same in the python.

Related short question:

1. How to take input in python


2. How to generate output in python
3. What are the supported data types in Python?
4. Explain various Mathematical Operations in python
Experiment 2

Experiment name: Write a program to perform different Arithmetic Operations on


numbers in Python.
Objectives: To learn how to perform calculations on data of different data types.
Prerequisites: Algorithm and logics, basic knowledge of C++
Key terms: Arithmetic, operators, logical

Experimental set-up/Equipment/Apparatus/Tools: -
1. Computer System
2. Google Colab /python Installed on system with editor (like pycharm, jupyter)

Theory and application

Python divides the operators in the following groups:

 Arithmetic operators
 Assignment operators
 Comparison operators
 Logical operators
 Identity operators
 Membership operators
 Bitwise operators

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

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

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 x >= y


to

<= Less than or equal to x <= y

Python Logical Operators

Logical operators are used to combine conditional statements:

and Returns True if both x < 5 and x < 10


statements are true

or Returns True if one x < 5 or x < 4


of the statements is
true
not Reverse the result, not(x < 5 and x < 10)
returns False if the
result is true
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 x is y


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

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 x in y


with the specified value is
present in the object

not in Returns True if a sequence x not in y


with the specified value is
not present in the object

Python Bitwise Operators

Bitwise operators are used to compare (binary) numbers:

Operator Name Description

& AND Sets each bit to 1 if both bits


are 1
| OR Sets each bit to 1 if one of two
bits is 1
^ XOR Sets each bit to 1 if only one of
two bits is 1
~ NOT Inverts all the bits

<< Zero fill left shift Shift left by pushing zeros in


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

Experimental Procedure-
1 Start Google Colab /python Installed on system with editor (like pycharm, jupyter)
2 Type a python program using input, output and calculations
3 Save the program
4 Execute it.

Source code:

a=10; b=3

print("addition of a:",a,"&b:",b,"is:",a+b)

print("substraction of a:",a,"&b:",b,"is:",a-b)

print("multiplication of a:",a,"&b:",b,"is:",a*b)

print("division of a:",a,"&b:",b,"is:",a/b)

print("floor divison of a:",a,"&b:",b,"is:",a//b)

print("moduli of a:",a,"&b:",b,"is:",a%b)

print("exponent of a:",a,"&b:",b,"is:",a**b)

Precaution and sources of error:


The devices either computers or any other networking device should be handled
with due care and preserved carefully.

Results
Conclusions
Operators are the constructs which can manipulate the value of operands. Manipulation is
required in every application. So the basic knowledge of operator is mandatory

Related short question:


1. What are different operators in python
2. Name some bitwise operator
3. Explain logical operator
4. What are membership operator
5. What are different identity operators
Experiment 3

Experiment name: Write a program to create, concatenate and print a string and
accessing substring
from a given string.

Objectives: To learn how to perform various operations on strings

Prerequisites: Algorithm and logics, basic knowledge of C++

Key terms: concatenate, string, print

Experimental set-up/Equipment/Apparatus/Tools: -
3. Computer System
4. Google Colab /python Installed on system with editor (like pycharm, jupyter)

Theory and application

Python String

Till now, we have discussed numbers as the standard data-types in Python. In this section of
the tutorial, we will discuss the most popular data type in Python, i.e., string.

Python string is the collection of the characters surrounded by single quotes, double quotes,
or triple quotes. The computer does not understand the characters; internally, it stores
manipulated character as the combination of the 0's and 1's.

Each character is encoded in the ASCII or Unicode character. So we can say that Python
strings are also called the collection of Unicode characters.

In Python, strings can be created by enclosing the character or the sequence of characters in
the quotes. Python allows us to use single quotes, double quotes, or triple quotes to create the
string.

Consider the following example in Python to create a string.

Syntax:
1. str = "Hi Python !"

Here, if we check the type of the variable str using a Python script
1. print(type(str)), then it will print a string (str).

In Python, strings are treated as the sequence of characters, which means that Python doesn't
support the character data-type; instead, a single character written as 'p' is treated as the string
of length 1.

Creating String in Python

We can create a string by enclosing the characters in single-quotes or double- quotes. Python
also provides triple-quotes to represent the string, but it is generally used for multiline string
or docstrings.

1. #Using single quotes


2. str1 = 'Hello Python'
3. print(str1)
4. #Using double quotes
5. str2 = "Hello Python"
6. print(str2)
7.
8. #Using triple quotes
9. str3 = '''''Triple quotes are generally used for
10. represent the multiline or
11. docstring'''
12. print(str3)

Output:

Hello Python
Hello Python
Triple quotes are generally used for
represent the multiline or
docstring

Strings indexing and splitting

Like other languages, the indexing of the Python strings starts from 0. For example, The
string "HELLO" is indexed as given in the below figure.
Consider the following example:

1. str = "HELLO"
2. print(str[0])
3. print(str[1])
4. print(str[2])
5. print(str[3])
6. print(str[4])
7. # It returns the IndexError because 6th index doesn't exist
8. print(str[6])

Output:

H
E
L
L
O
IndexError: string index out of range
As shown in Python, the slice operator [] is used to access the individual characters of the
string. However, we can use the : (colon) operator in Python to access the substring from the
given string. Consider the following example.

Here, we must notice that the upper range given in the slice operator is always exclusive i.e.,
if str = 'HELLO' is given, then str[1:3] will always include str[1] = 'E', str[2] = 'L' and nothing
else.

Consider the following example:

1. # Given String
2. str = "JAVATPOINT"
3. # Start Oth index to end
4. print(str[0:])
5. # Starts 1th index to 4th index
6. print(str[1:5])
7. # Starts 2nd index to 3rd index
8. print(str[2:4])
9. # Starts 0th to 2nd index
10. print(str[:3])
11. #Starts 4th to 6th index
12. print(str[4:7])

Output:
JAVATPOINT
AVAT
VA
JAV
TPO

We can do the negative slicing in the string; it starts from the rightmost character, which is
indicated as -1. The second rightmost index indicates -2, and so on. Consider the following
image.

Consider the following example

1. str = 'JAVATPOINT'
2. print(str[-1])
3. print(str[-3])
4. print(str[-2:])
5. print(str[-4:-1])
6. print(str[-7:-2])
7. # Reversing the given string
8. print(str[::-1])
9. print(str[-12])

Output:
T
I
NT
OIN
ATPOI
TNIOPTAVAJ
IndexError: string index out of range

Reassigning Strings

Updating the content of the strings is as easy as assigning it to a new string. The string object
doesn't support item assignment i.e., A string can only be replaced with new string since its
content cannot be partially replaced. Strings are immutable in Python.

Consider the following example.

Example 1
1. str = "HELLO"
2. str[0] = "h"
3. print(str)

Output:

Traceback (most recent call last):


File "12.py", line 2, in <module>
str[0] = "h";
TypeError: 'str' object does not support item assignment

However, in example 1, the string str can be assigned completely to a new content as
specified in the following example.

Example 2
1. str = "HELLO"
2. print(str)
3. str = "hello"
4. print(str)

Output:

HELLO
hello
Deleting the String

As we know that strings are immutable. We cannot delete or remove the characters from the
string. But we can delete the entire string using the del keyword.

1. str = "JAVATPOINT"
2. del str[1]

Output:

TypeError: 'str' object doesn't support item deletion

Now we are deleting entire string.

1. str1 = "JAVATPOINT"
2. del str1
3. print(str1)

Output:

NameError: name 'str1' is not defined

String Operators
Operator Description

+ It is known as concatenation operator used to join the strings given either side of the
operator.

* It is known as repetition operator. It concatenates the multiple copies of the same string.

[] It is known as slice operator. It is used to access the sub-strings of a particular string.

[:] It is known as range slice operator. It is used to access the characters from the specified
range.

in It is known as membership operator. It returns if a particular sub-string is present in the


specified string.
not in It is also a membership operator and does the exact reverse of in. It returns true if a
particular substring is not present in the specified string.

r/R It is used to specify the raw string. Raw strings are used in the cases where we need to
print the actual meaning of escape characters such as "C://python". To define any string as
a raw string, the character r or R is followed by the string.

% It is used to perform string formatting. It makes use of the format specifiers used in C
programming like %d or %f to map their values in python. We will discuss how
formatting is done in python.

Example

Consider the following example to understand the real use of Python operators.

1. str = "Hello"
2. str1 = " world"
3. print(str*3) # prints HelloHelloHello
4. print(str+str1)# prints Hello world
5. print(str[4]) # prints o
6. print(str[2:4]); # prints ll
7. print('w' in str) # prints false as w is not present in str
8. print('wo' not in str1) # prints false as wo is present in str1.
9. print(r'C://python37') # prints C://python37 as it is written
10. print("The string str : %s"%(str)) # prints The string str : Hello

Output:

HelloHelloHello
Hello world
o
ll
False
False
C://python37
The string str : Hello
Python String Formatting

Escape Sequence

Let's suppose we need to write the text as - They said, "Hello what's going on?"- the given
statement can be written in single quotes or double quotes but it will raise
the SyntaxError as it contains both single and double-quotes.

Example

Consider the following example to understand the real use of Python operators.

1. str = "They said, "Hello what's going on?""


2. print(str)

Output:

SyntaxError: invalid syntax

We can use the triple quotes to accomplish this problem but Python provides the escape
sequence.

The backslash(/) symbol denotes the escape sequence. The backslash can be followed by a
special character and it interpreted differently. The single quotes inside the string must be
escaped. We can apply the same as in the double quotes.

Example -
1. # using triple quotes
2. print('''''They said, "What's there?"''')
3.
4. # escaping single quotes
5. print('They said, "What\'s going on?"')
6.
7. # escaping double quotes
8. print("They said, \"What's going on?\"")

Output:

They said, "What's there?"


They said, "What's going on?"
They said, "What's going on?"
The list of an escape sequence is given below:

Sr. Escape Description Example


Sequence

1. \newline It ignores the new line. print("Python1 \


Python2 \
Python3")
Output:

Python1 Python2 Python3

2. \\ Backslash print("\\")
Output:

3. \' Single Quotes print('\'')


Output:

'

4. \\'' Double Quotes print("\"")


Output:

"

5. \a ASCII Bell print("\a")

6. \b ASCII Backspace(BS) print("Hello \b World")


Output:

Hello World

7. \f ASCII Formfeed print("Hello \f World!")


Hello World!

8. \n ASCII Linefeed print("Hello \n World!")


Output:

Hello
World!

9. \r ASCII Carriege Return(CR) print("Hello \r World!")


Output:

World!

10. \t ASCII Horizontal Tab print("Hello \t World!")


Output:

Hello World!

11. \v ASCII Vertical Tab print("Hello \v World!")


Output:

Hello
World!

12. \ooo Character with octal value print("\110\145\154\154\157")


Output:
Hello

13 \xHH Character with hex value. print("\x48\x65\x6c\x6c\x6f")


Output:

Hello

Here is the simple example of escape sequence.

1. print("C:\\Users\\DEVANSH SHARMA\\Python32\\Lib")
2. print("This is the \n multiline quotes")
3. print("This is \x48\x45\x58 representation")

Output:

C:\Users\DEVANSH SHARMA\Python32\Lib
This is the
multiline quotes
This is HEX representation

We can ignore the escape sequence from the given string by using the raw string. We can do
this by writing r or R in front of the string. Consider the following example.

1. print(r"C:\\Users\\DEVANSH SHARMA\\Python32")

Output:
C:\\Users\\DEVANSH SHARMA\\Python32

The format() method

The format() method is the most flexible and useful method in formatting strings. The curly
braces {} are used as the placeholder in the string and replaced by the format() method
argument. Let's have a look at the given an example:

1. # Using Curly braces


2. print("{} and {} both are the best friend".format("Devansh","Abhishek"))
3.
4. #Positional Argument
5. print("{1} and {0} best players ".format("Virat","Rohit"))
6.
7. #Keyword Argument
8. print("{a},{b},{c}".format(a = "James", b = "Peter", c = "Ricky"))

Output:

Devansh and Abhishek both are the best friend


Rohit and Virat best players
James,Peter,Ricky

Python String Formatting Using % Operator

Python allows us to use the format specifiers used in C's printf statement. The format
specifiers in Python are treated in the same way as they are treated in C. However, Python
provides an additional operator %, which is used as an interface between the format specifiers
and their values. In other words, we can say that it binds the format specifiers to the values.

Consider the following example.

1. Integer = 10;
2. Float = 1.290
3. String = "Devansh"
4. print("Hi I am Integer ... My value is %d\nHi I am float ... My value is %f\nHi I am string ...
My value is %s"%(Integer,Float,String))

Output:

Hi I am Integer ... My value is 10


Hi I am float ... My value is 1.290000
Hi I am string ... My value is Devansh

Python String functions

Python provides various in-built functions that are used for string handling. Many String fun

Method Description

capitalize() It capitalizes the first character of the String. This function is


deprecated in python3

casefold() It returns a version of s suitable for case-less comparisons.

center(width ,fillchar) It returns a space padded string with the original string centred
with equal number of left and right spaces.

count(string,begin,end) It counts the number of occurrences of a substring in a String


between begin and end index.

decode(encoding = 'UTF8', Decodes the string using codec registered for encoding.
errors = 'strict')

encode() Encode S using the codec registered for encoding. Default


encoding is 'utf-8'.

endswith(suffix ,begin=0,end=le It returns a Boolean value if the string terminates with given suffix
n(string)) between begin and end.

expandtabs(tabsize = 8) It defines tabs in string to multiple spaces. The default space value
is 8.

find(substring ,beginIndex, It returns the index value of the string where substring is found
endIndex) between begin index and end index.
format(value) It returns a formatted version of S, using the passed value.

index(subsring, beginIndex, It throws an exception if string is not found. It works same as


endIndex) find() method.

isalnum() It returns true if the characters in the string are alphanumeric i.e.,
alphabets or numbers and there is at least 1 character. Otherwise, it
returns false.

isalpha() It returns true if all the characters are alphabets and there is at least
one character, otherwise False.

isdecimal() It returns true if all the characters of the string are decimals.

isdigit() It returns true if all the characters are digits and there is at least one
character, otherwise False.

isidentifier() It returns true if the string is the valid identifier.

islower() It returns true if the characters of a string are in lower case,


otherwise false.

isnumeric() It returns true if the string contains only numeric characters.

isprintable() It returns true if all the characters of s are printable or s is empty,


false otherwise.

isupper() It returns false if characters of a string are in Upper case, otherwise


False.

isspace() It returns true if the characters of a string are white-space,


otherwise false.

istitle() It returns true if the string is titled properly and false otherwise. A
title string is the one in which the first character is upper-case
whereas the other characters are lower-case.

isupper() It returns true if all the characters of the string(if exists) is true
otherwise it returns false.

join(seq) It merges the strings representation of the given sequence.

len(string) It returns the length of a string.

ljust(width[,fillchar]) It returns the space padded strings with the original string left
justified to the given width.

lower() It converts all the characters of a string to Lower case.

lstrip() It removes all leading whitespaces of a string and can also be used
to remove particular character from leading.

partition() It searches for the separator sep in S, and returns the part before it,
the separator itself, and the part after it. If the separator is not
found, return S and two empty strings.

maketrans() It returns a translation table to be used in translate function.

replace(old,new[,count]) It replaces the old sequence of characters with the new sequence.
The max characters are replaced if max is given.

rfind(str,beg=0,end=len(str)) It is similar to find but it traverses the string in backward direction.

rindex(str,beg=0,end=len(str)) It is same as index but it traverses the string in backward direction.

rjust(width,[,fillchar]) Returns a space padded string having original string right justified
to the number of characters specified.
rstrip() It removes all trailing whitespace of a string and can also be used
to remove particular character from trailing.

rsplit(sep=None, maxsplit = -1) It is same as split() but it processes the string from the backward
direction. It returns the list of words in the string. If Separator is
not specified then the string splits according to the white-space.

split(str,num=string.count(str)) Splits the string according to the delimiter str. The string splits
according to the space if the delimiter is not provided. It returns
the list of substring concatenated with the delimiter.

splitlines(num=string.count('\n')) It returns the list of strings at each line with newline removed.

startswith(str,beg=0,end=len(str)) It returns a Boolean value if the string starts with given str between
begin and end.

strip([chars]) It is used to perform lstrip() and rstrip() on the string.

swapcase() It inverts case of all characters in a string.

title() It is used to convert the string into the title-case i.e., The
string meEruT will be converted to Meerut.

translate(table,deletechars = '') It translates the string according to the translation table passed in
the function .

upper() It converts all the characters of a string to Upper Case.

zfill(width) Returns original string leftpadded with zeros to a total of width


characters; intended for numbers, zfill() retains any sign given
(less one zero).

rpartition()

Experimental Procedure-
5 Start Google Colab /python Installed on system with editor (like pycharm, jupyter)
6 Type a python program using input, output and calculations
7 Save the program
8 Execute it.

11. str = "Hello"


12. str1 = " world"
13. print(str*3) # prints HelloHelloHello
14. print(str+str1)# prints Hello world
15. print(str[4]) # prints o
16. print(str[2:4]); # prints ll
17. print('w' in str) # prints false as w is not present in str
18. print('wo' not in str1) # prints false as wo is present in str1.
19. print(r'C://python37') # prints C://python37 as it is written
20. print("The string str : %s"%(str)) # prints The string str : Hello

Precaution and sources of error:


The devices either computers or any other networking device should be handled
with due care and preserved carefully.

Results

Output:

HelloHelloHello
Hello world
o
ll
False
False
C://python37
The string str : Hello

Conclusion:
Strings are amongst the most popular types in Python. We can create them simply by enclosing
characters in quotes. Python treats single quotes the same as double quotes Thorugh this experiment
we learnt to perform various operations on strings in python.

Related short question:

1. Check if a string contains a specific substring

2. Find the index of the first occurrence of a substring in a string

3. how to Count the total number of characters in a string

4. How to Capitalize the first character of a string

5. How to Search a specific part of a string for a substring


Experiment 4

Experiment name: Write a python script to print the current date in the following format
“Sun May 29 02:26:23 IST 2017”

Objectives: To learn how to work with date datatype

Prerequisites: Algorithm and logics, basic knowledge of C++

Key terms: date, DD, MM,YY

Experimental set-up/Equipment/Apparatus/Tools: -
5. Computer System
6. Google Colab /python Installed on system with editor (like pycharm, jupyter)

Theory and application

Python Date and time

Python provides the datetime module work with real dates and times. In real-world
applications, we need to work with the date and time. Python enables us to schedule our
Python script to run at a particular timing.

In Python, the date is not a data type, but we can work with the date objects by importing the
module named with datetime, time, and calendar.

In this section of the tutorial, we will discuss how to work with the date and time objects in
Python.

The datetime classes are classified in the six main classes.

o date - It is a naive ideal date. It consists of the year, month, and day as attributes.
o time - It is a perfect time, assuming every day has precisely 24*60*60 seconds. It has
hour, minute, second, microsecond, and tzinfo as attributes.
o datetime - It is a grouping of date and time, along with the attributes year, month,
day, hour, minute, second, microsecond, and tzinfo.
o timedelta - It represents the difference between two dates, time or datetime instances
to microsecond resolution.
o tzinfo - It provides time zone information objects.
o timezone - It is included in the new version of Python. It is the class that implements
the tzinfo abstract base class.

The datetime Module


The datetime module enables us to create the custom date objects, perform various
operations on dates like the comparison, etc.

To work with dates as date objects, we have to import the datetime module into the python
source code.

Consider the following example to get the datetime object representation for the current
time.

Example

1. import datetime
2. #returns the current datetime object
3. print(datetime.datetime.now())

Output:

2020-04-04 13:18:35.252578

Creating date objects


We can create the date objects bypassing the desired date in the datetime constructor for
which the date objects are to be created.

Consider the following example.

Example

1. import datetime
2. #returns the datetime object for the specified date
3. print(datetime.datetime(2020,04,04))

Output:
2020-04-04 00:00:00

We can also specify the time along with the date to create the datetime object. Consider the
following example.

Example

1. import datetime
2.
3. #returns the datetime object for the specified time
4.
5. print(datetime.datetime(2020,4,4,1,26,40))

Output:

2020-04-04 01:26:40

In the above code, we have passed in datetime() function year, month, day, hour, minute, and
millisecond attributes in a sequential manner.

Comparison of two dates


We can compare two dates by using the comparison operators like >, >=, <, and <=.

Consider the following example.

Example

1. from datetime import datetime as dt


2. #Compares the time. If the time is in between 8AM and 4PM, then it prints working hours otherwise i
t prints fun hours
3. if dt(dt.now().year,dt.now().month,dt.now().day,8)<dt.now()<dt(dt.now().year,dt.now().month,dt.now
().day,16):
4. print("Working hours....")
5. else:
6. print("fun hours")

Experimental Procedure-

9 Start Google Colab /python Installed on system with editor (like pycharm, jupyter)
10 Type a python program using input, output and calculations
11 Save the program
12 Execute it.

Source code:

import time import datetime


x =datetime.datetime.now() print(x.strftime("%c"))

Precaution and sources of error:


The devices either computers or any other networking device should be handled
with due care and preserved carefully.

Results

Conclusions
A Python program can handle date and time in several ways. Converting between date formats is a
common chore for computers. Python's time and calendar modules help track dates and
times.Thorugh this experiment we learnt to work with date format in python.

Related short question:


i. What is datetime module in python
ii. How to compare two dates
iii. How to convert date from one format to other
iv. How to change format of date
v. What are various functions to be applied on dates
Experiment 5

Experiment name: Creating and manipulating a List

Objectives: To learn how to perform various operations on lists

Prerequisites: knowledge of Python

Key terms: update, add, delete, remove

Experimental set-up/Equipment/Apparatus/Tools: -
7. Computer System
8. Google Colab /python Installed on system with editor (like pycharm, jupyter)

Theory and application

List

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:

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.

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:

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


print(thislist)

List Length

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

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


print(len(thislist))

List Items - Data Types

List items can be of any data type:

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


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

A list can contain different data types:

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

type()

From Python's perspective, lists are defined as objects with the data type '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.
thislist = list(("apple", "banana", "cherry")) # note the double round-brackets
print(thislist)

Python Collections (Arrays)

There are four collection data types in the Python programming language:

 List is a collection which is ordered and changeable. Allows duplicate members.


 Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
 Set is a collection which is unordered and unindexed. No duplicate members.
 Dictionary is a collection which is unordered and changeable. No duplicate members.

When choosing a collection type, it is useful to understand the properties of that type.
Choosing the right type for a particular data set could mean retention of meaning, and, it
could mean an increase in efficiency or security.

Change Item Value

To change the value of a specific item, refer to the index number:

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


thislist[1] = "blackcurrant"
print(thislist)

Change a Range of Item Values

To change the value of items within a specific range, define a list with the new values, and
refer to the range of index numbers where you want to insert the new values:

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]


thislist[1:3] = ["blackcurrant", "watermelon"]
print(thislist)

If you insert more items than you replace, the new items will be inserted where you specified,
and the remaining items will move accordingly:

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


thislist[1:2] = ["blackcurrant", "watermelon"]
print(thislist)

If you insert less items than you replace, the new items will be inserted where you specified,
and the remaining items will move accordingly:
thislist = ["apple", "banana", "cherry"]
thislist[1:3] = ["watermelon"]
print(thislist)

Insert Items

To insert a new list item, without replacing any of the existing values, we can use
the insert() method.

The insert() method inserts an item at the specified index:

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


thislist.insert(2, "watermelon")
print(thislist)

Python - Add List Items


Append Items

To add an item to the end of the list, use the append() method:

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


thislist.append("orange")
print(thislist)

Insert Items

To insert a list item at a specified index, use the insert() method.

The insert() method inserts an item at the specified index:

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


thislist.insert(1, "orange")
print(thislist)

Extend List

To append elements from another list to the current list, use the extend() method.

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


tropical = ["mango", "pineapple", "papaya"]
thislist.extend(tropical)
print(thislist)

The elements will be added to the end of the list.

Add Any Iterable

The extend() method does not have to append lists, you can add any iterable object (tuples,
sets, dictionaries etc.).

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


thistuple = ("kiwi", "orange")
thislist.extend(thistuple)
print(thislist)

Python - Remove List Items


Remove Specified Item

The remove() method removes the specified item.

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


thislist.remove("banana")
print(thislist)

Remove Specified Index

The pop() method removes the specified index.

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


thislist.pop(1)
print(thislist)

If you do not specify the index, the pop() method removes the last item.

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


thislist.pop()
print(thislist)

The del keyword also removes the specified index:


thislist = ["apple", "banana", "cherry"]
del thislist[0]
print(thislist)

The del keyword can also delete the list completely.

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


del thislist

Clear the List

The clear() method empties the list.

The list still remains, but it has no content.

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


thislist.clear()
print(thislist)

Copy a List

You cannot copy a list simply by typing list2 = list1, because: list2 will only be
a reference to list1, and changes made in list1 will automatically also be made in list2.

There are ways to make a copy, one way is to use the built-in List method copy().

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


mylist = thislist.copy()
print(mylist)

Another way to make a copy is to use the built-in method list().

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


mylist = list(thislist)
print(mylist)

Experimental Procedure-

13 Start Google Colab /python Installed on system with editor (like pycharm, jupyter)
14 Type a python program using input, output and calculations
15 Save the program
16 Execute it.
Precaution and sources of error:
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
abc = [2,3,4,5]
print (abc)
print(thislist)
print(thislist[5])
print(thislist[2:5])
print(thislist[:7])
print(thislist[3:])
print(thislist[-3:-1])

list1 = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]


list1.append("papaya")
print(list1)
list1.insert(2, "grapes")
print(list1)
list1.remove("kiwi")
print(list1)
list1.pop(0)
print(list1)
list1.pop()
print(list1)

list3 = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]


list4=list3.copy()
print(list4)
list5 = list(list3)
print(list5)

list6 = list(("apple", "banana", "cherry", "orange", "kiwi"))


print(list6)
list6[3] = "papaya"
print(list6)
list6[1:2] = ["peach", "plum"]
print(list6)
list6[0:3] = ["mango"]
print(list6)

list6.extend(list5)
print(list6)

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]


print(thislist)
print(thislist[3])
print(thislist[1:3])
print(thislist[-1])
print (thislist[-3:-1])
print(thislist[:5])
print(thislist[2:])

list3 = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]


list3.append("papaya")
print(list3)
list3.insert(2, "grapes")
print(list3)
list3.remove("kiwi")
print(list3)
del list3[3]
print(list3)
list3.clear()
print(list3)
del list3

list4 = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]


list5 = list4.copy()
print(list5)
list6=list(list4)
print(list6)
Results
Conclusions
A list is a data structure in Python that is a mutable, or changeable, ordered sequence of elements.
Each element or value that is inside of a list is called an item. Just as strings are defined as characters
between quotes, lists are defined by having values between square brackets [ ] . Thorugh this
experiment we learnt to perform various operations on lists in python.

Related short question:


i. What is a List
ii. How it is different from tuple
iii. How to perform list slicing
iv. How to insert data into list
v. How to delete data from the list
vi. How to generate in python
Experiment 6

Experiment name: Write a program to demonstrate working with tuples in python.

Objectives: To learn how to perform various operations tuples Prerequisites:


Algorithm and logics, basic knowledge of C++

Key terms: tuple, print

Experimental set-up/Equipment/Apparatus/Tools: -
9. Computer System
10. Google Colab /python Installed on system with editor (like pycharm, jupyter)

Theory and application


Python Tuple

Python Tuple is used to store the sequence of immutable Python objects. The tuple is similar
to lists since the value of the items stored in the list can be changed, whereas the tuple is
immutable, and the value of the items stored in the tuple cannot be changed.

Creating a tuple

A tuple can be written as the collection of comma-separated (,) values enclosed with the
small () brackets. The parentheses are optional but it is good practice to use. A tuple can be
defined as follows.

1. T1 = (101, "Peter", 22)


2. T2 = ("Apple", "Banana", "Orange")
3. T3 = 10,20,30,40,50
4.
5. print(type(T1))
6. print(type(T2))
7. print(type(T3))

Output:

<class 'tuple'>
<class 'tuple'>
<class 'tuple'>
Note: The tuple which is created without using parentheses is also known as tuple packing.

An empty tuple can be created as T =()

1. tup1 = ("JavaTpoint")
2. print(type(tup1))
3. #Creating a tuple with single element
4. tup2 = ("JavaTpoint",)
5. print(type(tup2))

Output:

<class 'str'>
<class 'tuple'>

A tuple is indexed in the same way as the lists. The items in the tuple can be accessed by
using their specific index value.

Consider the following example of tuple:

Example - 1
1. tuple1 = (10, 20, 30, 40, 50, 60)
2. print(tuple1)
3. count = 0
4. for i in tuple1:
5. print("tuple1[%d] = %d"%(count, i))
6. count = count+1

Output:

(10, 20, 30, 40, 50, 60)


tuple1[0] = 10
tuple1[1] = 20
tuple1[2] = 30
tuple1[3] = 40
tuple1[4] = 50
tuple1[5] = 60

Example - 2
1. tuple1 = tuple(input("Enter the tuple elements ..."))
2. print(tuple1)
3. count = 0
4. for i in tuple1:
5. print("tuple1[%d] = %s"%(count, i))
6. count = count+1

Output:

Enter the tuple elements ...123456


('1', '2', '3', '4', '5', '6')
tuple1[0] = 1
tuple1[1] = 2
tuple1[2] = 3
tuple1[3] = 4
tuple1[4] = 5
tuple1[5] = 6

A tuple is indexed in the same way as the lists. The items in the tuple can be accessed by
using their specific index value.

We will see all these aspects of tuple in this section of the tutorial.

Tuple indexing and slicing

The indexing and slicing in the tuple are similar to lists. The indexing in the tuple starts from
0 and goes to length(tuple) - 1.

The items in the tuple can be accessed by using the index [] operator. Python also allows us
to use the colon operator to access multiple items in the tuple.

Consider the following image to understand the indexing and slicing in detail.

Consider the following example:


1. tup = (1,2,3,4,5,6,7)
2. print(tup[0])
3. print(tup[1])
4. print(tup[2])
5. # It will give the IndexError
6. print(tup[8])

Output:

1
2
3
tuple index out of range

In the above code, the tuple has 7 elements which denote 0 to 6. We tried to access an
element outside of tuple that raised an IndexError.

1. tuple = (1,2,3,4,5,6,7)
2. #element 1 to end
3. print(tuple[1:])
4. #element 0 to 3 element
5. print(tuple[:4])
6. #element 1 to 4 element
7. print(tuple[1:5])
8. # element 0 to 6 and take step of 2
9. print(tuple[0:6:2])

Output:

(2, 3, 4, 5, 6, 7)
(1, 2, 3, 4)
(1, 2, 3, 4)
(1, 3, 5)

Negative Indexing

The tuple element can also access by using negative indexing. The index of -1 denotes the
rightmost element and -2 to the second last item and so on.

The elements from left to right are traversed using the negative indexing. Consider the
following example:
1. tuple1 = (1, 2, 3, 4, 5)
2. print(tuple1[-1])
3. print(tuple1[-4])
4. print(tuple1[-3:-1])
5. print(tuple1[:-1])
6. print(tuple1[-2:])

Output:

5
2
(3, 4)
(1, 2, 3, 4)
(4, 5)

Deleting Tuple

Unlike lists, the tuple items cannot be deleted by using the del keyword as tuples are
immutable. To delete an entire tuple, we can use the del keyword with the tuple name.

Consider the following example.

1. tuple1 = (1, 2, 3, 4, 5, 6)
2. print(tuple1)
3. del tuple1[0]
4. print(tuple1)
5. del tuple1
6. print(tuple1)

Output:

(1, 2, 3, 4, 5, 6)
Traceback (most recent call last):
File "tuple.py", line 4, in <module>
print(tuple1)
NameError: name 'tuple1' is not defined

Experimental Procedure-

17 Start Google Colab /python Installed on system with editor (like pycharm, jupyter)
18 Type a python program using input, output and calculations
19 Save the program
20 Execute it.

# creating tuples with college names..

colleges = ("SIIET","BHARAT","GNIT", "AVN")

print("the lists in colleges tuple is",colleges)

print("we can\'t add or remove

new elements in a tuple")

print("length of the tuple colleges

is:",len(colleges))

# checking whether 'SIIET' is present in the tuple or not

if "SIIET" in colleges:

print("Yes, 'SIIET' is in the colleges tuple")

Precaution and sources of error:


The devices either computers or any other networking device should be handled
with due care and preserved carefully.

Results

Conclusions
A tuple is a collection of objects which ordered and immutable. Tuples are sequences, just
like lists. The differences between tuples and lists are, the tuples cannot be changed unlike
lists and tuples use parentheses, whereas lists use square brackets. Creating a tuple is as
simple as putting different comma-separated values. Thorugh this experiment we learnt to
perform various operations on tuple in python.

Related short question:


Write properties of tuple
What‟s the difference between lists and tuples
Tell the operations of tuple
Experiment 7

Experiment name: Write a program to demonstrate working with dictionaries in python.

Objectives: To learn how to perform various operations on dictionaries

Prerequisites: Algorithm and logics, basic knowledge of C++

Key terms: update, add, delete, remove

Experimental set-up/Equipment/Apparatus/Tools: -
11. Computer System
12. Google Colab /python Installed on system with editor (like pycharm, jupyter)

Theory and application


Python Dictionary
Python Dictionary is used to store the data in a key-value pair format. The dictionary is the
data type in Python, which can simulate the real-life data arrangement where some specific
value exists for some particular key. It is the mutable data-structure. The dictionary is defined
into element Keys and values.

o Keys must be a single element


o Value can be any type such as list, tuple, integer, etc.

In other words, we can say that a dictionary is the collection of key-value pairs where the
value can be any Python object. In contrast, the keys are the immutable Python object, i.e.,
Numbers, string, or tuple.

Creating the dictionary


The dictionary can be created by using multiple key-value pairs enclosed with the curly
brackets {}, and each key is separated from its value by the colon (:).The syntax to define the
dictionary is given below.

Syntax:

5.3M
115

HTML Tutorial

1. Dict = {"Name": "Tom", "Age": 22}

In the above dictionary Dict, The keys Name and Age are the string that is an immutable
object.

Let's see an example to create a dictionary and print its content.

1. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}


2. print(type(Employee))
3. print("printing Employee data .... ")
4. print(Employee)

Output

<class 'dict'>
Printing Employee data ....
{'Name': 'John', 'Age': 29, 'salary': 25000, 'Company': 'GOOGLE'}

Python provides the built-in function dict() method which is also used to create dictionary.
The empty curly braces {} is used to create empty dictionary.

1. # Creating an empty Dictionary


2. Dict = {}
3. print("Empty Dictionary: ")
4. print(Dict)
5.
6. # Creating a Dictionary
7. # with dict() method
8. Dict = dict({1: 'Java', 2: 'T', 3:'Point'})
9. print("\nCreate Dictionary by using dict(): ")
10. print(Dict)
11.
12. # Creating a Dictionary
13. # with each item as a Pair
14. Dict = dict([(1, 'Devansh'), (2, 'Sharma')])
15. print("\nDictionary with each item as a pair: ")
16. print(Dict)

Output:

Empty Dictionary:
{}

Create Dictionary by using dict():


{1: 'Java', 2: 'T', 3: 'Point'}

Dictionary with each item as a pair:


{1: 'Devansh', 2: 'Sharma'}

Accessing the dictionary values


We have discussed how the data can be accessed in the list and tuple by using the indexing.

However, the values can be accessed in the dictionary by using the keys as keys are unique in
the dictionary.

The dictionary values can be accessed in the following way.

1. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}


2. print(type(Employee))
3. print("printing Employee data .... ")
4. print("Name : %s" %Employee["Name"])
5. print("Age : %d" %Employee["Age"])
6. print("Salary : %d" %Employee["salary"])
7. print("Company : %s" %Employee["Company"])

Output:

<class 'dict'>
printing Employee data ....
Name : John
Age : 29
Salary : 25000
Company : GOOGLE

Python provides us with an alternative to use the get() method to access the dictionary values.
It would give the same result as given by the indexing.
Adding dictionary values
The dictionary is a mutable data type, and its values can be updated by using the specific
keys. The value can be updated along with key Dict[key] = value. The update() method is
also used to update an existing value.

Note: If the key-value already present in the dictionary, the value gets updated. Otherwise,
the new keys added in the dictionary.

Let's see an example to update the dictionary values.

Example - 1:

1. # Creating an empty Dictionary


2. Dict = {}
3. print("Empty Dictionary: ")
4. print(Dict)
5.
6. # Adding elements to dictionary one at a time
7. Dict[0] = 'Peter'
8. Dict[2] = 'Joseph'
9. Dict[3] = 'Ricky'
10. print("\nDictionary after adding 3 elements: ")
11. print(Dict)
12.
13. # Adding set of values
14. # with a single Key
15. # The Emp_ages doesn't exist to dictionary
16. Dict['Emp_ages'] = 20, 33, 24
17. print("\nDictionary after adding 3 elements: ")
18. print(Dict)
19.
20. # Updating existing Key's Value
21. Dict[3] = 'JavaTpoint'
22. print("\nUpdated key value: ")
23. print(Dict)
Output:

Empty Dictionary:
{}

Dictionary after adding 3 elements:


{0: 'Peter', 2: 'Joseph', 3: 'Ricky'}

Dictionary after adding 3 elements:


{0: 'Peter', 2: 'Joseph', 3: 'Ricky', 'Emp_ages': (20, 33, 24)}

Updated key value:


{0: 'Peter', 2: 'Joseph', 3: 'JavaTpoint', 'Emp_ages': (20, 33, 24)}

Example - 2:

1. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}


2. print(type(Employee))
3. print("printing Employee data .... ")
4. print(Employee)
5. print("Enter the details of the new employee....");
6. Employee["Name"] = input("Name: ");
7. Employee["Age"] = int(input("Age: "));
8. Employee["salary"] = int(input("Salary: "));
9. Employee["Company"] = input("Company:");
10. print("printing the new data");
11. print(Employee)

Output:

Empty Dictionary:
{}

Dictionary after adding 3 elements:


{0: 'Peter', 2: 'Joseph', 3: 'Ricky'}

Dictionary after adding 3 elements:


{0: 'Peter', 2: 'Joseph', 3: 'Ricky', 'Emp_ages': (20, 33, 24)}

Updated key value:


{0: 'Peter', 2: 'Joseph', 3: 'JavaTpoint', 'Emp_ages': (20, 33, 24)}

Deleting elements using del keyword


The items of the dictionary can be deleted by using the del keyword as given below.
1. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}
2. print(type(Employee))
3. print("printing Employee data .... ")
4. print(Employee)
5. print("Deleting some of the employee data")
6. del Employee["Name"]
7. del Employee["Company"]
8. print("printing the modified information ")
9. print(Employee)
10. print("Deleting the dictionary: Employee");
11. del Employee
12. print("Lets try to print it again ");
13. print(Employee)

Output:

<class 'dict'>
printing Employee data ....
{'Name': 'John', 'Age': 29, 'salary': 25000, 'Company': 'GOOGLE'}
Deleting some of the employee data
printing the modified information
{'Age': 29, 'salary': 25000}
Deleting the dictionary: Employee
Lets try to print it again
NameError: name 'Employee' is not defined

The last print statement in the above code, it raised an error because we tried to print the
Employee dictionary that already deleted.

o Using pop() method

The pop() method accepts the key as an argument and remove the associated value. Consider
the following example.

1. # Creating a Dictionary
2. Dict = {1: 'JavaTpoint', 2: 'Peter', 3: 'Thomas'}
3. # Deleting a key
4. # using pop() method
5. pop_ele = Dict.pop(3)
6. print(Dict)
Output:

{1: 'JavaTpoint', 2: 'Peter'}

Python also provides a built-in methods popitem() and clear() method for remove elements
from the dictionary. The popitem() removes the arbitrary element from a dictionary, whereas
the clear() method removes all elements to the whole dictionary.

Iterating Dictionary
A dictionary can be iterated using for loop as given below.

Example 1
# for loop to print all the keys of a dictionary

1. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}


2. for x in Employee:
3. print(x)

Output:

Name
Age
salary
Company

Example 2
#for loop to print all the values of the dictionary

1. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}


2. for x in Employee:
3. print(Employee[x])

Output:

John
29
25000
GOOGLE
Example - 3
#for loop to print the values of the dictionary by using values() method.

1. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}


2. for x in Employee.values():
3. print(x)

Output:

John
29
25000
GOOGLE

Example 4
#for loop to print the items of the dictionary by using items() method.

1. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}


2. for x in Employee.items():
3. print(x)

Output:

('Name', 'John')
('Age', 29)
('salary', 25000)
('Company', 'GOOGLE')

Properties of Dictionary keys


1. In the dictionary, we cannot store multiple values for the same keys. If we pass more than
one value for a single key, then the value which is last assigned is considered as the value of
the key.

Consider the following example.

1. Employee={"Name":"John","Age":29,"Salary":25000,"Company":"GOOGLE","Name":"John"}
2. for x,y in Employee.items():
3. print(x,y)

Output:
Name John
Age 29
Salary 25000
Company GOOGLE

2. In python, the key cannot be any mutable object. We can use numbers, strings, or tuples as
the key, but we cannot use any mutable object like the list as the key in the dictionary.

Consider the following example.

1. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE",


[100,201,301]:"Department ID"}
2. for x,y in Employee.items():
3. print(x,y)

Output:

Traceback (most recent call last):


File "dictionary.py", line 1, in
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE",
[100,201,301]:"Department ID"}
TypeError: unhashable type: 'list'

Experimental Procedure-

21 Start Google Colab /python Installed on system with editor (like pycharm, jupyter)
22 Type a python program using input, output and calculations
23 Save the program
24 Execute it.

# creating a dictionary for SIIET


college = { "name": "siiet",
"code": "INDI",
"id": "x3"

}
print(college)
#adding items to dictionary college["location"] = "IBP" print(college)
#changing values of a key college["location"] = "sheriguda" print(college)
# to remove items use pop() college.pop("code") print(college)
#know the length using len() print("length of college is:",len(college)) #to copy the same
dictionary use copy() mycollege= college.copy() print(mycollege)
Precaution and sources of error:
The devices either computers or any other networking device should be handled
with due care and preserved carefully.

Results

Conclusions
A dictionary is a data structure in Python that is a mutable, or changeable, unordered elements. Keys
are unique within a dictionary while values may not be. The values of a dictionary can be of any type,
but the keys must be of an immutable data type such as strings, numbers, or tuples. Through this
experiment we learnt to perform various operations on dictionaries in python.

Related short question:

1. How to initialize a dictionary in python?


2. How to get all the keys from the dictionary?
3. When to choose dictionary instead of a list?
4. What is a key of dictionary
5. How to create dictionary
6. How to retrieve all the values in a dictionary?
Experiment 8

Experiment name: Write a python program to find largest of three numbers.


List

Objectives: To learn how to use conditional statement in python

Prerequisites: Algorithm and logics, basic knowledge of C++

Key terms: if, elif, else

Experimental set-up/Equipment/Apparatus/Tools: -
13. Computer System
14. Google Colab /python Installed on system with editor (like pycharm, jupyter)

Theory and application

Decision making is anticipation of conditions occurring while execution of the program and
specifying actions taken according to the conditions.
Decision structures evaluate multiple expressions which produce TRUE or FALSE as
outcome. You need to determine which action to take and which statements to execute if
outcome is TRUE or FALSE otherwise.
Following is the general form of a typical decision making structure found in most of the
programming languages −

Python programming language assumes any non-zero and non-null values as TRUE, and if
it is either zero or null, then it is assumed as FALSE value.
Python programming language provides following types of decision making statements.
Click the following links to check their detail.

Sr.No Statement & Description


.

1 if statements

An if statement consists of a boolean expression followed by one or more statements.

2 if...else statements

An if statement can be followed by an optional else statement, which executes when the
boolean expression is FALSE.

3 nested if statements

You can use one if or else if statement inside another if or else if statement(s).

In general, statements are executed sequentially: The first statement in a function is executed
first, followed by the second, and so on. There may be a situation when you need to execute
a block of code several number of times.
Programming languages provide various control structures that allow for more complicated
execution paths.

Experimental Procedure-

25 Start Google Colab /python Installed on system with editor (like pycharm, jupyter)
26 Type a python program using input, output and calculations
27 Save the program
28 Execute it.

# user-defined function to know which number is


larger def bigOf3(a,b,c):
if(a>b):
if(a>c):
print("a is greater than b and c")
else:
print("c is greater than a and b")
elif(b>c):
print("b is greater than a and c")
else:
print("c is greater than a and b")

txt= input("enter a,b,c values:")


a,b,c= txt.split()
bigOf3(int(a),int(b),int(c)) #calling the function

Precaution and sources of error:


The devices either computers or any other networking device should be handled
with due care and preserved carefully.

Results

Conclusions

Decision making is anticipation of conditions occurring while execution of the program and
specifying actions taken according to the conditions.
Decision structures evaluate multiple expressions which produce TRUE or FALSE as
outcome. You need to determine which action to take and which statements to execute if
outcome is TRUE or FALSE otherwise. Thorugh this experiment we learnt to work with
conditional statements in python.

Related short question:


What are various conditional statement in python
Explain nested if
Explain if elif else
Experiment 9
Experiment name: Write a Python program to convert temperatures to and from Celsius,
Fahrenheit.

Objectives: To learn how to convert to and from Celsius, Fahrenheit using formula

Prerequisites: Algorithm and logics, basic knowledge of C++

Key terms: Celsius, Fahrenheit

Experimental set-up/Equipment/Apparatus/Tools: -
15. Computer System
16. Google Colab /python Installed on system with editor (like pycharm, jupyter)

Theory and application

Formula: c/5 = f-32/9


f=((9*c)/5)+32

A loop statement allows us to execute a statement or group of statements multiple times.


The following diagram illustrates a loop statement −

Python programming language provides following types of loops to handle looping


requirements.

Sr.No. Loop Type & Description


1 while loop

Repeats a statement or group of statements while a given condition is TRUE. It tests the
condition before executing the loop body.

2 for loop

Executes a sequence of statements multiple times and abbreviates the code that manages the
loop variable.

3 nested loops

You can use one or more loop inside any another while, for or do..while loop.

Loop Control Statements


Loop control statements change execution from its normal sequence. When execution leaves
a scope, all automatic objects that were created in that scope are destroyed.
Python supports the following control statements. Click the following links to check their
detail.
Let us go through the loop control statements briefly

Sr.No. Control Statement & Description

1 break statement

Terminates the loop statement and transfers execution to the statement immediately following
the loop.

2 continue statement

Causes the loop to skip the remainder of its body and immediately retest its condition prior to
reiterating.

3 pass statement

The pass statement in Python is used when a statement is required syntactically but you do not
want any command or code to execute.
Experimental Procedure-

29 Start Google Colab /python Installed on system with editor (like pycharm, jupyter)
30 Type a python program using input, output and calculations
31 Save the program
32 Execute it.

while(1):
print("1.CELSIUS TO FAHRENHEIT\n2.FAHRENHEIT TO CELSIUS\n3.EXIT\n")
choice=input("ENTER YOUR CHOICE:")
ch=int(choice)
if(ch==1):
c=int(input("ENTER TEMPERATURE IN CELSIUS:"))
f=((9*c)/5)+32
print("converted temperature is:",f) elif(ch==2):
f=int(input("ENTER TEMPERATURE IN FAHRENHEIT:"))
c=((f-32)/9)*5
print("converted temperature is:",c) elif(ch==3):
exit()
else:
print("wrong choice")

Precaution and sources of error:


The devices either computers or any other networking device should be handled
with due care and preserved carefully.

Results
Conclusions
Thorugh this experiment we learnt about loops and conversion of temperatures to and from
Celsius, Fahrenheit.

in python.

Related short question:


Write formula of conversion temperatures to and from Celsius, Fahrenheit.
Write syntax of while loop
Write syntax of for loop
Experiment 10

Experiment name: Write a Python program to construct the following pattern, using a
nested for
loop
*
**
***
****
***
**
**
*

Objectives: To learn how to work with nested loops in python

Prerequisites: Algorithm and logics, basic knowledge of C++

Key terms: for, while, print

Experimental set-up/Equipment/Apparatus/Tools: -
17. Computer System
18. Google Colab /python Installed on system with editor (like pycharm, jupyter)

Theory and application


A nested loop is an inner loop in the loop body of the outer loop. The inner or outer loop can
be any type, such as a while loop or for loop. For example, the outer for loop can contain
a while loop and vice versa.

The outer loop can contain more than one inner loop. There is no limitation on the chaining
of loops.

In the nested loop, the number of iterations will be equal to the number of iterations in the
outer loop multiplied by the iterations in the inner loop.

In each iteration of the outer loop inner loop execute all its iteration. For each iteration of an
outer loop the inner loop re-start and completes its execution before the outer loop can
continue to its next iteration.
Nested loops are typically used for working with multidimensional data structures, such as
printing two-dimensional arrays, iterating a list that contains a nested list.

A nested loop is a part of a control flow statement which helps you to understand the basics
of Python.

Python Nested for Loop

In Python, the for loop is used to iterate over a sequence such as a list, string, tuple, other
iterable objects such as range.

Syntax of using a nested for loop in Python

# outer for loop


for element in sequence
# inner for loop
for element in sequence:
body of inner for loop
body of outer for loop

In this example, we are using a for loop inside a for loop. In this example, we
are printing a multiplication table of the first ten numbers.

 The outer for loop uses the range() function to iterate over the first ten numbers
 The inner for loop will execute ten times for each outer number
 In the body of the inner loop, we will print the multiplication of the outer
number and current number
 The inner loop is nothing but a body of an outer loop.
Nested Loop to Print Pattern

Another most common use of nested loop is to print various star and number pattern.

Let’s see how to use nested loop to print the following pattern in Python.

Pattern:

**

***

****

*****

Program:

rows = 5
# outer loop
for i in range(1, rows + 1):
# inner loop
for j in range(1, i + 1):
print("*", end=" ")
print('')

 In this program, the outer loop is the number of rows print.


 The number of rows is five, so the outer loop will execute five times
 Next, the inner loop is the total number of columns in each row.
 For each iteration of the outer loop, the columns count gets incremented by 1
 In the first iteration of the outer loop, the column count is 1, in the next it 2. and
so on.
 The inner loop iteration is equal to the count of columns.
 In each iteration of an inner loop, we print star
Experimental Procedure-

33 Start Google Colab /python Installed on system with editor (like pycharm, jupyter)
34 Type a python program using input, output and calculations
35 Save the program
36 Execute it.

n=int(input("ENTER A VALUE:"))

for x in range(0,n+1,1):
print(x*'*')
if(x==n):
for x in range(n,0,-1):
print(x*'*')

Precaution and sources of error:


The devices either computers or any other networking device should be handled
with due care and preserved carefully.

Results

Conclusions
Nested loops are typically used for working with multidimensional data structures,
such as printing two-dimensional arrays, iterating a list that contains a nested list..
Through this experiment we learnt about nested loop and how generate various patterns in
python.

Related short question:


What is a nested loop
Write syntax for nested for loop
How to nest while in for loop
Experiment 11

Experiment name: Write a Python script that prints prime numbers less than 20.

Objectives: To learn how to find out whether number is prime or not

Prerequisites: Algorithm and logics, basic knowledge of C++

Key terms: for, break, while

Experimental set-up/Equipment/Apparatus/Tools: -
19. Computer System
20. Google Colab /python Installed on system with editor (like pycharm, jupyter)

Theory and application


Python break statement
The break is a keyword in python which is used to bring the program control out of the loop.
The break statement breaks the loops one by one, i.e., in the case of nested loops, it breaks
the inner loop first and then proceeds to outer loops. In other words, we can say that break is
used to abort the current execution of the program and the control goes to the next line after
the loop.

The break is commonly used in the cases where we need to break the loop for a given
condition.

The syntax of the break is given below.

1. #loop statements
2. break;

Example 1
1. list =[1,2,3,4]
2. count = 1;
3. for i in list:
4. if i == 4:
5. print("item matched")
6. count = count + 1;
7. break
8. print("found at",count,"location");

Output:

s Java

item matched
found at 2 location

Experimental Procedure-

37 Start Google Colab /python Installed on system with editor (like pycharm, jupyter)
38 Type a python program using input, output and calculations
39 Save the program
40 Execute it.

n=int(input("enter range of prime numbers:"))

for num in range(2,n+1): #takes each number

count=0

for i in range(2,num//2+1): #checks the divisibility of each num

if(num%i==0):

count=count+1 #if its noot prime count increases.

if(count==0): print(num)

Precaution and sources of error:


The devices either computers or any other networking device should be handled
with due care and preserved carefully.

Results
Conclusions
The break is commonly used in the cases where we need to break the loop for a given condition.
Through this experiment we learnt to work with break statement in python.

Related short question:


What is the use of break statement?
What is the use of continue statement
What is the difference between break statement and continue statement
Experiment 12

Experiment name: Write a python program to find factorial of a number using


Recursion.

Objectives: To learn how to perform recursion in python

Prerequisites: Algorithm and logics, basic knowledge of C++

Key terms: for, while

Experimental set-up/Equipment/Apparatus/Tools: -
21. Computer System
22. Google Colab /python Installed on system with editor (like pycharm, jupyter)

Theory and application


Recursion in Python
The term Recursion can be defined as the process of defining something in terms of itself. In
simple words, it is a process in which a function calls itself directly or indirectly.

Advantages of using recursion


 A complicated function can be split down into smaller sub-problems utilizing recursion.
 Sequence creation is simpler through recursion than utilizing any nested iteration.
 Recursive functions render the code look simple and effective.
Disadvantages of using recursion
 A lot of memory and time is taken through recursive calls which makes it expensive for
use.
 Recursive functions are challenging to debug.
 The reasoning behind recursion can sometimes be tough to think through.

Syntax:

def func(): <--


|
| (recursive call)
|
func() ----
Example 1:
A Fibonacci sequence is the integer sequence of 0, 1, 1, 2, 3, 5, 8....

# Program to print the fibonacci series upto n_terms

# Recursive function

def recursive_fibonacci(n):

if n <= 1:

return n

else:

return(recursive_fibonacci(n-1) + recursive_fibonacci(n-2))

n_terms = 10

# check if the number of terms is valid

if n_terms <= 0:

print("Invalid input ! Please input a positive value")

else:

print("Fibonacci series:")

for i in range(n_terms):

print(recursive_fibonacci(i))

Output:
Fibonacci series:
0
1
1
2
3
5
8
13
21
34

Experimental Procedure-

41 Start Google Colab /python Installed on system with editor (like pycharm, jupyter)
42 Type a python program using input, output and calculations
43 Save the program
44 Execute it.

# Program to print factorial of a number


# recursively.
# Recursive function
def recursive_factorial(n):
if n == 1:
return n
else:
return n * recursive_factorial(n-1)
# user input
num = 6
# check if the input is valid or not
if num < 0:
print("Invalid input ! Please enter a positive number.")
elif num == 0:
print("Factorial of number 0 is 1")
else:
print("Factorial of number", num, "=", recursive_factorial(num))

Output:

Factorial of number 6 = 720

Precaution and sources of error:


The devices either computers or any other networking device should be handled
with due care and preserved carefully.

Results

Conclusions
Recursive functions render the code look simple and effective.
Through this experiment we learnt to implement recursion in python.

Related short question:


1. What is recursion
2. What is the difference between loop and recursion
3. What are the advantages of recursion
4. What are the disadvantages of recursion
Experiment 13
Experiment name: Write a program that accepts the lengths of three sides of a triangle as
inputs. The program output should indicate whether or not the triangle is a right
triangle (Recall from the Pythagorean Theorem that in a right triangle, the
square of one side equals the sum of the squares of the other two sides).

Objectives: To learn to implement a program to check whether the triangle is right angle
triangle or not

Prerequisites: Pythagorean theorem, Algorithm and logics, basic knowledge of C++

Key terms: Pythagorean Theorem, triangle

Experimental set-up/Equipment/Apparatus/Tools: -
23. Computer System
24. Google Colab /python Installed on system with editor (like pycharm, jupyter)

Theory and application

In mathematics, the Pythagorean theorem, also known as Pythagoras' theorem, is a


fundamental relation in Euclidean geometry among the three sides of a right triangle. It states
that the square of the hypotenuse (the side opposite the right angle) is equal to the sum of the
squares of the other two sides.
Function used

pythagorean(a,b,c)
Experimental Procedure-

45 Start Google Colab /python Installed on system with editor (like pycharm, jupyter)
46 Type a python program using input, output and calculations
47 Save the program
48 Execute it.

a=float(input("enter length of hypotenuse side:"))

b=float(input("enter length of base side:"))

c=float(input("enter length of height side:")) def pythagorean(a,b,c): #defining function


a=a*a; b=b*b; c=c*c
if(a==b+c):

print("yes!! the given inputs are triplets of a right angled triangle!!") print("height:",c**0.5,"\
nbase:",b**0.5,"\nhypotenuse:",a**0.5)
pythagorean(a,b,c) # calling function

Precaution and sources of error:


The devices either computers or any other networking device should be handled
with due care and preserved carefully.

Results

Conclusion

Through this experiment we learnt to use pythogorean function in python.

Related short question:


1. What is pythogorous theorem
2. Whicht function implement pythogorous theorem in python
3. Whar are the inputs for pythagorean() function

Experiment 14
Experiment name: Write a python program to define a module to find Fibonacci
Numbers and import the module to another program.

Objectives: To learn how to perform various operations on modules.

Prerequisites: Algorithm and logics, basic knowledge of C++

Key terms: module, import, Fibonacci

Experimental set-up/Equipment/Apparatus/Tools: -
25. Computer System
26. Google Colab /python Installed on system with editor (like pycharm, jupyter)

Theory and application


The Fibonacci numbers are the numbers in the following integer sequence.
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ……..
In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence
relation
Fn = Fn-1 + Fn-2
with seed values
F0 = 0 and F1 = 1.

Any non-trivial Python program would be organized in multiple files, connected with each
other using imports. Python, as most of the other programming languages, uses this modular
program structure, where functionalities are grouped in to reusable units. In general, we can
distinguish three types of files in a multi-file Python application:

 top-level file: A Python file, or script, which is the main entry point of the program.
This file is run to launch your application.
 user-defined modules: Python files which are imported in to the top-level file, or
among each other, and provide separate functionalities. These files are usually not
launched directly from your command prompt, and are custom-made for the purpose
of the project.
 standard library modules: Pre-coded modules which are built-in to the Python
installation package, such as platform-independent tools for system interfaces,
Internet scripting, GUI construction, and others. These modules are not part of the
Python executable itself, but part of the standard Python library.

Figure 1 shows an example program structure with the three file types:
Figure 1: An example program structure including a top-level script, custom modules, and
standard library modules.

In this figure, the module 'top_module.py' is a top-level Python file which imports tools
defined in module 'module1', but also has access to tools in 'module2' through 'module1'. The
two custom modules use each other's resources, as well as other modules from the standard
Python library. The importing chain can go as deep as you want: there's no limit in the
number of imported files, and they can import each-other, although you need to be careful
with circular importing.

Let's illustrate this through a code example:

# top_module.py
import module1
module1.print_parameters()
print(module1.combinations(5, 2))

# module1.py
from module2 import k, print_parameters
from math import factorial
n = 5.0
def combinations(n, k):
return factorial(n) / factorial(k) / factorial(n-k)

# module2.py
import module1
k = 2.0
def print_parameters():
print('k = %.f n = %.f' % (k, module1.n))

In the above example, 'top_module.py' is a top-level module that will be run by the user, and
it imports tools from other modules through 'module1.py'. module1 and module2 are user-
defined modules, while the 'math' module is imported from the standard Python library.
When running the top-level script, we get:

$ python top_module.py
k=2n=5
10.0

When a top-level Python file is run, its source code statements, and the statements within
imported modules, are compiled in an intermediate format known as byte code, which is a
platform-independent format. Byte code files of imported modules are stored with a .pyc
extension in the same directory as the .py file for Python versions up to 3.2, and in
directory __pycache__ in the program's home directory in Python 3.2+.

$ ls __pycache__/
module1.cpython-36.pyc module2.cpython-36.pyc

Dual-Mode Code

As mentioned earlier, Python files can also be designed as both importable modules and top-
level scripts. That is, when run, the Python module will run as a stand-alone program, and
when imported, it will act as a importable module containing code definitions.

This is easily done using the attribute __name__ , which is automatically built into every
module. If the module is run as a top-level script the __name__ attribute will equal to the
string "__main__", otherwise if imported, it will contain the name of the actual module.

Here's an example of dual-mode code:

code:

# hiprinter.py

# Name definitions part


multiply = 3
def print_hi():
print("Hi!" * multiply)

# Stand-alone script part


if __name__ == '__main__':
print_hi()
The above 'hiprinter.py' file defines a function, which will be exposed to the client when it's
imported. If the file is run as a stand-alone program, the same function is called
automatically. The difference here, compared with the 'my_script.py' example in Section The
Basics, is that when 'hiprinter.py' is imported it won't run the code nested under the if
__name__ == '__main__' statement.

# Terminal window

$ python hiprinter.py
Hi!Hi!Hi!
# Python interpreter

>> import hiprinter


>> hiprinter.print_hi()
Hi!Hi!Hi!

The dual-mode code is very common in practice, and especially useful for unit-testing: while
variables and functions are defined as top-level names in the file, the part inside
the if statement can serve as a testing area of the above defined names.

Using a Module

Import Statements

The example in Section Program Architecture was useful to look at the difference between
two importing statements: import and from. The main difference is that import loads the
entire module as a single object, while from loads specific properties and functions from the
module. Importing names with the from statement can then be used directly in the importer
module, without calling the imported object name.

Using the from statement is only allowed in the top-level of the module file in Python 3.x,
and not within a function. Python 2.x allows to use it in a function, but issues a warning.
Performance-wise, the from statement is slower than import because it does all the work
that import does - going through all the content of the imported module, and then does an
extra step in selecting the appropriate names for importing.

There's also a third import statement from * which is used to import all top-level names from
the imported module and use them directly in the importer class. For example we could have
used:

from module2 import *

This would import all names (variables and functions) from the module2.py file. This
approach is not recommended because of possible name duplication - the imported names
could overwrite already existing names in the importer module.
Experimental Procedure-

49 Start Google Colab /python Installed on system with editor (like pycharm, jupyter)
50 Type a python program using input, output and calculations
51 Save the program
52 Execute it.

Source code:
fibonacci.py
def fibonacci(n):
n1=0; n2=1;
print(n1)
print(n2)
for x in range(0,n):
n3=n1+n2
if(n3>=n):
break;
print(n3,end = ' ')
n1=n2
n2=n3

using_fibonacci.py

Note: we will be using previous program as a library or package It is mandatory to


write both the programs are separately

import fibonacci
n=int(input("enter range:"))
if(n<0):
print("enter correct range!!")
else:

print("FIBONACCI SERIES \n")

fibonacci.fibonacci (n)

Precaution and sources of error:


The devices either computers or any other networking device should be handled
with due care and preserved carefully.
Results

Conclusions
Python, as most of the other programming languages, uses this modular program structure,
where functionalities are grouped in to reusable units. Thorugh this experiment we learnt to
create and import module in python.

Related short question:


What is a module?
Explain import key word
What is the meaning of * with import statement
Write syntax for importing function from module
Experiment 15

Experiment name: Write a python program to define a module and import a specific
function in that module to another program.

Objectives: To learn how to import a particular function of module into another program
Prerequisites: Algorithm and logics, basic knowledge of C++

Key terms: module, import

Experimental set-up/Equipment/Apparatus/Tools: -
1. Computer System
2. Google Colab /python Installed on system with editor (like pycharm, jupyter)

Theory and application


Import module in Python
 Difficulty Level : Easy
 Last Updated : 12 May, 2021
Import in python is similar to #include header_file in C/C++. Python modules can get
access to code from another module by importing the file/function using import. The
import statement is the most common way of invoking the import machinery, but it is
not the only way.
import module_name
When the import is used, it searches for the module initially in the local scope by
calling __import__() function. The value returned by the function is then reflected in
the output of the initial code.
 PYTHON

import math

print(math.pi)

Output:
3.141592653589793
import module_name.member_name
In the above code module, math is imported, and its variables can be accessed by
considering it to be a class and pi as its object.
The value of pi is returned by __import__().
pi as a whole can be imported into our initial code, rather than importing the whole
module.

rom math import pi

# Note that in the above example,


# we used math.pi. Here we have used
# pi directly.
print(pi)

Output:
3.141592653589793

from module_name import *


In the above code module, math is not imported, rather just pi has been imported as a
variable. All the functions and constants can be imported using *.

from math import *

print(pi)

print(factorial(6))

Output:
3.141592653589793
720
As said above import uses __import__() to search for the module, and if not found, it
would raise ImportError

Experimental Procedure-

53 Start Google Colab /python Installed on system with editor (like pycharm, jupyter)
54 Type a python program using input, output and calculations
55 Save the program
56 Execute it.

fibonacci.py

def fibonacci(n):
n1=0; n2=1;
print(n1)

print(n2)

for x in range(0,n):
n3=n1+n2 if(n3>=n):
break;
print(n3,end = ' ')
n1=n2
n2=n3

using_fibonacci.py

Note: we will be using previous program as a library or package It is mandatory to


write both the programs are separately

from fibonacci import fibonacci


n=int(input("enter range:"))
if(n<0):
print("enter correct range!!")
else:
print(" fibonacci (n)

Precaution and sources of error:


The devices either computers or any other networking device should be handled
with due care and preserved carefully.

Results

Conclusions
Through this experiment we learnt how to import specific function of a module into another
program in python.

Related short question:


What is a module?
Explain import key word
What is the meaning of * with import statement
Write syntax for importing function from module
Experiment 16

Experiment name: Write a script named copyfile.py. This script should prompt the user
for the names of two text files. The contents of the first file should be input and written
to the second file.

Objectives: To learn how to take one file as a input to another file in python

Prerequisites: Algorithm and logics, basic knowledge of C++

Key terms: open, close, file

Experimental set-up/Equipment/Apparatus/Tools: -
3. Computer System
4. Google Colab /python Installed on system with editor (like pycharm, jupyter)

Theory and application


Python too supports file handling and allows users to handle files i.e., to read and write files,
along with many other file handling options, to operate on files. The concept of file handling has
stretched over various other languages, but the implementation is either complicated or lengthy,
but alike other concepts of Python, this concept here is also easy and short. Python treats file
differently as text or binary and this is important. Each line of code includes a sequence of
characters and they form text file. Each line of a file is terminated with a special character, called
the EOL or End of Line characters like comma {,} or newline character. It ends the current line
and tells the interpreter a new one has begun. Let’s start with Reading and Writing files.

Working of open() function


We use open () function in Python to open a file in read or write mode. As explained
above, open ( ) will return a file object. To return a file object we
use open() function along with two arguments, that accepts file name and the mode,
whether to read or write. So, the syntax being: open(filename, mode). There are
three kinds of mode, that Python provides and how files can be opened:
 “ r “, for reading.
 “ w “, for writing.
 “ a “, for appending.
 “ r+ “, for both reading and writing
One must keep in mind that the mode argument is not mandatory. If not passed, then
Python will assume it to be “ r ” by default. Let’s look at this program and try to
analyze how the read mode works:
Creating a file using write() mode
Let’s see how to create a file and how write mode works:
To manipulate the file, write the following in your Python environment:

# Python code to create a file

file = open('geek.txt','w')

file.write("This is the write command")

file.write("It allows us to write in a particular file")

file.close()

The close() command terminates all the resources in use and frees the system of this
particular program.
For taking contents one from to another file

Open one file called input.txt in read mode.


2. Open another file output.txt in write mode.
3. Read each line from the input file and write it into the output file.
4. Exit.

Program Explanation
1. The file input.txt is opened using the open() function using the f stream.
2. Another file output.txt is opened using the open() function in the write mode using the f1
stream.
3. Each line in the file is iterated over using a for loop (in the input stream).
4. Each of the iterated lines is written into the output file.

Experimental Procedure-

57 Start Google Colab /python Installed on system with editor (like pycharm, jupyter)
58 Type a python program using input, output and calculations
59 Save the program
60 Execute it.

Note: create a text file as “input.txt” and write some date in it. This will be used in the
program.

with open("input.txt") as input:

with open("output.txt","w") as output:

for line in input:


output.write(line)

print("JOB DONE!!")

Precaution and sources of error:


The devices either computers or any other networking device should be handled
with due care and preserved carefully.

Results

Conclusions
Thorugh this experiment we learnt how to take one take one file data input into other file in
python.

Related short question:


What is file object?
What are various modes of file opening?
What is append mode?
What is default mode?
Experiment 17

Experiment name: Write a program that inputs a text file. The program should print all
of the unique words in the file in alphabetical order.

Objectives: To learn how to read a file through python program and print unique words.

Prerequisites: Algorithm and logics, basic knowledge of C++

Key terms: open, close, read ,write

Experimental set-up/Equipment/Apparatus/Tools: -
5. Computer System
6. Google Colab /python Installed on system with editor (like pycharm, jupyter)

Theory and application

Python - Reading a File

Let's start by learning how to read a file.

readline() function is used to read a line in the document. It can be used like:

>>> myFile.readline()

Copy

where myFile is the instance of the file. readline() function will simply print the whole line
starting from the cursor's position.

In order to print the whole content of the file, iterating line by line, we can use a for loop:

for line in myFile:

# will print all the lines one by one

print (line)
Copy

Beside using iteration, there is another way of reading the whole file,
using readlines() function(notice it is readlines, which is different from readline). Using the
function will return a list that will contain each line of the file. Because of this, one should be
careful while using this function. In case there is lots of data in the file, the list may take lots
of space, and thus making the whole reading time longer. Thus, it is recommended to use this
function only for reading shorter files which can be stored in a list efficiently.

It is used pretty much like readlines() only, except that in this case we need to store the
returned value in some variable:

>>> content = myFile.readlines()

Copy

Similar thing can done manually using iterative approach:

content = []

for line in myFile:

content.append(line)

Copy

This will iteratively append each line of the file on content list.

Python - Writing to a file

write() function is used to write a single string into the file. For example, there is a string

>>> content = "Hello, World. I am learning Python."

# In order to write this line in a file

>>> myFile.write(content)

Copy
or

>>> myFile.write("Hello, World. I am learning Python")

Copy

Write can't be used for writing the content of list or tuple. In such cases, writelines() function
is used.

>>> content = ["Python 3.x\n", "Hello, World. I am learning Python"]

>>> myFile.writelines(content)

Copy

Executing this will write the file content with:

Python 3.x

Hello, World. I am learning Python

Experimental Procedure-

61 Start Google Colab /python Installed on system with editor (like pycharm, jupyter)
62 Type a python program using input, output and calculations
63 Save the program
64 Execute it.

fname=input("enter file name with correct extension:")


file_opened=open(fname)
our_list=list() #creating an empty list

for line in file_opened:

word=line.rstrip().split() #rstrip for removing unwanted spaces


for element in word:

if element in our_list:
continue
else:

our_list.append(element)
our_list.sort()
print(our_list)

Precaution and sources of error:


The devices either computers or any other networking device should be handled with due
care and preserved carefully.

Results

Conclusions
Thorugh this experiment we learnt to read a file into other file and print unique words from it
in python.

Related short question:


What is file object?
What are various modes of file opening?
What is append mode?
What is default mode?
Experiment 18

Experiment name: Write a Python class to convert an integer to a roman numeral.

Objectives: To learn how to work with classes in python

Prerequisites: Algorithm and logics, basic knowledge of C++

Key terms: class, object

Experimental set-up/Equipment/Apparatus/Tools: -
7. Computer System
8. Google Colab /python Installed on system with editor (like pycharm, jupyter)

Theory and application

A class is a user-defined blueprint or prototype from which objects are created. Classes
provide a means of bundling data and functionality together. Creating a new class creates a
new type of object, allowing new instances of that type to be made. Each class instance can
have attributes attached to it for maintaining its state. Class instances can also have methods
(defined by their class) for modifying their state.
To understand the need for creating a class let’s consider an example, let’s say you wanted to
track the number of dogs that may have different attributes like breed, age. If a list is used,
the first element could be the dog’s breed while the second element could represent its age.
Let’s suppose there are 100 different dogs, then how would you know which element is
supposed to be which? What if you wanted to add other properties to these dogs? This lacks
organization and it’s the exact need for classes.
Class creates a user-defined data structure, which holds its own data members and member
functions, which can be accessed and used by creating an instance of that class. A class is like
a blueprint for an object.
Class Definition Syntax:

class ClassName:
# Statement-1
.
.
.
# Statement-N
Class Objects
An Object is an instance of a Class. A class is like a blueprint while an instance is a copy of
the class with actual values. It’s not an idea anymore, it’s an actual dog, like a dog of breed
pug who’s seven years old. You can have many dogs to create many different instances, but
without the class as a guide, you would be lost, not knowing what information is required.
An object consists of :
 State: It is represented by the attributes of an object. It also reflects the properties of an
object.
 Behavior: It is represented by the methods of an object. It also reflects the response of
an object to other objects.
 Identity: It gives a unique name to an object and enables one object to interact with
other objects.

Declaring Objects (Also called instantiating a class)


When an object of a class is created, the class is said to be instantiated. All the instances
share the attributes and the behavior of the class. But the values of those attributes, i.e. the
state are unique for each object. A single class may have any number of instances.
Example:

Declaring an object –
# Python3 program to
# demonstrate instantiating
# a class
class Dog:

# A simple class
# attribute
attr1 = "mammal"
attr2 = "dog"

# A sample method
def fun(self):
print("I'm a", self.attr1)
print("I'm a", self.attr2)

# Driver code
# Object instantiation
Rodger = Dog()

# Accessing class attributes


# and method through objects
print(Rodger.attr1)
Rodger.fun()

Experimental Procedure-

65 Start Google Colab /python Installed on system with editor (like pycharm, jupyter)
66 Type a python program using input, output and calculations
67 Save the program
68 Execute it.

class roman_solution:

def int_to_Roman(num):

val = [1000, 900, 500, 400, 100, 90, 50, 40, , 9, 5, 4, 1]

syb = ["M", "CM", "D", "CD", "C", "XC", "L", "XL","X", "IX", "V", "IV", "I” ]

roman_num = “”

i=0

if(n<1 or n>3999):

print("ENTER A GOOD VALUE!")


else:

while num > 0:

if(num-val[i]>=0):
roman_num+=syb[i] num-=val[i]
else:

i+=1

return roman_num
n=int(input("ENTER A NUMBER:"))
print("roman numeral of given number is:",roman_solution.int_to_Roman(n))

Precaution and sources of error:


The devices either computers or any other networking device should be handled
with due care and preserved carefully.

Results

Conclusions
A class is a user-defined blueprint or prototype from which objects are created. Classes
provide a means of bundling data and functionality together. Creating a new class creates a
new type of object, allowing new instances of that type to be made. Thorugh this
experiment we learnt to use class in python.

Related short question:


What is a class?
What is an instance?
Write syntax to create class?
Write syntax to create object
Experiment 19

Experiment name: Write a Python class to implement pow(x, n)

Objectives: To learn to use Pow() function in python

Prerequisites: Algorithm and logics, basic knowledge of C++

Key terms: pow, print, input

Experimental set-up/Equipment/Apparatus/Tools: -
 Computer System
 Google Colab /python Installed on system with editor (like pycharm, jupyter)

Theory and application

The pow() function returns the value of x to the power of y (xy).

If a third parameter is present, it returns x to the power of y, modulus z.

Syntax
pow(x, y, z)

Parameter Values

Parameter Description

x A number, the base

y A number, the exponent

Optional. A number, the


z
modulus
Experimental Procedure-

69 Start Google Colab /python Installed on system with editor (like pycharm, jupyter)
70 Type a python program using input, output and calculations
71 Save the program
72 Execute it.

class py_power:
def power(x,n):
print("power of given literals:\nx:",x,"\nn\n:",n,"is:",x**n)
x=float(input("ENTER X(BASE) VALUE:"))
n=float(input("ENTER N(POWER) VALUE:"))
py_power.power(x,n)

Precaution and sources of error:


The devices either computers or any other networking device should be handled
with due care and preserved carefully.

Results

Conclusions
A list is a data structure in Python that is a mutable, or changeable, ordered sequence of elements.
Each element or value that is inside of a list is called an item. Just as strings are defined as characters
between quotes, lists are defined by having values between square brackets [ ] . Thorugh this
experiment we learnt to perform various operations on lists in python.
Related short question:
Write syntax of pow() function
In which library pow() function is present
Experiment 20

Experiment name: Write a Python class to reverse a string word by word.

Objectives: To learn how to how to use string class for reversing a string

Prerequisites: Algorithm and logics, basic knowledge of C++

Key terms: string, input, import, print

Experimental set-up/Equipment/Apparatus/Tools: -
9. Computer System
10. Google Colab /python Installed on system with editor (like pycharm, jupyter)

Theory and application

Python has a built-in string class named "str" with many handy features (there is an older
module named "string" which you should not use). String literals can be enclosed by either
double or single quotes, although single quotes are more commonly used. Backslash escapes
work the usual way within both single and double quoted literals -- e.g. \n \' \". A double
quoted string literal can contain single quotes without any fuss (e.g. "I didn't do it") and
likewise single quoted string can contain double quotes. A string literal can span multiple
lines, but there must be a backslash \ at the end of each line to escape the newline. String
literals inside triple quotes, """ or ''', can span multiple lines of text.

Python strings are "immutable" which means they cannot be changed after they are created
(Java strings also use this immutable style). Since strings can't be changed, we construct
*new* strings as we go to represent computed values. So for example the expression ('hello'
+ 'there') takes in the 2 strings 'hello' and 'there' and builds a new string 'hellothere'.

Characters in a string can be accessed using the standard [ ] syntax, and like Java and C++,
Python uses zero-based indexing, so if s is 'hello' s[1] is 'e'. If the index is out of bounds for
the string, Python raises an error. The Python style (unlike Perl) is to halt if it can't tell what
to do, rather than just make up a default value. The handy "slice" syntax (below) also works
to extract any substring from a string. The len(string) function returns the length of a string.
The [ ] syntax and the len() function actually work on any sequence type -- strings, lists, etc..
Python tries to make its operations work consistently across different types. Python newbie
gotcha: don't use "len" as a variable name to avoid blocking out the len() function. The '+'
operator can concatenate two strings. Notice in the code below that variables are not pre-
declared -- just assign to them and go.
s = 'hi'
print s[1] ## i
print len(s) ## 2
print s + ' there' ## hi there

Unlike Java, the '+' does not automatically convert numbers or other types to string form. The
str() function converts values to a string form so they can be combined with other strings.

pi = 3.14
##text = 'The value of pi is ' + pi ## NO, does not work
text = 'The value of pi is ' + str(pi) ## yes

For numbers, the standard operators, +, /, * work in the usual way. There is no ++ operator,
but +=, -=, etc. work. If you want integer division, it is most correct to use 2 slashes -- e.g.
6 // 5 is 1 (previous to python 3, a single / does int division with ints anyway, but moving
forward // is the preferred way to indicate that you want int division.)

The "print" operator prints out one or more python items followed by a newline (leave a
trailing comma at the end of the items to inhibit the newline). A "raw" string literal is
prefixed by an 'r' and passes all the chars through without special treatment of backslashes, so
r'x\nx' evaluates to the length-4 string 'x\nx'. A 'u' prefix allows you to write a unicode string
literal (Python has lots of other unicode support features -- see the docs below).

raw = r'this\t\n and that'

# this\t\n and that


print raw

multi = """It was the best of times.


It was the worst of times."""

# It was the best of times.


# It was the worst of times.
print multi

String Methods

Here are some of the most common string methods. A method is like a function, but it runs
"on" an object. If the variable s is a string, then the code s.lower() runs the lower() method on
that string object and returns the result (this idea of a method running on an object is one of
the basic ideas that make up Object Oriented Programming, OOP). Here are some of the most
common string methods:
 s.lower(), s.upper() -- returns the lowercase or uppercase version of the string
 s.strip() -- returns a string with whitespace removed from the start and end
 s.isalpha()/s.isdigit()/s.isspace()... -- tests if all the string chars are in the various character classes
 s.startswith('other'), s.endswith('other') -- tests if the string starts or ends with the given other string
 s.find('other') -- searches for the given other string (not a regular expression) within s, and returns the
first index where it begins or -1 if not found
 s.replace('old', 'new') -- returns a string where all occurrences of 'old' have been replaced by 'new'
 s.split('delim') -- returns a list of substrings separated by the given delimiter. The delimiter is not a
regular expression, it's just text. 'aaa,bbb,ccc'.split(',') -> ['aaa', 'bbb', 'ccc']. As a convenient special
case s.split() (with no arguments) splits on all whitespace chars.
 s.join(list) -- opposite of split(), joins the elements in the given list together using the string as the
delimiter. e.g. '---'.join(['aaa', 'bbb', 'ccc']) -> aaa---bbb---ccc

A google search for "python str" should lead you to the official python.org string
methods which lists all the str methods.

Python does not have a separate character type. Instead an expression like s[8] returns a
string-length-1 containing the character. With that string-length-1, the operators ==, <=, ... all
work as you would expect, so mostly you don't need to know that Python does not have a
separate scalar "char" type.

String Slices

The "slice" syntax is a handy way to refer to sub-parts of sequences -- typically strings and
lists. The slice s[start:end] is the elements beginning at start and extending up to but not
including end. Suppose we have s = "Hello"

 s[1:4] is 'ell' -- chars starting at index 1 and extending up to but not including index 4
 s[1:] is 'ello' -- omitting either index defaults to the start or end of the string
 s[:] is 'Hello' -- omitting both always gives us a copy of the whole thing (this is the pythonic way to
copy a sequence like a string or list)
 s[1:100] is 'ello' -- an index that is too big is truncated down to the string length
The standard zero-based index numbers give easy access to chars near the start of the string.
As an alternative, Python uses negative numbers to give easy access to the chars at the end of
the string: s[-1] is the last char 'o', s[-2] is 'l' the next-to-last char, and so on. Negative index
numbers count back from the end of the string:

 s[-1] is 'o' -- last char (1st from the end)


 s[-4] is 'e' -- 4th from the end
 s[:-3] is 'He' -- going up to but not including the last 3 chars.
 s[-3:] is 'llo' -- starting with the 3rd char from the end and extending to the end of the string.

It is a neat truism of slices that for any index n, s[:n] + s[n:] == s. This works even for n
negative or out of bounds. Or put another way s[:n] and s[n:] always partition the string into
two string parts, conserving all the characters. As we'll see in the list section later, slices work
with lists too.

Experimental Procedure-

73 Start Google Colab /python Installed on system with editor (like pycharm, jupyter)
74 Type a python program using input, output and calculations
75 Save the program
76 Execute it.

fname="HELLO EVERYONE THIS IS WITH LISTS"


our_list=list()
word=fname.split()
for element in word:
our_list.append(element)
print("tried sentence is:",our_list)
our_list.sort()
print("list after sort",our_list)
our_list.sort(reverse=True)
print("list after the reverse()",our_list)
Output:
word.
PYTHON PROGRAMMING AND WE'RE PLAYING
#creating an empty list
#spliting up the list
#method

our_list=list()
word=fname.split()
for element in word:
our_list.append(element)

#creating an empty list #spliting up the list

print("tried sentence is:",our_list)

our_list.reverse() #method to reverse the elements in the list

print("list after the reverse()",our_list)

Precaution and sources of error:


The devices either computers or any other networking device should be handled
with due care and preserved carefully.

Results

Conclusions
Python has a built-in string class named "str" with many handy features Thorugh this experiment
we learnt to perform various operations on strings in python.

Related short question:


What is string slicing?
What is the name of string related library in python?
What are different inbuilt functions of string?

You might also like