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

PROGRAMS

The document contains a series of Python programming exercises covering various topics such as operator manipulation, control flow statements, and basic loops. Each section includes multiple questions with user input, demonstrating different programming concepts like arithmetic operations, type conversion, and calculating areas or interest. The document provides code snippets and expected outputs for each exercise.

Uploaded by

cajay781980
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

PROGRAMS

The document contains a series of Python programming exercises covering various topics such as operator manipulation, control flow statements, and basic loops. Each section includes multiple questions with user input, demonstrating different programming concepts like arithmetic operations, type conversion, and calculating areas or interest. The document provides code snippets and expected outputs for each exercise.

Uploaded by

cajay781980
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 75

Topic : Operator Manipulation

Q1 Write a Python program to perform operator manipulation


(arithmetic, comparison, logical, bit wise, assignment, identity, and
membership) using user input.
#Arithmetic Operations
a=int(input("Enter first number : "))
b=int(input("Enter second number : "))
print("Arithmetic Operations :")
print(f"{a} + {b} = {a + b}")
print(f"{a} - {b} = {a - b}")
print(f"{a} * {b} = {a * b}")
print(f"{a} / {b} = {a / b}")
print(f"{a} % {b} = {a % b}")
print(f"{a} // {b} = {a // b}")
print(f"{a} ** {b} = {a ** b}")

OUTPUT :

#Comparison Operations
a=int(input("Enter first number : "))
b=int(input("Enter second number : "))
print("Comparison Operations :")
print(f"{a} == {b} : {a == b}")
print(f"{a} != {b} : {a != b}")
print(f"{a} > {b} : {a > b}")
print(f"{a} < {b} : {a < b}")
print(f"{a} >= {b} : {a >= b}")
print(f"{a} <= {b} : {a <= b}")

OUTPUT :

#Logical Operations
a=int(input("Enter first number : "))
b=int(input("Enter second number : "))
print("Logical Operations :")
print(f"{a} and {b} : {a and b}")
print(f"{a} or {b} : {a or b}")
print(f"not {a} : {not a}")
print(f"not {b} : {not b}")

OUTPUT :

#Bitwise Operations
a=int(input("Enter first number : "))
b=int(input("Enter second number : "))
print("Bitwise Operations :")
print(f"{a} & {b} : {a & b}")
print(f"{a} | {b} : {a | b}")
print(f"{a} ^ {b} : {a ^ b}")
print(f"~{a} : {~a}")
print(f"{a} << 2 : {a << 2}")
print(f"{a} >> 2 : {a >> 2}")

OUTPUT :

#Assignment Operations
a=int(input("Enter a number : "))
print("Assignment Operations :")
x=a
print(f"x = {a}")
x += 5
print(f"x += 5 : {x}")
x -= 3
print(f"x -= 3 : {x}")
x *= 2
print(f"x *= 2 : {x}")
x /= 2
print(f"x /= 2 : {x}")
x %= 3
print(f"x %= 3 : {x}")
x //= 2
print(f"x //= 2 : {x}")
x **= 2
print(f"x **= 2 : {x}")
OUTPUT :

#Identity Operations
a=int(input("Enter first number : "))
b=int(input("Enter second number : "))
print("Identity Operations :")
print(f"{a} is {b} : {a is b}")
print(f"{a} is not {b} : {a is not b}")

OUTPUT :

#Membership Operations
list1=[23,1,56,7,11,3]
e=int(input("Enter an element : "))
print("Membership Operations :")
print(f"{e} in {list1} : {e in list1}")
print(f"{e} not in {list1} : {e not in list1}")

OUTPUT :
Q2 Write a Python program to demonstrate type conversion.
print("Implicit Type Conversion : ")
a=10
b=1.5
c=a+b
print(f"Type of 'a' : {type(a)}")
print(f"Type of 'b' : {type(b)}")
print(f"Result of 'a + b' : {c}, Type of c : {type(c)}")
print("\nExplicit Type Conversion : ")
s="123"
print(f"Type of 's' : {type(s)}")
s1=int(s) #Converting string to integer
print(f"After conversion to integer : {s1}, Type: {type(s1)}")
s2=float(s1) #Converting integer to float
print(f"After conversion to float : {s2}, Type: {type(s2)}")
num = 29
print(f"Integer: {num}")
print(f"Binary: {bin(num)}")
print(f"Octal: {oct(num)}")
print(f"Hexadecimal: {hex(num)}")
OUTPUT :
Q3 Write a Python program to calculate the area of a triangle using
user input.
b=int(input("Enter the base of the triangle : "))
h=int(input("Enter the height of the triangle : "))
area=(b*h)/2
print("Area of triangle =",area)

OUTPUT :

Q4 Write a Python program to convert kilo meters to miles using


user input.
#1 kilometer = 0.621371 miles.
k=float(input("Enter the distance in kilometers : "))
m=k*0.621371
print(f"{k} kilometers is equal to {m} miles")

OUTPUT :

Q5 Write a Python program to calculate simple interest using user


input.
p = float(input("Enter the principal amount : "))
r = float(input("Enter the annual rate of interest (in %) : "))
t = int(input("Enter the time period (in years): "))
si= (p*r*t)/100
print("Simple Interest =",si)
OUTPUT :

Q6 Write a Python program to check if a given year is a leap year.


y=int(input("Enter the year : "))
if(y%100==0):
if(y%400==0):
print(f"{y} is a Leap Year")
else:
print(f"{y} is not a Leap Year")
elif(y%4==0):
print(f"{y} is a Leap Year")
else:
print(f"{y} is not a Leap Year")

OUTPUT :

Topic – Control Flow Statements

Q1 WAP to check whether a number is even or odd.


x=int(input("Enter a number : "))
if(x%2==0):
print(f"{x} is an even number")
else:
print(f"{x} is an odd number")
OUTPUT 1 :

Q2 WAP to find largest of two numbers expected from user.


a=int(input("Enter first number : "))
b=int(input("Enter second number : "))
if(a>b):
print(a,"is largest")
else:
print(b,"is largest")

OUTPUT 2 :

Q3 WAP to find largest of three numbers expected from user.


a=int(input("Enter first number : "))
b=int(input("Enter second number : "))
c=int(input("Enter third number : "))
if(a>b)and(a>c):
print(a,"is largest")
elif(b>a)and(b>c):
print(b,"is largest")
else:
print(c,"is largest")
OUTPUT 3 :

Q4 WAP to accept age of 4 people and display the youngest one.


a=int(input("Enter age of first person : "))
b=int(input("Enter age of second person : "))
c=int(input("Enter age of third person : "))
d=int(input("Enter age of fourth person : "))
if(a<b)and(a<c)and(a<d):
print(a,"is the age of youngest person")
elif(b<a)and(b<c)and(b<d):
print(b,"is the age of youngest person")
elif(c<a)and(c<b)and(c<d):
print(c,"is the age of youngest person")
else:
print(d,"is the age of youngest person")

OUTPUT 4 :
Q5 WAP to check whether a number entered is a 3 digit number or
not.
y=int(input("Enter a number : "))
z=y//100
if(z>=1)and(z<=9):
print(y,"is a 3-digit number")
else:
print(y,"is not a 3-digit number")

OUTPUT 5 :

Q6 WAP to calculate the electricity bill.


u=int(input("Enter the number of units : "))
if(u<=100):
a=0
print("Electricity bill : Rs ",a)
elif(u<=200):
a=(u-100)*5
print("Electricity bill : Rs ",a)
elif(u>200):
a=100*5 + (u-200)*10
print("Electricity bill : Rs ",a)
OUTPUT 6 :

Q7 WAP to check whether a triangle is possible or not.


l1=int(input("Enter length of first side : "))
l2=int(input("Enter length of second side : "))
l3=int(input("Enter length of third side : "))
if(l1<l2+l3)and(l2<l1+l3)and(l3<l1+l2):
print("Triangle is possible")
else:
print("Triangle is not possible")

OUTPUT 7 :

Q8 WAP to calculate the attendance percentage of a student.


a=int(input("Enter the total number of working days : "))
b=int(input("Enter the number of days of absent : "))
att=100-(b/a)*100
print("Attendance Percentage = ",att)
if(a<75):
print("Student is not eligible to sit in exam")
else:
print("Student is eligible to sit in exam")
OUTPUT 8 :

Q9 WAP to display grades according to percentage.


p=int(input("Enter the percentage : "))
if(p>=80):
print("Grade : A+")
elif(p>=60):
print("Grade : A")
elif(p>=50):
print("Grade : B+")
elif(p>=45):
print("Grade : B")
elif(p>=25):
print("Grade : C")
else :
print("Grade : D")

OUTPUT 9 :

Q10 WAP to perform operations on given numbers.


a=int(input("Enter first number : "))
b=int(input("Enter second number : "))
x=input("Enter operator : ")
if(x=='+'):
print("The Answer is : ",a+b)
elif(x=='-'):
print("The Answer is : ",a-b)
elif(x=='*'):
print("The Answer is : ",a*b)
elif(x=='/'):
print("The Answer is : ",a/b)
elif(x=='//'):
print("The Answer is : ",a//b)
elif(x=='%'):
print("The Answer is : ",a%b)
elif(x=='**'):
print("The Answer is : ",a**b)
else:
print("Invalid Operation")

OUTPUT 10 :

Q11 WAP to display the kind of triangle.


l1=int(input("Enter length of first side : "))
l2=int(input("Enter length of second side : "))
l3=int(input("Enter length of third side : "))
if(l1==l2)and(l1==l3):
print("Equilateral Triangle")
elif(l1==l2)or(l1==l3)or(l2==l3):
print("Isosceles Triangle")
else:
print("Scalene triangle")

OUTPUT 11 :

Q12 WAP to calculate library charge.


d=int(input("Enter the number of days : "))
if(d>15):
ch=5*2+5*3+5*4+(d-15)*5
print("Library charge : Rs ",ch)
elif(d>=11)and(d<=15):
ch=5*2+5*3+(d-10)*4
print("Library charge : Rs ",ch)
elif(d>=6)and(d<=10):
ch=5*2+(d-5)*3
print("Library charge : Rs ",ch)
elif(d<=5):
ch=d*2
print("Library charge : Rs ",ch)
OUTPUT 12 :

Topic – Basic Loops

Q1 WAP to display all even numbers from 1 to 20.


print("Even Numbers from 1 to 20 are : ")
for i in range(2,21):
print(i)

OUTPUT 1 :

Q2 WAP to print first n natural numbers.


n=int(input("Enter the value of n : "))
print("First",n,"natural numbers are :")
for i in range(1,n+1):
print(i)
OUTPUT 2 :

Q3 WAP to print sum of first n natural numbers.


n=int(input("Enter the value of n : "))
sum=0
for i in range(1,n+1):
sum+=i
print("Sum of first ",n,"natural numbers is ",sum)

OUTPUT 3 :

Q4 WAP to print all numbers divisible by 7 from 1 to 100


print("Numbers divisible by 7 :")
for i in range(1,100):
if(i%7==0):
print(i,end=" ")

OUTPUT 4 :
Q5 WAP to print table of any number.
num=int(input("Enter a number : "))
print("Table of ",num)
for i in range(1,11):
print(num*i)

OUTPUT 5 :

Q6 WAP to print 1,2,3,5,6,7,8,9 using continue statement.


for i in range(1,10):
if(i==4):
continue
print(i,end=",")

OUTPUT 6 :

Q7 WAP to print table of 5 in the format. 5x1=5 5x2=10 5x3=15


for i in range(1,11):
print("5 x",i,"=",5*i)
OUTPUT 7 :

Q8 WAP to find the sum of first 50 Natural Numbers using for Loop.
sum=0
for i in range(1,51):
sum+=i
print("Sum of first 50 Natural Numbers =",sum)

OUTPUT 8 :

Q9 WAP calculate the factorial of a given number.


n=int(input("Enter a number : "))
fact1=1
for i in range(1,n+1):
fact1*=i
print("Factorial of",n,"using for loop is",fact1)
fact2=1
j=1
while(j<=n):
fact2*=j
j+=1
print("Factorial of",n,"using while loop is",fact2)
OUTPUT 9 :

Q10 WAP to check if anumber is zero, +ve or -ve.


n=int(input("Enter a number : "))
if(n>0):
print(n,"is positive")
elif(n<0):
print(n,"is negative")
else:
print(n,"is zero")

OUTPUT 10 :

Topic – Basic Loops

Q1 WAP to count the sum of digits in the entered number.


x=int(input("Enter a number : "))
y=x
sum=0
while(y!=0):
sum+=y%10
y//=10
print("Sum of digits of ",x," = ",sum)
OUTPUT 1 :

Q2 WAP to find the reverse of a given number.


x=int(input("Enter a number : "))
y=x
rev=0
while(y!=0):
rev=rev*10+y%10
y//=10
print("Reverse of",x,"is",rev)
OUTPUT 2 :

Q3 WAP to check whether a given number is a perfect number.


x=int(input("Enter a number : "))
dsum=0
for i in range(1,x):
if(x%i==0):
dsum+= i
if(dsum==x):
print(x,"is a Perfect number")
else:
print(x,"is not a Perfect number")
OUTPUT 3 :

Q4 WAP to print Armstrong number from 1 to 1000


import math
print("Armstrong Numbers from 1 to 1000")
for i in range(1,1001):
count=0
x=i
y=i
while(x!=0):
count+=1
x//=10
asum=0
while(y!=0):
asum+=math.pow(y%10,count)
y//=10
if(asum==i):
print(i)

OUTPUT 4 :
Q5 WAP to calculate the value of nCr
n = int(input("Enter the value of n : "))
r = int(input("Enter the value of r : "))
factn,factr,factnr=1,1,1
for i in range(1,n+1):
factn*=i
for j in range(1,r+1):
factr*=j
for k in range(1,n-r+1):
factnr*=k
nCr=factn//(factr*factnr)
print("The value of nCr is",nCr)
OUTPUT 5 :

Q6 WAP to generate the Fibonacci series.


n = int(input("Enter the value of n : "))
a=0
b=1
print("Fibonacci Series :")
print(a,b,end=" ")
for i in range(1,n-1):
c = a+b
print(c,end=" ")
a=b
b=c
OUTPUT 6 :

Q7 WAP to check whether a given number is Palindrome or not.


x=int(input("Enter a number : "))
y=x
rev=0
while(y!=0):
rev=rev*10+y%10
y//=10
if(rev==x):
print(x,"is a Palindrome Number")
else:
print(x,"is not a Palindrome Number")

OUTPUT 7 :

Q8 WAP to check whether a given number is an Armstrong Number.


import math
i=int(input("Enter a number : "))
count=0
x=i
y=i
while(x!=0):
count+=1
x//=10
asum=0
while(y!=0):
asum+=math.pow(y%10,count)
y//=10
if(asum==i):
print(i,"is an Armstrong Number")
else:
print(i,"is not an Armstrong number")

OUTPUT 8 :

Q9 WAP to check whether a given number is prime.


n=int(input("Enter a number: "))
count = 0
for i in range(2,n):
if(n%i==0):
count += 1
if(count == 0):
print(n,"is a Prime Number")
else :
print(n,"is not a Prime Number")
OUTPUT 9 :

Q10 WAP to print prime factors of a given number.


n=int(input("Enter a number : "))
print("Prime factors of",n,"are :")
for i in range(2,n):
if(n%i==0):
count = 0

for j in range(2,i):
if(i%j==0):
count += 1
if(count==0):
print(i,end=" ")

OUTPUT 10 :

Q11 WAP to find the GCD (Greatest Common Divisor) of two


numbers.
a=int(input("Enter first number : "))
b=int(input("Enter second number : "))
if(a<b):
small=a
else:
small=b
for i in range(1,small+1):
if(a%i==0)and(b%i==0):
gcd=i
print("The GCD of",a,"and",b,"is",gcd)

OUTPUT 11 :

Q12 WAP to find the LCM (Least Common Multiple) of two numbers.
a=int(input("Enter first number : "))
b=int(input("Enter second number : "))
if(a>b):
large=a
else:
large=b
max=a*b
for i in range(large,max+1):
if(i%a==0)and(i%b==0):
lcm=i
break
print("The LCM of",a,"and",b,"is",lcm)
OUTPUT 12 :

Q13 WAP to check whether a number is a fibonacci number or not.


n = int(input("Enter the value of n : "))
a=0
b=1
count=0
if(n==a)or(n==b):
print(n,"is a fibonacci number")
count=1

if(n>1):
while(b<=n):
c = a+b
if(n==c):
print(n,"is a fibonacci number")
count=1
break
a=b
b=c
if(count==0):
print(n,"is not a fibonacci number")
OUTPUT 13 :

PATTERN PRINTING

Ques1 :
n=int(input("Enter number of rows : "))
for i in range(1,n+1):
for j in range(0,i):
print(i,end=" ")
print()

OUTPUT 1 :

Ques2 :
n=int(input("Enter number of rows : "))
for i in range(1,n+1):
for j in range(1,i+1):
print(j,end=" ")
print()
OUTPUT 2 :

Ques3 :
n=int(input("Enter number of rows : "))
for i in range(1,n+1):
for j in range(0,n+1-i):
print(i,end=" ")
print()

OUTPUT 3 :

Ques4 :
n=int(input("Enter number of rows : "))
for i in range(1,n+1):
for j in range(0,n+1-i):
print(5,end=" ")
print()

OUTPUT 4 :
Ques5 :
n=int(input("Enter number of rows : "))
for i in range(0,n):
for j in range(0,n+1-i):
print(j,end=" ")
print()

OUTPUT 5 :

Ques6 :
n=int(input("Enter number of rows : "))
a=1
for i in range(1,n+1):
for j in range(0,i):
print(a,end=" ")
a+=2
print()

OUTPUT 6 :
Ques7 :
n=int(input("Enter number of rows : "))
for i in range(1,n+1):
for j in range(i,n+1):
print(j,end=" ")
print()

OUTPUT 7 :

Ques8 :
n=int(input("Enter number of rows : "))
for i in range(1,n+1):
k=i
for j in range(i,0,-1):
print(k,end=" ")
k+=i
print()

OUTPUT 8 :
Ques9 :
n=int(input("Enter number of rows : "))
for i in range(n,0,-1):
for j in range(n,n-i,-1):
print(i,end=" ")
print()

OUTPUT 9 :

Ques10 :
n=int(input("Enter number of rows : "))
x=0
for i in range(1,n+1):
x+=i
y=x
for j in range(1,i+1):
print(y,end=" ")
y-=1
print()

OUTPUT 10 :
Ques11 :
n=int(input("Enter number of rows : "))
for i in range(1,n+1):
for j in range(n-i):
print(" ",end=" ")
for k in range(1,i+1):
print(k,end=" ")
print()

OUTPUT 11 :

Ques12 :
n=int(input("Enter number of rows : "))
for i in range(1,n+1):
for j in range(1,n+1):
if(i>=j):
print(i,end=" ")
else:
print(j,end=" ")
print()

OUTPUT 12 :
Ques13 :
n=int(input("Enter number of rows : "))
for i in range(n,0,-1):
for j in range(1,i+1):
if(j==i):
print(j,end=" ")
else:
print(j,"*",end=" ")
print()

OUTPUT 13 :

Ques14 :
s="Python"
for i in range(1,len(s)+1):
for j in range(i):
print(s[j],end="")
print()

OUTPUT 14 :
Ques15 :
n=int(input("Enter number of rows : "))
for i in range(1,n+1):
for j in range(n-i):
print(" ",end="")
for k in range(2*i-1):
print("*",end="")
print()

OUTPUT 15 :

Ques16 :
n = int(input("Enter a number : "))
a=n
b=n
for i in range(1,2*n):
for j in range(1,n+i+1):
if(j==a or j==b) :
print("*",end="")
else:
print(" ",end="")
print()
if(i<n):
a = a-1
b = b+1
else :
a = a+1
b = b-1

OUTPUT 16 :

Ques17 :
n = int(input("Enter a number : "))
a=n
for i in range(1,n+1):
for j in range(1,n+1):
if(j>=a) :
print("*",end=" ")
else:
print(" ",end="")
print()
a = a-1

OUTPUT 17 :
Ques18 :
n = int(input("Enter a number : "))
a=1
for i in range(1,n+1):
for j in range(1,n+1):
if(j>=a) :
print("*",end=" ")
else:
print(" ",end="")
print()
a = a+1

OUTPUT 18 :

Ques19 :
n = int(input("Enter a number : "))
a=1
b=n
for i in range(1,2*n+1):
if (i<=n):
for j in range(1,n+1):
if (j>=a):
print("*", end=" ")
else:
print(" ", end="")
print()
a += 1
else:
for j in range(1, n + 1):
if (j>=b):
print("*", end=" ")
else:
print(" ", end="")
print()
b -= 1

OUTPUT 19 :

Topic – Python Data Structures


Q1 Write a program that iterates over a dictionary of student names
and their marks, printing each student's name and marks.
dict1={"Prakhar":91 , "Prashant":90 ,"Rishabh":92 }
for i in dict1:
print(i,":",dict1[i])

OUTPUT 1 :
Q2 Given a list of fruits fruits = ["apple", "banana", "cherry"], print
each fruit using a for loop.
fruits=["apple","banana","cherry"]
print("The given list is:",fruits)
print("The list fruits has following elements:")
for i in fruits:
print(i)

OUTPUT 2 :

Q3 Given two tuples (1, 2, 3) and (4, 5, 6), concatenate them and
print the result.
t1=(1,2,3)
t2=(4,5,6)
print("Tuple t1:",t1)
print("Tuple t2:",t2)
t3=t1+t2
print("Concatenated Tuple:",t3)

OUTPUT 3 :
Q4 Write a program to replace all spaces in a string with hyphens
using replace().
s="Hi Rohan how are you?"
print("The given string is:",s)
print("New string is:",s.replace(" ","-"))

OUTPUT 4 :

Q5 Write a Python program to add a new key-value pair to a


dictionary and update the value of an existing key using update().
dict1={1:"a",2:"b",3:"c"}
print("The given dictionary is: ",dict1)
k=int(input("Enter key: "))
v=input("Enter value: ")
dict1[k]=v
print("Dictionary after adding a key-value pair: ",dict1)
dict1.update({3:"e"})
print("Dictionary after updation: ",dict1)

OUTPUT 5 :
Q6 Write a Python program to find the key with the highest value in
the dictionary scores = {"Alice": 85, "Bob": 90, "Charlie": 88}.
scores={"Alice":85, "Bob":90, "Charlie":88}
print("The given dictionary is:",scores)
max=0
for i in scores:
if(max<scores[i]):
max=scores[i]
y=i
print("The key with highest value is:",y)

OUTPUT 6 :

Q7 Write a Python program that takes a string as input and counts


the frequency of each word in the string using a dictionary.
s=input("Enter a string: ")
w = s.split()
f = [w.count(word) for word in w]
d = dict()
for i in range(len(w)):
k=w[i]
v=f[i]
d[k]=v
print("The required dictionary is:",d)
OUTPUT 7 :

Q8 Write a program that inputs a list of numbers and prints a new


list with only the unique elements.
l1=[ ]
n=int(input("Enter number of elements to be entered: "))
for i in range(n):
x=int(input("Enter element: "))
l1.append(x)
l2=[ ]

for i in l1:
if(i not in l2):
l2.append(i)
print("List of unique elements:",l2)

OUTPUT 8 :
Q9 Write a Python program that takes a string, converts it into a list
of characters, reverses the list, and then joins it back into a string
to print the reversed string.
s=input("Enter a string: ")
l1=list(s)
print("List of characters:",l1)
rev=l1[::-1]
print("Reversed List:",rev)
s1=""
for i in rev:
s1+=i
print("Required String is:",s1)

OUTPUT 9 :

Q10 Write a Python program to store student information (name,


age, course) using a dictionary, and allow the user to input the
details of multiple students. Later, print the details of each student.
d=dict()
n=int(input("Enter number of elements: "))
for i in range(1,n+1):
s=input("Enter student info (name, age, course) : ")
t=tuple(s.split(","))
d[i]=t
print("Details of Students are:")
for k in d:
print(k,":",d[k])
OUTPUT 10 :

Topic – Python Functions

Q1 Write a Python function fibonacci(n) that returns the nth


Fibonacci number using recursion. Test the function with different
values of n.
def fibonacci(n):
if(n==0 or n==1):
return n
return fibonacci(n-1)+fibonacci(n-2)

n=int(input("Enter the number: "))


print(f"{n}th Fibonacci number is:", fibonacci(n))

OUTPUT 1 :

Q2 Write a lambda function that takes two numbers as input and


returns their sum.
a=int(input("Enter first number: "))
b=int(input("Enter second number: "))
add = lambda x,y : x+y
print(f"Sum : {a} + {b} =", add(a, b))
OUTPUT 2 :

Q3 Write a Python program that demonstrates the difference


between a local and a global variable. Declare a global variable
x=10, then modify it locally inside a function and print the results
before and after the function call.
x=10 # Global variable
def modify_variable():
x = 20 # Local variable with the same name
print(f"Inside the function, local x = {x}")

print(f"Before the function call, global x = {x}")


modify_variable()
print(f"After the function call, global x = {x}")

OUTPUT 3 :

Q4 Write a Python program to create a simple calculator that can


add, subtract, multiply, and divide using functions. Each operation
should be a separate function.
def add(a, b):
return a+b
def subtract(a, b):
return a-b
def multiply(a, b):
return a*b

def divide(a, b):


if b==0:
return "Error: Division by zero is undefined."
return a/b

while(True):
print("Simple Calculator")
print("Select an operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
print("5. Exit")
ch = input("Enter your choice (1/2/3/4/5): ")
if ch not in ['1', '2', '3', '4', '5']:
print("Invalid choice. Please select a valid operation.")
continue
if ch == '5':
print("Exit")
break
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
if ch == '1':
print(f"The result of addition is: {add(num1, num2)}")

elif ch == '2':
print(f"The result of subtraction is: {subtract(num1, num2)}")
elif ch == '3':
print(f"The result of multiplication is: {multiply(num1, num2)}")
elif ch == '4':
print(f"The result of division is: {divide(num1, num2)}")

OUTPUT 4 :
Q5 Write a function is_prime(n) that checks if a number is prime.
Use this function inside a program to check if a given number is
prime or not.
def is_prime(n):
count=0
for i in range(2,n):
if(n%i==0):
count+=1
if(count==0):
print(n,"is a Prime Number")
else :
print(n,"is not a Prime Number")

x=int(input("Enter a number: "))


is_prime(x)

OUTPUT 5 :

Q6 Write a function is_palindrome(s) that checks if a given string s


is a palindrome (reads the same forward and backward). Use this
function inside a program to check different strings.
def is_palindrome(x):
rev=x[::-1]
if(rev==x):
print(x,"is Palindrome")
else:
print(x,"is not Palindrome")
s=input("Enter a string: ")
is_palindrome(s)

OUTPUT 6 :

Q7 Write a Python function find_largest(lst) that takes a list of


numbers as input and returns the largest number.
def find_largest(k):
return max(k)

lst = [ ]
n = int(input("Enter number of elements : "))
for i in range(0, n):
ele = int(input("Enter element: "))
lst.append(ele)
print("The list is:", lst)
print("The largest element of the list is: " , find_largest(lst))

OUTPUT 7 :
Q8 Write a function celsius_to_fahrenheit(celsius) that converts
Celsius to Fahrenheit and another function
fahrenheit_to_celsius(fahrenheit) that converts Fahrenheit to
Celsius. Use these functions in a program to perform the
conversions.
def celsius_to_fahrenheit(x):
return (x*9//5)+32

def fahrenheit_to_celsius(y):
return (y-32)*5//9

x = int(input("Enter temperature in celcius : "))


y = int(input("Enter temperature in fahrenheit : "))

print(x,"celsius in fahrenheit is", celsius_to_fahrenheit(x))


print(y,"fahrenheit in celcius is", fahrenheit_to_celsius(y))

OUTPUT 8 :

Q9 Write a function count_words(sentence) that takes a sentence


as input and returns the number of words in it.
def count_words(sentence):
words = sentence.split()
return len(words)

x = input("Enter a sentence :")


print("The number of words in the sentence are:", count_words(x))
OUTPUT 9 :

Q10 Write a function validate_password(password) that checks if a


password meets the following criteria:
● At least 8 characters long
● Contains both uppercase and lowercase characters
● Contains at least one number
Use this function inside a program to validate user-entered
passwords.
def validate_password(password):
if len(password) < 8:
return "Invalid"
if not any(char.isupper() for char in password):
return "Invalid"
if not any(char.islower() for char in password):
return "Invalid"
if not any(char.isdigit() for char in password):
return "Invalid"
return "Valid"

x = input("Enter the password : ")


print("The Password is :",validate_password(x))

OUTPUT 10 :
Python File Operations

Q1. Write a Python program that reads and prints each line of a file
one by one using readline() in a loop.
with open('/content/drive/MyDrive/data.csv','r') as file:
line = file.readline()
while line:
print(line, end='')
line = file.readline()

OUTPUT 1 :
Q2. Write a program that appends "This is a new line." to an
existing file using the write() method.
file_obj = open('/content/drive/MyDrive/data.csv','a')
file_obj.write('\nThis is a new line.')
file_obj.close()
file_obj = open('/content/drive/MyDrive/data.csv','r')
print(file_obj.read())
file_obj.close()

OUTPUT 2 :
Q3. Write a Python program that reads the first 10 characters of a
file, then uses seek(5) to move the pointer to the 6th character, and
reads the next 5 characters from that position.
with open('/content/drive/MyDrive/data.csv', 'r') as file:
# Read the first 10 characters
first_10_chars = file.read(10)
print("First 10 characters:", first_10_chars)

# Move the file pointer to the 6th character (index 5)


file.seek(5)

# Read the next 5 characters


next_5_chars = file.read(5)
print("Next 5 characters:", next_5_chars)

OUTPUT 3 :

Q4. Write a Python program that reads a text file and counts the
number of words, lines, and characters in the file.
def count_file_stats(file_path):
num_words = 0
num_lines = 0
num_chars = 0

with open(file_path, 'r') as file:


for line in file:
num_lines += 1
words = line.split()
num_words += len(words)
num_chars += len(line)

return num_words, num_lines, num_chars

file_path = '/content/drive/MyDrive/data.csv'
words, lines, chars = count_file_stats(file_path)

print(f"Number of words: {words}")


print(f"Number of lines: {lines}")
print(f"Number of characters: {chars}")

OUTPUT 4 :

Q5. Write a Python program that takes user input and appends it to
a file. The program should continue accepting input until the user
enters "STOP".
file_path = '/content/drive/MyDrive/data.csv'
with open(file_path, 'a') as file:
while True:
user_input = input("Enter text to append (or 'STOP' to quit): ")
if user_input.upper() == "STOP":
break
file.write(user_input + "\n")
print("Input appended to file successfully!")
OUTPUT 5 :

Q6. Write a Python program that writes a list of dictionaries


(containing student data like name, age, and grade) to a CSV file.
import csv
student_data = [
{'name': 'Alia', ‘age': 16, 'grade': '10th'},
{'name': 'Bobby', 'age': 17, 'grade': '11th'},
{'name': 'Champ', 'age': 15, 'grade': '9th'},
]
csv_file_path = '/content/drive/MyDrive/student_data.csv'

with open(csv_file_path, 'w', newline='') as csvfile:


fieldnames = ['name', 'age', 'grade']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

writer.writeheader()
writer.writerows(student_data)

print(f"Student data written to '{csv_file_path}' successfully!")

OUTPUT 6 :
Q7. Write a Python program that compares the contents of two files
line by line and reports any differences.
def compare_files(file1_path, file2_path):
with open(file1_path, 'r') as file1, open(file2_path, 'r') as file2:
line_num = 1
while True:
line1 = file1.readline()
line2 = file2.readline()

if line1 != line2:
print(f"Difference found at line {line_num}:")
print(f"File 1: {line1.strip()}")
print(f"File 2: {line2.strip()}")

if not line1 and not line2:


break

line_num += 1

file1_path = '/content/drive/MyDrive/data.csv'
file2_path = '/content/drive/MyDrive/Matplotlib.csv'

compare_files(file1_path, file2_path)
print("File comparison complete.")
OUTPUT 7 :

Q8. Write a Python program that reads the contents of a file and
writes the lines in reverse order to a new file (i.e., last line first, first
line last).
def reverse_file_lines(input_file_path, output_file_path):
with open(input_file_path, 'r') as infile, open(output_file_path, 'w') as outfile:
lines = infile.readlines()
for line in reversed(lines):
outfile.write(line)
input_file_path = '/content/drive/MyDrive/Matplotlib.csv'
output_file_path = '/content/drive/MyDrive/output.txt'

reverse_file_lines(input_file_path, output_file_path)
print(f"File '{input_file_path}' reversed and written to '{output_file_path}'")
print('/n')
print("Original file is: ")
file_ob = open('/content/drive/MyDrive/Matplotlib.csv','r')
print(file_ob.read())
file_ob.close()
print('\n')
print("Reversed file is: ")
file_obj = open('/content/drive/MyDrive/output.txt','r')
print(file_obj.read())
file_obj.close()

OUTPUT 8 :

Q9. Write a program that reads a file and replaces all occurrences
of a given word with another word, saving the changes to the file.
def replace_word_in_file(file_path, old_word, new_word):
with open(file_path, 'r+') as file:
file_content = file.read()
new_content = file_content.replace(old_word, new_word)
file.seek(0)
file.write(new_content)
file.truncate()
file_path = '/content/drive/MyDrive/output.txt'
old_word = "is"
new_word = "IS"

replace_word_in_file(file_path, old_word, new_word)


print(f"Replaced '{old_word}' with '{new_word}' in '{file_path}'")

OUTPUT 9 :
Q10. Write a Python program that reads a file and counts how many
times a specific word appears in the file.
file = open('/content/drive/MyDrive/output.txt','r')
word_count ={}
content = file.read()
words = content.split()
for word in words:
word = word.lower()
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
file.close()
for word, count in word_count.items():
print(f"{word}: {count}")

OUTPUT 10 :
Python Packages

Q1 Plot a graph of y = x^2 for x values from 0 to 10. Customize the


graph with the following features:
• Set the title as "Quadratic Function"
• Label the x-axis as "x" and the y-axis as "y"
• Change the line color to red and line style to dashed.

import matplotlib.pyplot as plt


import numpy as np
x = np.arange(0,11, 1)
y = x ** 2
plt.plot(x, y, color='red', linestyle='--')
plt.title('Quadratic Function')
plt.xlabel('x')
plt.ylabel('y')
plt.show()

OUTPUT 1 :
Q2 Given the list of students' names ["Alice", "Bob", "Charlie",
"David"] and their corresponding scores [85, 92, 78, 90], plot a bar
chart to represent the scores of each student.

import matplotlib.pyplot as plt


students = ["Alice", "Bob", "Charlie", "David"]
scores = [85, 92, 78, 90]
plt.bar(students, scores, color='blue')
plt.title('Students and their Scores')
plt.xlabel('Students')
plt.ylabel('Scores')
plt.show()

OUTPUT 2 :

Q3 Write a Python program that generates random x and y data


points using numpy and creates a scatter plot using matplotlib.

import numpy as np
x = np.random.rand(100)
y = np.random.rand(100)
plt.scatter(x, y, color='green')
plt.title('Random Scatter Plot')
plt.xlabel('x')
plt.ylabel('y')
plt.show()

OUTPUT 3 :

Q4 Write a Python program that multiplies two 3x3 matrices using


numpy’s dot() function.

import numpy as np
matrix1 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
matrix2 = np.array([[9, 8, 7], [6, 5, 4], [3, 2, 1]])
result = np.dot(matrix1, matrix2)
print(result)
OUTPUT 4 :

Q5 Create a numpy array with numbers from 1 to 20 and slice the


array to print :
• The first 5 elements • The last 5 elements
• Elements at even indices
import numpy as np
arr = np.arange(1, 21)
print(arr[:5])
print(arr[-5:])
print(arr[::2])

OUTPUT 5 :

Q6 Create two numpy arrays a=np.array([1, 2, 3]) and b=np.array([4,


5, 6]). Perform element-wise addition, subtraction, multiplication,
and division of these arrays and print the results.
import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
print("Addition:", a + b)
print("Subtraction:", a - b)
print("Multiplication:", a * b)
print("Division:", a / b)
OUTPUT 6 :

Q7 Given a numpy array data = np.array([10, 15, 7, 22, 17]),


calculate and print the following statistics: • Mean • Standard
deviation • Median • Sum of all elements

import numpy as np
data = np.array([10, 15, 7, 22, 17])
print("Mean:", np.mean(data))
print("Standard deviation:", np.std(data))
print("Median:", np.median(data))
print("Sum:", np.sum(data))

OUTPUT 7 :

Q8 Create a DataFrame with the following data: data = {"Name":


["John", "Anna", "Peter", "Linda"], "Age": [28, 24, 35, 32], "City":
["New York", "London", "Berlin", "Tokyo"]} Perform the following
operations: • Print the column "Age". • Add a new column "Salary"
with values [50000, 60000, 55000, 65000]. • Filter and display rows
where the "Age" is greater than 30.
import pandas as pd
data = {
"Name": ["John", "Anna", "Peter", "Linda"],
"Age": [28, 24, 35, 32],
"City": ["New York", "London", "Berlin", "Tokyo"]
}
df = pd.DataFrame(data)
print(df["Age"])
df["Salary"] = [50000, 60000, 55000, 65000]
print(df)
print(df[df["Age"] > 30])

OUTPUT 8 :

Q9 Write a Python program to merge two DataFrames using


pandas. One DataFrame contains employee details (ID, Name,
Department), and another contains employee salaries (ID, Salary).
Merge them based on the "ID" column.
import pandas as pd
employee_details = pd.DataFrame({
"ID": [1, 2, 3, 4],
"Name": ["Alice", "Bob", "Charlie", "David"],
"Department": ["HR", "Finance", "IT", "Marketing"]
})
employee_salaries = pd.DataFrame({
"ID": [1, 2, 3, 4],
"Salary": [50000, 60000, 55000, 65000]
})
merged_df = pd.merge(employee_details, employee_salaries, on="ID")
print(merged_df)

OUTPUT 9 :

Q10 Read a CSV file containing daily weather data (e.g.,


temperature, humidity, rainfall). Use pandas to perform the
following: • Calculate the average temperature for each month. •
Plot a line graph of the daily temperature over time using
matplotlib.

import pandas as pd
import matplotlib.pyplot as plt
weather_data = pd.read_csv('weather.csv')
weather_data['Date'] = pd.to_datetime(weather_data['Date'])
weather_data['Month'] = weather_data['Date'].dt.month
monthly_avg_temp = weather_data.groupby('Month')['Temperature'].mean()
print(monthly_avg_temp)
plt.plot(weather_data['Date'], weather_data['Temperature'])
plt.title('Daily Temperature Over Time')
plt.xlabel('Date')
plt.ylabel('Temperature')
plt.xticks(rotation=45)
plt.show()

TKINTER
Q1 Write a Python program to create a basic Tkinter window with
the following properties:
● The window title should be "Welcome Window".
● The window should have a fixed size of 500x400 pixels.
● Add a label that says "Hello, Tkinter!" in the center of the window.
import tkinter as tk
def main():
window = tk.Tk()
window.title("Welcome Window")
window.geometry("500x400")
window.resizable(False, False)
label = tk.Label(window, text="Hello, Tkinter!", font=("Arial", 16))
label.pack(expand=True)
window.mainloop()
if __name__ == "__main__":
main()
OUTPUT 1 :

Q2 Create a Tkinter window with a button labeled "Press Me". When


the button is clicked, it should display a pop-up message box with
the text "Button was clicked!
import tkinter as tk
from tkinter import messagebox
def on_button_click():
messagebox.showinfo("Information", "Button was clicked!")
def main():
window = tk.Tk()
window.title("Welcome Window")
window.geometry("500x400")
window.resizable(False, False)
label = tk.Label(window, text="Hello, Tkinter!", font=("Arial", 16))
label.pack(expand=True)
button = tk.Button(window, text="Press Me", command=on_button_click)
button.pack(pady=20)
window.mainloop()
if __name__ == "__main__":
main()
OUTPUT 2 :

Q3 Build a simple calculator using Tkinter. The calculator should


have buttons for numbers 0-9, and basic arithmetic operators (+, -,
*, /). It should display the result when the user clicks the "=" button.
import tkinter as tk
def button_click(value):
if value == "=":
try:
result = eval(entry.get())
entry.delete(0, tk.END)
entry.insert(tk.END, str(result)) # Insert the result
except Exception as e:
entry.delete(0, tk.END)
entry.insert(tk.END, "Error")
elif value == "C":
entry.delete(0, tk.END) # Clear the entry widget
else:
entry.insert(tk.END, value) # Insert the button value
def main():
window = tk.Tk()
window.title("Simple Calculator")
window.geometry("400x500")
window.resizable(False, False)
global entry
entry = tk.Entry(window, font=("Arial", 20), borderwidth=5, relief=tk.RIDGE,
justify=tk.RIGHT)
entry.grid(row=0, column=0, columnspan=4, padx=10, pady=10)
buttons = [
'7', '8', '9', '/',
'4', '5', '6', '*',
'1', '2', '3', '-',
'C', '0', '=', '+'
]
row_val = 1
col_val = 0
for button in buttons:
tk.Button(window, text=button, font=("Arial", 18), command=lambda val=button:
button_click(val), width=5, height=2).grid(row=row_val, column=col_val, padx=5,
pady=5)
col_val += 1
if col_val > 3:
col_val = 0
row_val += 1
window.mainloop()
if __name__ == "__main__":
main()
OUTPUT 3 :

Q4 Create a login form with two input fields for username and
password. Add a "Login" button that validates the inputs:
● If the username is "admin" and the password is "password123",
display "Login successful" in a label below the button.
● If the credentials are incorrect, display "Invalid username or
password"
import tkinter as tk
def validate_login():
username = username_entry.get()
password = password_entry.get()
if username == "admin" and password == "password123":
result_label.config(text="Login successful", fg="green")
else:
result_label.config(text="Invalid username or password", fg="red")
def main():
window = tk.Tk()
window.title("Login Form")
window.geometry("400x300")
window.resizable(False, False)
tk.Label(window, text="Username:", font=("Arial", 14)).pack(pady=10)
global username_entry
username_entry = tk.Entry(window, font=("Arial", 14), width=25)
username_entry.pack(pady=5)
tk.Label(window, text="Password:", font=("Arial", 14)).pack(pady=10)
global password_entry
password_entry = tk.Entry(window, font=("Arial", 14), show="*", width=25)
password_entry.pack(pady=5)
tk.Button(window, text="Login", font=("Arial", 14),
command=validate_login).pack(pady=20)
global result_label
result_label = tk.Label(window, text="", font=("Arial", 14))
result_label.pack(pady=10)
window.mainloop()
if __name__ == "__main__":
main()

OUTPUT 4 :

Q5 Create a Tkinter application to convert temperatures between


Celsius and Fahrenheit. It should have:
● Two entry fields: one for Celsius and one for Fahrenheit.
● Buttons to convert from Celsius to Fahrenheit and vice versa.
● Display the converted temperature in the appropriate entry field.
import tkinter as tk
def convert_to_fahrenheit():
try:
celsius = float(celsius_entry.get())
fahrenheit = (celsius * 9/5) + 32
fahrenheit_entry.delete(0, tk.END)
fahrenheit_entry.insert(0, f"{fahrenheit:.2f}")
except ValueError:
fahrenheit_entry.delete(0, tk.END)
fahrenheit_entry.insert(0, "Invalid input")
def convert_to_celsius():
try:
fahrenheit = float(fahrenheit_entry.get())
celsius = (fahrenheit - 32) * 5/9
celsius_entry.delete(0, tk.END)
celsius_entry.insert(0, f"{celsius:.2f}")
except ValueError:
celsius_entry.delete(0, tk.END)
celsius_entry.insert(0, "Invalid input")
def main():
window = tk.Tk()
window.title("Temperature Converter")
window.geometry("400x200")
window.resizable(False, False)
tk.Label(window, text="Celsius:", font=("Arial", 14)).grid(row=0, column=0,
padx=10, pady=10)
global celsius_entry
celsius_entry = tk.Entry(window, font=("Arial", 14), width=15)
celsius_entry.grid(row=0, column=1, padx=10, pady=10)
tk.Label(window, text="Fahrenheit:", font=("Arial", 14)).grid(row=1, column=0,
padx=10, pady=10)
global fahrenheit_entry
fahrenheit_entry = tk.Entry(window, font=("Arial", 14), width=15)
fahrenheit_entry.grid(row=1, column=1, padx=10, pady=10)
tk.Button(window, text="Convert to Fahrenheit", font=("Arial", 12),
command=convert_to_fahrenheit).grid(row=2, column=0, padx=10, pady=10)
tk.Button(window, text="Convert to Celsius", font=("Arial", 12),
command=convert_to_celsius).grid(row=2, column=1, padx=10, pady=10)
window.mainloop()
if __name__ == "__main__":
main()
OUTPUT 5 :

You might also like