0% found this document useful (0 votes)
4 views23 pages

gaurisha_11

The document contains a list of programming tasks and corresponding Python code snippets for various algorithms and functionalities, such as calculating series sums, checking for Armstrong and palindrome numbers, searching algorithms, sorting methods, and file operations. Each task is numbered and includes example code and output for clarity. The tasks cover a wide range of topics, including basic programming concepts, data structures, and file handling in Python.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views23 pages

gaurisha_11

The document contains a list of programming tasks and corresponding Python code snippets for various algorithms and functionalities, such as calculating series sums, checking for Armstrong and palindrome numbers, searching algorithms, sorting methods, and file operations. Each task is numbered and includes example code and output for clarity. The tasks cover a wide range of topics, including basic programming concepts, data structures, and file handling in Python.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 23

INDEX

S.NO Code:
1. Write a program to input values of x and n and print the sum of the series:
1+x+x2+x3+……xn
2. Write a python program to determine whether a number is an Armstrong
number or not.
3. Write a python program to determine whether a number is Palindrome
number or not.
4. Write a python program to input a number and check if the number is a
prime or composite number.
5. Write a python program for pattern:
*******
*****
***
*
6. Write a python program to compute the nth Fibonacci number
7. Write a python program to find the factorial of a natural number.
8. Write a python program of linear search
9. Write a python program of binary search
10. Write a python program for sorting a list using bubble sort
11. Write a python program for sorting a list using selection sort
12. Write a python program to input a string and determine whether it is a
palindrome or not and then convert the case of characters in a string.
13. Write a python program to count number of alphabet, digit, special
symbol of given statement
14. Write a python program to read a text file line by line and display each
word separated by a ‘#’.
15. Write a python program to read a text file and display the number of
vowels, consonants, uppercase and lowercase characters present in a text file
STORY.TXT.
16. Write a python program to remove all the lines that contain the character
‘a’ in a text file and write it to another file.
17. Write a python program to count the word “this” present in a text file
DATA.TXT
18. Write a python random number generator that generates random numbers
between 1 and 6 (simulates a dice)
19. Write a python program to create a binary file with name and roll number. Search for
a given roll number and display the name, if not found display
appropriate message
20. Write a python program to create a binary file with roll number, name and
marks. Input a roll number and update the marks
21. Write a python program to check whether the entered number is even or
odd
22. Write a python program to create a CSV file to store student data (Rollno, Name,
Marks). Obtain data from user and write five records into the file.
Again open this CSV file to read its records and display them.
23. Write a python program to implement a stack using a list data-structure
24. Write a python program to check whether the entered number is even or
odd
25. Write a program in Python including PUSH(Arr), where Arr is a list of
numbers. Implemented by using a list.
26. Given a stack named book_details that contains book_no, book_name and price.
Write a menu driven program to implement the following functions
for the stack.
27. SQL program 1
28. SQL program 2
29. SQL program 3
30. SQL program 4
31. SQL program 5
32. SQL program 6
33. Write a python program that displays first three rows fetched from
employee table by integrating SQL with python
34. Write a python database connectivity script that deletes records from
category table of database items that have name=’Stockable’.
35. Write python code to connect to a MYSQL database namely School and
then fetch all those records from table Student where grade is ‘A’.
Ques1. Write a program to input values of x and n and print the sum
of the series:
1+x+x2+x3+……xn

code:

x=int(input("Enter The Value Of x ="))


n=int(input("Enter The Value Of n ="))
sum=0
for i in range(n+1):
sum=sum+(x**i)
print (“The sum of series=”, sum)

output:

Enter The Value Of x = 2


Enter The Value Of n = 5
The sum of series = 63

Ques2. Write a python program to determine whether a number is an


Armstrong number or not.

code:

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


sum = 0
temp = num

while temp > 0:


digit = temp % 10
sum += digit ** 3
temp //= 10

if num == sum:
print(num, "is an Armstrong number")
else:
print(num, "is not an Armstrong number")
output:

Enter a number: 343


343 is not an Armstrong number

Enter a number: 370


370 is an Armstrong number

Ques3. Write a python program to determine whether a number is


Palindrome number or not.

Code:

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


temp = num
rev = 0

while num > 0:


dig = num % 10
rev = rev * 10 + dig
num = num // 10

if temp == rev:
print("The number is a palindrome!")
else:
print("Not a palindrome!")

Output:

Enter a number: 6
The number is a palindrome!

Enter a number: 32
Not a palindrome!
Ques4. Write a python program to input a number and check if the
number is a prime or composite number.

Code:

x = int(input("Enter The Number = "))


c=0

if x == 2:
print(x, "The number is Prime")
else:
for i in range(2, x):
if x % i == 0:
c += 1
if c > 0:
print("Number Is Composite.")
else:
print("The Number Is Prime.")

Output:

Enter The Number = 4


Number Is Composite.

Enter The Number = 7


The Number Is Prime.

Ques5. Write a python program for pattern:


*******
*****
***
*

code:

for i in range(4, 0, -1):


for j in range(4 - i):
print(' ', end='')
for j in range(2 * i - 1):
print('*', end='')
print()

Output:

*******
*****
***
*

Ques6. Write a python program to compute the nth Fibonacci number

Code:

num = int ( input (“ Enter a number =”) )


a=0
b=1
sum = 0
for i in range(0, num):
sum = sum + a
c=a+b
a=b
b=c
print (“Sum of Fibonacci Series=”,sum )

Output:

Enter the number = 10


Sum of Fibonacci Series = 54

Ques7. Write a python program to find the factorial of a natural


number.
Code:

def factorial(x):
f=1
for i in range(1, x + 1):
f *= i
print("Factorial =", f)

x = int(input("Enter The Number: "))


factorial(x)

Output:

Enter The Number: 5


Factorial = 120

Ques8. Write a python program of linear search

Code:

l = []
N = int ( input (“ Enter The Range Of List:”))
for i in range ( N ):
ele = int ( input (“ Enter The Element:”) )
l.append ( ele )
search = int ( input (“ Enter The Element For Search:”) )
c=0
for i in range ( N ):
if ( l[i] == search ):
print (“ Element Found At Location:” , i )
c += 1
if ( c == 0 ):
print (“ Element Not Found” )

Output:

Enter The range Of List: 5


Enter The Element: 10
Enter The Element: 20
Enter The Element: 30
Enter The Element: 40
Enter The Element: 50
Enter The Element For Search: 30
Element Found At Location: 2

Ques9. Write a python program of binary search.

Code:

l = []
N = int ( input (“ Enter The Range Of List:”) )
for i in range ( N ):
ele = int ( input (“ Enter The Element:”) )
l.append ( ele )
lowlim = 0
uplim = N - 1
c=0
search = int ( input (“ Enter The Element For Search:”) )
while ( lowlim <= uplim ):
mid = ( lowlim + uplim ) // 2
if ( l[mid] == search ):
print (“ Element Found At Location:”, mid )
c += 1
break
elif ( l[mid] > search ):
uplim = mid - 1
elif ( l[mid] < search ):
lowlim = mid + 1
if ( c == 0 ):
print (“Element Not Found”)

Output:

Enter The Range Of List: 6


Enter The Element: 10
Enter The Element: 20
Enter The Element: 30
Enter The Element: 40
Enter The Element: 50
Enter The Element: 60
Enter The Element For Search: 40
Element Found At Location: 3

Ques10. Write a python program for sorting a list using selection sort.

Code:

l = []
N = int ( input (“ Enter range:”) )
for i in range ( N ):
ele = int ( input (“ Enter element: "”))
l.append ( ele )
for i in range ( N - 1 ):
for j in range ( i+1 , N ):
if ( l[j] < l[i] ):
l[i] , l[j] = l[j] , l[i]
print (“Sorted List:”, l )

Output:

Enter range: 5
Enter element: 12
Enter element: 14
Enter element: 8
Enter element: 10
Enter element: 4
Sorted List: [4, 8, 10, 12, 14]

Ques11. Ques10. Write a python program for sorting a list using


Binary sort.

Code:
l = []
N = int ( input ("; Enter range: ";) )
for i in range ( N ):
ele = int ( input ("; Enter element: ";) )
l.append ( ele )
for i in range ( N - 1 ):
for j in range ( N - i - 1 ):
if ( l[j] > l[j+1] ):
l[j] , l[j+1] = l[j+1] , l[j]
print ("; Sorted List: ";, l )

Output:
Enter range: 5
Enter element: 3
Enter element: 5
Enter element: 1
Enter element: 12
Enter element: 10
Sorted List: [1, 3, 5, 10, 12]

Ques12. Write a python program to input a string and determine


whether it is a palindrome or not and then convert the case of
characters in a string.

Code:

str = input (“ Enter a word:”)


s = “”
rev = str[ : :-1]
if ( str == rev ):
print (“Word is Palindrome”)
else :
print (“Word is not Palindrome”)
for ch in str:
if ( ch.isupper() ):
s = s+ch.lower()
elif ( ch.islower() ):
s = s+ch.upper()
print (“String after case change:”,s)

Output:

Enter a word: MalayalaM


Word is Palindrome
String after case change: mALAYALAm

Ques13. Write a python program to count number of alphabet, digits,


special symbol of given statement.

Code:

str = input (“Enter a sentence:”)


alphabet = 0
digit = 0
special_symbol = 0
whitespace = 0
for ch in str:
if ( ch.isalpha() ):
alphabet += 1
elif ( ch.isdigit() ):
digit += 1
elif ( ch.isspace() ):
whitespace += 1
else :
special_symbol += 1
print ( “Alphabets:”,alphabet )
print ( “ Digits:”,digit )
print ( "Special Symbols: ",special_symbol)

Output:

Enter a sentence: An apple a day 123 keeps *&^ away


Alphabets: 20
Digits: 3
Special Symbols: 3

Ques14.Write a python program to read a text file line by line and


display each word separated by a#.

Code:

f = open ( "Myfile.txt" , 'r' )


lines = f . readlines ( )
for line in lines:
line = line.split ( "a#" )
for words in line:
print ( words , end='' )

Input:

An a#applea# a day kea#eps the docta#ora#


away

Output:

An apple a day keeps the doctor away

Ques15. Write a python program to read a text file and display the
number of vowels, consonants, uppercase and lowercase characters
present in a text file
STORY.TXT.

Code:

f = open ( "STORY.txt" , 'r' )


lines = f.readlines ( )
vowel = 0
consonant = 0
upper = 0
lower = 0
for line in lines:
line = line.split ( " " )
for word in line:
for ch in word:
if ( ch in "AEIOUaeiou" ):
vowel += 1
else :
consonant += 1
if ( ch.isupper() ):
upper += 1
else :
lower += 1
print ( "Vowels: ", vowel )
print ( "Consonants: ", consonant )
print ( "Uppercase characters: ", upper )
print ( "Lowercase characters: ", lower )

Input:

Time Flows Like A River

Output:

Vowels: 8
Consonants: 14
Uppercase characters: 5
Lowercase characters: 17

Ques 16. Write a python program to remove all the lines that contain
the character ‘a’ in a text file and write it to another file.

Code:

def remove_add():
f=open("file.txt","r")
f2=open("File2.txt","w")
data=f.readlines()
for i in data:
if "a" in i:
i=i.replace(i," ")
f2.write(i)
f.close()
f2.close()
remove_add()

Q17. Write a python program to count the word “this” present in a


text file

Code:

DATA.TXT
fi=open('data.txt','w')
l=['this computer program is executed by a
computer.\n','Computer requires programs to function.\n']
fi.writelines(l)
fi.close()
def count():
fi=open('data.txt')
rec=fi.readlines()
print (rec)
count1=0
for line in rec:
k=line.split(' ')
for word in k:
if word in ['this','THIS','This']:
count1+=1
print('no of this in the file is', count1)
count()

Output:

no of this in the file is 1

Q18. Write a python random number generator that generates


random numbers between 1 and 6 (simulates a dice).
Code:

import random
ans=input('do you want to roll dice(Y/N)')
while ans in 'Yy':
k=random.randint(1,6)
print(k)
ans=input('do you want to roll dice again(Y/N)')
if ans in 'Nn':
break

Output:

do you want to roll dice(Y/N)Y


5
do you want to roll dice again(Y/N)Y
1
do you want to roll dice again(Y/N)N

Q19. Write a python program to create a binary file with name


and roll number. Search for a given roll number and display the
name, if not found display appropriate message.

Code:

import pickle
def write():
D={}
f=open ("Studentdetails.dat","wb")
while True:
r=int(input("Enter roll no="))
n=input("Enter name=")
D['Roll no']=r
D['Name']=n
pickle.dump(D,f)
ch=input("More?(Y/N)")
if ch in "Nn":
break
f.close()
def Search():
found=0
rollno=int(input("Enter roll no whose name you
want to display="))
f=open("Studentdetails.dat",'rb')
try:
while True:
rec=pickle.load(f)
if rec['Roll no']==rollno:
print(rec['Name'])
found=1
break
except EOFError:
f.close()
if found==0:
print("Sorry not found....")
f.close()
write()
Search()

Output:

Enter roll no=1


Enter name= Adeline
More?(Y/N)y
Enter roll no=2
Enter name= Lightwood
More?(Y/N)n
Enter roll no whose name you want to display=2
lila

Q20. Write a python program to create a binary file with name and
roll number. Search for a given roll number and display the name, if
not found display appropriate message.

Code:
import pickle
def write():
f= open("studentdetails.dat",'wb')
while True:
r=int(input("Enter roll no. ="))
n = input("Enter Name : ")
m = int(input ("Enter Marks : "))
record = [r,n,m]
pickle.dump(record,f)
ch = input("Do you want to enter more?(Y/N)")
if ch in "Nn":
break

f.close()
def Read():
f=open("Studentdetals.dat",'rb')
try:
while True:
rec=pickle.load(f)
print(rec)
except EOFError:
f.close()
def Update():
f=open("Studentdetails.dat",'rb+')
rollno=int(input("Enter roll no whose marks you want to
update"))
try:
while True:
pos=f.tell()
rec=pickle.load(f)
if rec[0]==rollno:
um=int(input("Enter updated marks="))
rec[2]=um
f.seek(pos)
pickle.dump(rec,f)
#print(rec)
except EOFError:
f.close()
write()
Read()
Update()
Read()

Output:

Enter roll no: 1


Enter Name: Alice
Do you want to enter more? (Y/N): Y

Enter roll no: 2


Enter Name: Bob
Do you want to enter more? (Y/N): N

Q21. Write a python program to check whether the entered


number is even or odd.

Code:

num=int(input(“enter number=”))
if(num%2==0):
print(“number is even”)

else:
print(“number is odd”)

Output:
enter number=5
number is odd
enter number=4
number is even

Q22. Write a python program to create a CSV file to store student data
(Rollno, Name, Marks). Obtain data from user and write five records
into the file. Again open this CSV file to read its records and display
them.

Code:

import csv
def create_record():
f=open('data.csv','w')
rows=[[1,'naman',13],
[2,'adi', 34],
[3, 'om', 56]]
writer=csv.writer(f)
writer.writerows(rows)
f.close()
def read_record():
f=open("data.csv",'r')
reader=csv.reader(f)
for row in reader:
print(row)
read_record()

Output:

[1, 'naman', '13']


[2, 'adi', '34']
[3, 'om', '56']

Q24. Write a python program to check whether the entered number is


even or Odd.

Code:

num=int(input(“enter number=”))
if(num%2==0):
print(“number is even”)

else:
print(“number is odd”)

Output:

enter number=5
number is odd
enter number=4
number is even

Q25. Write a program in Python including PUSH(Arr), where Arr is a


list of numbers. Implemented by using a list.

Code:

def PUSH(Arr):
stack=[]
for i in Arr:

stack.append(i)
print(stack)

Arr=[8,9,10]
Push(Arr)

Output :
[8, 9, 10]

Q26. Given a stack named book_details that contains book_no,


book_name and price. Write a menu driven program to implement
the following functions
for the stack.

Code:

book_details=[]
def insertion():

book_no=int(input('enter book no'))


book_name= input('enter book name')
price=int(input('enter book price'))
l=[book_no,book_name,price]
book_details.append(l)

def deletion():
if len(book_details)==0:
print('stack underflow')
else:
print('popped element=')

book_details.pop()

def display():
if len(book_details)==0:
print('stack empty')
else:
for i in book_details:
print(i)

while True:
print('1:push')
print('2.pop')
print('3.display')
ch=int(input('enter choice'))
if ch==1:
insertion()
if ch==2:
deletion()
if ch==3:
display()
else:
print('wrong choice ')
ans=input(('want to perform more operation(y/n)'))
if ans in 'nN':
break

Output:
1: Push
2: Pop
3: Display
Enter choice: 1
Enter book no: 1
Enter book name: BookA
Enter book price: 10
Want to perform more operations? (y/n): y

1: Push
2: Pop
3: Display
Enter choice: 1
Enter book no: 2
Enter book name: BookB
Enter book price: 20
Want to perform more operations? (y/n): y

1: Push
2: Pop
3: Display
Enter choice: 3
[1, 'BookA', 10]
[2, 'BookB', 20]
Want to perform more operations? (y/n): y

1: Push
2: Pop
3: Display
Enter choice: 2
Popped element: [2, 'BookB', 20]
Want to perform more operations? (y/n): y

1: Push
2: Pop
3: Display
Enter choice: 3
[1, 'BookA', 10]
Want to perform more operations? (y/n): n

You might also like