AY 2024-25
III Semester
ECL306: INTRODUCTION TO PYTHON
LAB MANUAL
PREPARED BY
AYUSH GAUTAM
(23212)
SCHOOL OF ELECTRONICS
INDIAN INSTITUTE OF INFORMATION TECHNOLOGY UNA
SALOH, HIMACHAL PRADESH -177209
DECEMBER 2024
LIST OF EXPERIMENTS
S.No Name of the Experiment Date Marks
1. Introduction to Python programming 29/07/24
2. Convert decimal numbers to binary 30/07/24
3. Print the grades according to the marks 30/07/24
4. Calculate the sum of the first “n” numbers 30/07/24
5. Find the sum of the square of the first n nos. 05/08/24
6. Check whether the given number is prime or not 05/08/24
7. Check the given numbers are twin primes 06/08/24
8. Find the intersection and union of two lists 06/08/24
9. Transpose a given matrix 09/09/24
10. Remove the ith occurrence of a given word 09/09/24
11. Check if a substring is present in each string 09/09/24
12. Map two lists into a dictionary 09/09/24
13. Count the frequency of words in a string 23/09/24
14. Create a dictionary with the key-value pair. 23/09/24
15. Find the length of a list using recursion 23/09/24
16. Read a file and modify the first letter of the word 24/09/24
Total Marks
SIGNATURE OF THE STUDENT SIGNATURE OF THE FACULTY
EXPERIMENT-1
Objective: Introduction to Python Programming.
1.Datatypes: A data type refers to the type of value that variable is
storing. Source Code:
y="hello"
print(y,type(y))
z=[7,10,11,9]
print(z,type(z))
x=(3,5,7)
print(x,type(x))
b={"argentina":24,"france":18,"germany":14,"spain":10}
print(b,type(b))
a=frozenset({384,346,287})
print(a,type(a))
e=True
print(e,type(e))
f=None
print(f,type(f))
Input and output:
2. Variables: Variables are containers for storing data values.
Source code:
a=5
b=10
c=a+b
print(c)
d=int (input("enter number"))
e=int (input("enter number2"))
print("the new addition is",d+e)
'''
f="welcome back"
print(f)
x=" to home"
print(f+x)
Input and output:
3. Type Conversions:Type Casting is the method to convert the Python variable datatype into a
certain data type in order to perform the required operation by users.
Source code:
a="7"
b=int(a)
print(a,type(a))
print(b,type(b))
c=6.4
d=int(c)
print(c,type(c))
print(d,type(d))
f=67
x=float(f)
print(f,type(f))
print(x,type(x))
h1=int(input("enter the no"))
h2=float(input("enter the no"))
h3=input("enter the string")
print(h1,h2,h3)
Input and output:
4. Dictionary: Dictionaries are used to store data values in key value pairs. A dictionary is a
collection which is ordered, changeable and do not allow duplicates.
Source code:
dict1={
1:'Python',
2:'dictionary',
3:'example'
print(dict1)
dict2={'NAME':'IIITU','ESTABLISHED':2014,'STATE':'HIMACHAL
PRADESH'} print(dict2)
print(dict2['NAME'])
print(len(dict2))
x=dict2.get('NAME')
print(x)
y=dict2.keys()
print(y)
z=dict2.values()
print(z)
a=dict2.items()
print(a)
dict2['year']=2022
print(dict2)
dict2.update({'year':2014})
print(dict2)
dict2['type']='INI'
print(dict2)
dict2.update({'location':'saloh'})
print(dict2)
dict2.pop('location')
print(dict2)
dict2.popitem()
print(dict2)
del dict2['year']
print(dict2)
dict3=dict2.copy()
print(dict3)
dict4=dict(dict2)
print(dict4)
Input and output:
5.Sets: Sets are used to store multiple items in a single variable.
Source and code:
months=set(['jan','feb','mar'])
print(months)
#adding elements
months.add('april')
months.add('may')
print(months)
months.update(['june','july','august'])
#accesing sets using loop
for i in months:
print(i)
#removing data from set
months.discard('jan')
print(months)
s1=set(['sun','mon','tue','wed'])
s2=set(['wed','thurs','fri','sat'])
#union of sets
print(s1|s2)
print(s1.union(s2))
#intersection of sets
print(s1 & s2)
print(s1.intersection(s2))
Input and output:
6. List: Lists are used to store multiple items in a single variable.List items are ordered,
changeable, and allow duplicate values.
Source code:
list1=[]
list2=[1,'student1','python',9.4]
print(list1)
print(list2,type(list2))
print('Index 0',list2[0])
print('Index 1',list2[1])
print('Index 2',list2[2])
print('Index 3',list2[3])
print('Index -1',list2[-1])
list2[2]='java'
#slicing operator
print(list2[0:2])#slice the list from index 0 to 1
print(list2[2:])#slice the list starting from index 2 to ebd
print(list2[:3])
list3=[3,3.2,3.2]
print(list2+list3)#list
concatenation print(list3*3)
a=10,20,30
print(a[0],type(a))
l=[1,2,3,4,5]
print(l)
l[2]=10#replacing value
print(l)
l[1:3]=[89,78]
print(l)
l.append(100)
print(l)
l.insert(3,200)
print(l)
l.insert(-2,250)
print(l)
l.remove(5)
print(l)
del(l[4])
print(l)
l.pop(4)
print(l)
Input and output:
7. Tuples: A tuple is a collection which is ordered and unchangeable.Tuple allow duplicate
values.Tuple items are indexed, the first item has index [0], the second item has index [1] etc.
Source code:
tuple_1=()
print(tuple_1,type(tuple_1))
tuple2=(1,'student 1','python',9.4)
print('Index 0=',tuple2[0])
print('Index 1=',tuple2[1])
print('Index 2=',tuple2[2])
print('Index 3=',tuple2[3])
print('Index -1=',tuple2[-1])
tuple3=(3,3.2,3.2)
print(tuple2+tuple3)
list4=list(tuple2)
print(list4,type(list4))
list4[2]='JAVA'
tuple4=tuple(list4)
print(tuple4,type(tuple4))
print(tuple3 * 3)
Input and output:
8. Operators: Operators are used to perform operations on variables and values.Assignment
operators are used to assign values to variables.
Source code:
a=6
b=5
add=a+b
sub=a-b
mul=a*b
div=a/b
mod=a%b
exp=a**b
fl_div=a//b
print('the sum is',add)
print('the difference is',sub)
print('the product is',mul)
print('the division is',div)
print('the exponential is',exp)
print('the remainder is',mod)
print('the quotient is',fl_div)
Input and output:
9. Functions:A function is a block of code that performs a specific task (or) Take inputs, do the
computation, and provide the output/result.
Source code:
def display():
print('iiit una')
display()
def sum_num():
a=10
b=20
c=a+b
print('sum of 10 & 20 is',c)
return c
sum_num()
def sum_input(a,b):
print('sum is',a+b)
a=int(input('enter the5 first no.'))
b=int(input('enter the second no.'))
sum_input(a,b)
n=int(input('enter the value of n'))
for i in range(0,n):
display()
Input and output:
10.Loops and Conditional statements:The while loop we can execute a set of statements as
long as a condition is true.For loops are used for sequential traversal.
Source code:
: #while loop
i=1
while i<6:
print('the value of i is',+i)
i+=1
#break statement
i=1
while i<6:
print('value of i in break statement loop',+i)
if i==3:
break
i += 1
#continue statement
i=0
while i<6:
i+=1
if i==3:
continue
print('value of i in continue statement loop',+i)
#else statement
i=1
while i<6:
print('value of i in the else statement loop', +i)
i+=1
else:
print('is no longer less than 6')
#for loop
inst_name=["indian","institute","of","information","technology","una"
] for words in inst_name:
if words == 'una':
break
print(words)
#continue statement
for words in inst_name:
if words=='information':
continue
print(words)
#use of range()
for x in range(2,6):#6 excluded
print(x)
for x in range(2,30,3):
print(x)
#else statement
for word in inst_name:
print(word)
else:
print('name is completed')
#pass statement
for x in [0,1,2]:
print('executing pass command')
pass
adj=["red","big","tasty"]
fruits=["apple","banana","cherry"]
for x in adj:
for y in fruits:
print(x,y)
stud_marks=[20,80,75,40,90,65]
grade=["A","A","A","A","A","A"]
Input and output:
Conclusion: I learned the basics of Python, like doing simple math, using lists and dictionaries,
and creating functions. This helped me understand how to organize and manage data better,
making my code easier to write and work with.
EXPERIMENT-02
Objective: To implement a function to convert decimal number to
binary. Source code:
#function to convert decimal number to binary
def decimal_to_binary(decimal_number):
if decimal_number==0:
return "0"
binary_number = " "
while decimal_number>0:
binary_number=str(decimal_number % 2)+ binary_number
decimal_number=decimal_number//2
return binary_number
#taking input from the user
decimal_number=int(input("enter a decimal number;"))
#converting decimal to binary
binary_number=decimal_to_binary(decimal_number)
print(f"the binary representation
of{decimal_number}is{binary_number}") Input and output:
Conclusion:
The experiment showed how to create a function that turns a decimal number into binary. I have
learned how to write and use this function to convert numbers, which helped me to understand
binary numbers.
EXPERIMENT-03
Objective: To implement conditional statements in python using
function. Source code: def determine_grade(marks):
if marks>=90:
return 'A'
elif marks>=80:
return 'B'
elif marks>=70:
return 'C'
elif marks>=60:
return 'D'
else:
return 'F'
marks=int(input("Enter the marks:"))
grade=determine_grade(marks)
print(f"the grade for {marks}is{grade}")
Input and output:
Conclusion: In this experiment I have learned how to implement conditional statements in
python using function which enables my code to give output based on different conditions.
EXPERIMENT-04
Objective: To implement a function to give sum of first n numbers as
output. Source code:
def sum_of_first_n_numbers(n):
if n<0:
return "please enter a non-negative integer."
elif n==0:
return 0
else:
return n*(n+1)//2
n=int(input("Enter the number:"))
sum=sum_of_first_n_numbers(n)
print(f"the sum of first {n} numbers is {sum}")
Input and output:
Conclusion:
From this experiment, I’ve learned how to implement a function in Python that adds up the first
n numbers. This enabled me to find the total of numbers from 1 to any number I choose.
EXPERIMENT-05
Objective:To implement a function to find sum of square of first n
numbers.
Source code:
def sum_of_square_of_first_n_numbers(n):
if n<0:
return "please enter a non-negative integer."
elif n==0:
return 0
else:
return n*(n+1)*(2*n+1)//6
n=int(input("Enter the number:"))
sum=sum_of_square_of_first_n_numbers(n)
print(f"the sum of square of first {n} numbers is {sum}")
try:
n=int(input("enter a positive number"))
if n<=0:
raise ValueError
except ValueError:
print("invalide input, please enter a positive integer")
else:
result=sum_of_square_of_first_n_numbers(n)
print(f"the sum of squares of the first({n}natural numbers is{result}")
Input and output:
Conclusion: From this experiment, I’ve learned how to create a function in Python that
calculates the sum of the squares of the first n numbers. This helped me in finding the total of
sum of squares from 1 to any number I choose.
EXPERIMENT-06
Objective: To make a program to check whether given number is prime or
not. Source code:
num=int(input("enter the number"))
if num>1:
for i in range(2,(num//2)+1):
if (num%i)==0:
print(num,"is not a prime number")
break
else:
print(num,"is a prime number")
else:
( num,"is not a prime number")
Input and output:
Conclusion: From this experiment, I’ve learned how to write a program in Python that checks if
a number is prime or not. This enables me to find out whether a number has no divisors other
than 1 and itself.
EXPERIMENT-07
Objective: To implement a function to check whether the given two numbers are twin primes or
not.
Source code:
def is_prime(n):
if n<=1:
return False
if n<=3:
return True
if n%2==0 or n%3==0:
return False
i=5
while i*i<=n:
if n%i==0 or n%i(i+2)==0:
return False
i+=6
return True
def are_twin_primes(a,b):
return is_prime(a) and is_prime(b) and abs(a-b)==2
num1=int(input("enter the first number"))
num2=int(input("enter the second number"))
if are_twin_primes(num1,num2):
print(f"{num1} and {num2} are twin primes")
else:
print(f"{num1}and {num2} are not twin primes")
Input and output:
Conclusion:
From this experiment, I’ve learned how to implement a function in Python to check if two
numbers are twin primes. Twin primes are pairs of numbers that are both prime and differ by 2.
This function helps me to determine if any given pair of numbers fits this special condition or
not.
EXPERIMENT-08
Objective : To make a program to find union and intersection of two
lists. Source code:
list1=[1,2,3,4,5]
list2=[4,5,6,7,8]
#convert lists to sets
set1= set(list1)
set2= set(list2)
#find the intersection
intersection=set1.intersection(set2)
print("intersection:",intersection)
#find the union
union=set1.union(set2)
print("union:",union)
Input and outputs:
Conclusion:
From this experiment, I’ve learned how to write a program in Python to find the union and
intersection of two lists. The union gave all the unique elements from both lists, while the
intersection shows only the elements that appear in both lists as output.
EXPERIMENT-09
Objective- To make a program to find transpose of a given matrix.
Source code:
#transpose a given matrix
import numpy as np
matrix=np.array([[1,2,3],
[4,5,6],
[7,8,9]])
transposed_matrix=np.transpose(matrix)
print("original matrix:")
print(matrix)
print("\nTransposed matrix")
print(transposed_matrix)
matrix1=np.array([[1,2],
[3,4]])
transposed_matrix1=np.transpose(matrix1)
print("original 2*2 matrix:")
print(matrix1)
print("\nTransposed 2*2 matrix:")
print(transposed_matrix1)
Input & output:
Conclusion: The program successfully transposes a matrix by swapping its rows and
columns using numpy library. It is simple as well as effective.
EXPERIMENT-10
Objective: To make a program to remove i’th occurrence of a given word.
Source code:
def remove_ith_occurrence(word_list,word_to_remove,i):
count=0
for index,word in enumerate(word_list):
if word == word_to_remove:
count+=1
if count == i:
del word_list[index]
return word_list #stop after removing ith occurrence
return word_list
words= ['apple','banana','cherry','apple','date','apple']
print(words)
word_to_remove='apple'
i=2
result= remove_ith_occurrence(words,word_to_remove,i)
print(result)
Input and output:
Conclusion: The experiment successfully developed a program to remove the i’th occurrence
of a given word from a text. The program accurately identifies and eliminates the desired
occurrence.
EXPERIMENT-11
Objective: To make a program to check if a substring is present in each string or not.
Source code:
string_list=["hello world","python programming","world of code","hello"]
substring="hello"
substring_present=[substring in string for string in string_list]
for i, string in enumerate(string_list):
if substring_present[i]:
print(f"substring '{substring}' is present in:'{string}'")
else:
print(f"substring '{substring}' is not present in: '{string}'")
Input and output:
Conclusion: This experiment successfully created a program that checks if a given substring
is present in each string of a provided string list.
EXPERIMENT-12
Objective: To implement a program to map two lists into a dictionary.
Source code:
#map two strings into a dictionary
keys=['name','age','profession']
values=['ayush',20,'student']
mapped_dict=dict(zip(keys,values))
print("mapped dictionary1:", mapped_dict)
#using loop
mapped_dict1={}
for i in range(len(keys)):
mapped_dict1[keys[i]]=values[i]
print("mapped dictionary2:",mapped_dict1)
Input and output:
Conclusion: The experiment successfully implemented a program that maps two lists into a
dictionary. The program accurately pairs elements from the two lists, creating a dictionary
where one list’s elements serve as keys and the other’s as values.
EXPERIMENT 13
Objective: To make a program to count the frequency of words in a string.
Source code:
#count the frequency of words in a string
input_string="My name is Ayush Gautam. My branch is ECE."
#convert the string to lowercase and split into words
words=input_string.lower().split()
word_frequency={}
for word in words:
word=word.strip(".,!?")
if word in word_frequency:
word_frequency[word]+=1
else:
word_frequency[word]=1
for word, count in word_frequency.items():
print(f"{word}:{count}")
Input and Output:
Conclusion: The program to count frequency of words in a string has been successfully
implemented. It accurately counts number of words present in a given string.
EXPERIMENT 14
Objective: To implement a program to make a dictionary using key-value pair.
Source code:
import time
import random
temperature_data={}
cities=['Una','Delhi','Varanasi','Dehradun','Lucknow']
for i in range(5):
print(f"---Recording data{i+1}---")
for city in cities:
temperature=round(random.uniform(15,32),2)
temperature_data[city]=temperature
print("updated temperature data:",temperature_data)
time.sleep(3)
Input and output:
Conclusion: The program to make a dictionary using key value pair has been successfully
implemented. It allows me to add, retrieve, remove, and display entries as well.
EXPERIMENT 15
Objective: To make a program to find the length of a string using recursion.
Source code:
def recursive_length(lst):
if not lst:
return 0
else:
return 1+ recursive_length(lst[1:])
first_list=[1,2,3,4,5]
length=recursive_length(first_list)
print("length of the first list is:",length)
second_list=[2,5,6,3,4,3]
length1=recursive_length(second_list)
print("length of the second list is:",length1)
Input and output:
Conclusion: The program to find the length of a string using recursion has been successfully
implemented. It accurately counts the length of a given string.
EXPERIMENT 16
Objective: To make a program to read a file and modify the first letter of the word.
Source code:
def modify_first_letter(file_path):
with open(file_path,'r')as file:
content=file.read()
words=content.split()
modified_words=[word[0].upper()+ word[1:] if word else word for word in words]
modified_content=''.join(modified_words)
with open(file_path,'w')as file:
file.write(modified_content)
return modified_content
#example
file_path='C:/Users/iiit una/abcd.txt'
modified_text=modify_first_letter(file_path)
print("modified content:",modified_text)
Input and output:
Conclusion: The program to read a file and modify the first letter of the word has been
successfully implemented and has worked properly.