0% found this document useful (0 votes)
15 views47 pages

Programming Basics: Prime, Fibonacci, Palindrome, and More

The document outlines various programming tasks, including prime number verification, Fibonacci series generation, palindrome checking, and factorial calculation, among others. Each task includes the aim, source code, and confirmation of successful execution. Additionally, it covers file operations, arithmetic operations, and SQL queries, demonstrating a range of programming concepts and their implementations.

Uploaded by

udtbooks
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)
15 views47 pages

Programming Basics: Prime, Fibonacci, Palindrome, and More

The document outlines various programming tasks, including prime number verification, Fibonacci series generation, palindrome checking, and factorial calculation, among others. Each task includes the aim, source code, and confirmation of successful execution. Additionally, it covers file operations, arithmetic operations, and SQL queries, demonstrating a range of programming concepts and their implementations.

Uploaded by

udtbooks
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

Output:

1
1. Prime Number Verification

Aim:
To write a program to check whether a number is prime or not.

Source Code:
# taking input from user
number = int(input("Enter any number: "))

# prime number is always greater than 1


if number > 1:
for i in range(2, number):
if (number % i) == 0:
print(number, "is not a prime number")
break
else:
print(number, "is a prime number")

# if the entered number is less than or equal to 1


# then it is not prime number
else:
print(number, "is not a prime number")

Result:
The program to check if the given number is prime or not, was successfully
executed and the output was verified.

2
Output:

3
2. Fibonacci Series

Aim:
To write a program to enter the number of terms and to print the Fibonacci
Series.

Source Code:
#Fibonacci sequence
n=int(input("Enter the number of terms:"))
n1=0
n2=1
count=0
if n<=0:
print("Enter valid number of terms")
elif n==1:
print("Fibonacci sequence up to",n,"terms is")
print(n1)
else:
print("Fibonacci sequence:")
while count<n:
print(n1)
nth=n1+n2
n1,n2=n2,nth
count+=1

Result:
The program to print fibonacci sequence was successfully executed and the output
was verified.

4
Output:

5
3. Palindrome Verification

Aim:
To write a program to check whether a string is palindrome.

Source Code:
#taking a input- string from user
st1=input("enter a word:")
#checking palindrome
if st1==st1[::-1]:
print("The given string:",st1,"is a palindrome.")
else:
print("The given string:",st1,"is not a palindrome.")

Result:
The program to check if the given string is a palindrome or not was successfully
executed and the output was verified.

6
Output:

7
4. Displaying factorial of a number

Aim:
To write a program to display the factorial of a number.

Source Code:
#input from user
num=int(input("Enter a number to find the factorial : "))
fac=1
count=1

#finding factorial
while count<=num:
fac=fac*count
count=count+1
else:
print("The factorial of the number",num,"is",fac)

Result:
The program to display the factorial of a number was successfully executed and
the output was verified.

8
Output:

9
5. Creation of Binary file and Search

Aim:
To write a program to create a binary file and search a record in it.

Source Code:
import pickle
print(" Entering the data in binary file")
fh=open("[Link]","wb")
data={}
var=int(input("Enter the no of records to be written:"))
for i in range(var):
Roll_no=int(input("Roll_no:"))
Name=input("Name:")
Dept=input("Dept:")
data["Roll_no"]=Roll_no
data["Name"]=Name
data["Dept"]=Dept
[Link](data,fh)
rollno=int(input("enter roll no to search"))
with open("[Link]","rb") as fh:
data={}
try:
while True:
data=[Link](fh)
if rollno==data['Roll_no']:
print(data)
except EOFError:
[Link]()

Result:
The program to create a binary file and search a record in it was successfully
executed and the output was verified.

10
Output:

11
6. Armstrong Number Verification

Aim:
To write a program to verify if the number is an armstrong number or not.

Source Code:
# take input from the user
num = int(input("Enter a number: "))
sum = 0

# finding the sum of the cube of each digit


a = num
while a > 0:
digit = a % 10
sum += digit ** 3
a//= 10
if num == sum:
print(num,"is an Armstrong number")
else:
print(num,"is not an Armstrong number")

Result:
The program to verify if the number is an armstrong number or not was
successfully executed and the output was verified.

12
Output:
Text file:

13
7. Removal of Lines with “a”

Aim:
To write a program to remove lines with “a”

Source Code:
myfile=open('[Link]','r')
myfh=open('[Link]','w')
line=" "
while line:
line=[Link]()
if 'a' not in line:
[Link](line)
[Link]()
[Link]()

print("Newly created file contains")


print("..............................................")
myfh=open("[Link]","r")
line=" "
while line:
line=[Link]()
print(line)
[Link]()

Result:
The program to remove the lines with “a”, was successfully executed and the
output was verified.

14
Output:
Text file:

15
8. Count of occurrences of Each Word

Aim:
To write a program to count the occurrences of each word.

Source Code:
text = open("[Link]", "r")
d = dict()
for line in text:
line = [Link]()
line = [Link]()
words = [Link](" ")
for word in words:
if word in d:
d[word] = d[word] + 1
else:
d[word] = 1
for key in list([Link]()):
print(key, ":", d[key])
[Link]()

Result:
The program to count the occurrences of each word was successfully executed and
the output was verified.

16
Output:

17
9. Displaying number of vowels, consonants, uppercase and lowercase
characters in the file

Aim:
To write a program to display the number of vowels, consonants, uppercase
and lowercase characters in the file

Source Code:
f=open("[Link]","r")
pm=[Link]()
print(pm)
vc=0
cc=0
lc=0
uc=0
for ch in pm :
if ([Link]()):
lc+=1
elif([Link]()):
uc+=1
ch=[Link]()
if( ch in ['a','e','i','o','u']):
vc+=1
elif (ch in ['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z']):
cc+=1
[Link]()
print("Vowels are : ",vc)
print("consonants are : ",cc)
print("Lower case letters are : ",lc)
print("Upper case letters are : ",uc)

Result:
The program to display the number of vowels, consonants, uppercase and
lowercase characters in the file was successfully executed and the output was
verified.

18
Output:

19
10. Arithmetic Operations for Two Numbers

Aim:
To write a program to perform Arithmetic operations for two numbers.

Source Code:
#Input from user
a =int(input("Enter a number : "))
b =int(input("Enter a number : "))
print("[Link] [Link] [Link] [Link] [Link]")
#asking for choice of operator
ch=int(input("Enter your choice of operator : "))

if ch==1:
add = a + b
print("The result of ",a,"added to",b,"is",add)
elif ch==2:
sub = a - b
print("The result of ",b,"subtracted from",a,"is",sub)
elif ch==3:
mul = a * b
print("The result of ",a,"times",b,"is",mul)
elif ch==4:
mod = a % b
print("The result of ",a,"modulus",b,"is",mod)
elif ch==5:
p = a ** b
print("The result of ",a,"raised to the power",b,"is",p)
else:
print("Invalid choice :(")

Result:
The program to perform Arithmetic operations for two numbers was successfully
executed and the output was verified.

20
Output:

21
11. Creation of Binary file and Search to update marks

Aim:
To write a program to create a Binary file and Search to update marks.

Source Code:
import pickle
#creating a file(binary)
print(" Entering the data in binary file")
fh=open("[Link]","wb")
data={}
var=int(input("Enter the number of records to be written:"))
for i in range(var):
Roll_no=int(input("Roll_no:"))
Name=input("Name:")
Marks=float(input("Marks:"))
data["Roll_no"]=Roll_no
data["Name"]=Name
data["Marks"]=Marks
[Link](data,fh)
choice=input("""Do you want to see the records?
Enter y to continue """)
if choice=='y':
Rollno=int(input("Enter your roll no to display the record:"))
with open("[Link]","rb") as fh:
data={}
try:
while True:
data=[Link](fh)
if data['Roll_no']==Rollno:
print(data)
except EOFError:
[Link]()

22
23
#Updating the file(binary)
data={}
fh=open('[Link]','rb+')
Rollno=int(input("Enter the roll no to update marks:"))
Marks=float(input("Enter marks that are required to be updated:"))
try :
while True:
pos=[Link]()
data=[Link](fh)
for i in data:
if data["Roll_no"]== Rollno:
data['Marks']=Marks
[Link](pos)
[Link](data,fh)
except EOFError:
choice=input("""\nDo you want to see the records?\n Enter y to continue """)
if choice=='y':
Rollno=int(input("Enter your roll no to display the record:"))
with open("[Link]","rb") as fh:
data={}
try:
while True:
data=[Link](fh)
if data['Roll_no']==Rollno:
print(data)
except EOFError:
[Link]()

Result:
The program to create a Binary file and Search to update marks was successfully
executed and the output was verified.

24
Output:

25
12. Random Number Generator

Aim:
To write a program to generate a random number.

Source Code:
import random
while True:
ch=input("Wanna play ?,Roll the dice(y/n):")
if ch=='y':
print("Your lucky number is :",[Link](0,6))
else:
Break

Result:
The program to generate a random number was successfully executed and the
output was verified.

26
Output:

27
13. Separation of Words by ‘#’

Aim:
To write a program to separate words with ”#”.

Source Code:
fh=open("[Link]","r")
line=" "
while line:
line=[Link]()
for word in [Link]():
print(word,end='#')
print()
[Link]()

Result:
The program to separate words with ”#” was successfully executed and the output
was verified.

28
Output:

Table created:

29
14. Creation of CSV file by entering user-id and password

Aim:
To write a program to create a CSV file by entering user-id and password.

Source Code:
import csv
def create_csv_file(filename):
with open(filename, 'w', newline='') as file:
writer = [Link](file)
[Link](["User ID", "Password"])
for i in range(n):
user_id = input("Enter User ID (or 'exit' to finish): ")
if user_id.lower() == 'exit':
break
password = input("Enter Password: ")
[Link]([user_id, password])

filename = "UserID,[Link]"
n=int(input("no of userid,passkeys:"))
create_csv_file(filename)
print("CSV file '{filename}' has been created.")

Result:
The program to create a CSV file by entering user-id and password was
successfully executed and the output was verified.

30
Output:

31
15. Implementation of a Stack using List

Aim:
To write a program to implement a stack using a list.

Source Code:
#### stk IMPLEMENTED AS LIST####
def isEmpty(stk):
if stk==[]:
return True
else:
return False
def push(stk,itm):
[Link](itm)
top=len(stk) -1
def pop(stk):
if isEmpty(stk):
return "UNDERFLOW"
else:
itm=[Link]()
if len(stk)==0:
top=None
else:
top=len(stk) -1
return itm
def peek(stk):
if isEmpty(stk):
return "UNDERFLOW"
else:
top=len(stk) -1
return stk[top]
def display(stk):
if isEmpty(stk):
print("EMPTY stk")
else:
top=len(stk) -1
print(stk[top],"---top")
for a in range(top-1,-1,-1):
print(stk[a])

32
33
#__main__
stk=[]
top=None
while True:
print("stk OPERATIONS")
print("[Link]")
print("[Link]")
print("[Link]")
print("[Link] stk")
print("[Link]")
ch=int(input("enter your choice(1-5):"))
if ch==1:
itm=int(input("Enter item:"))
push(stk,itm)
elif ch==2:
itm=pop(stk)
if itm=="UNDERFLOW":
print("Underflow...stk is Empty :(")
else:
print("popped item is :",itm)
elif ch==3:
itm=peek(stk)
if itm=="UNDERFLOW":
print("Underflow! stk is empty")
else:
print("Topmost item is ",itm)
elif ch==4:
display(stk)
elif ch==5:
print("terminating the loop")
break
else:
print("INVALID CHOICE!")

Result:
The program to implement a stack using list was successfully executed and the
output was verified.

34
Output:
#Table description:

#Table created:

#Alter table(col = sec):

35
16. Creation of Table and Implementation of SQL Queries

Aim:
To write a program to create a Table and Implement the following SQL
commands on the student table
ALTER table to add new attributes / modify data type / drop attribute
UPDATE table to modify data
ORDER By to display data in ascending / descending order
DELETE to remove tuple(s)
GROUP BY and find the min, max, sum, count and average.

Source Code:
#Creating table;
create table g12(rollno integer PRIMARY KEY,
names char(20) NOT NULL,
class char(3),
dept char(5),
marks integer,
grade char(2));

#Inserting values;
insert into g12 values(221,"divya","12","CS",98,"A");
insert into g12 values(222,"dhinesh","12","CS",90,"A");
insert into g12 values(223,"dhesigan","12","Bio",90,"A");
insert into g12 values(224,"elizabeth","12","Bio",93,"A");
insert into g12 values(225,"shruthi","12","Bio",96,"A");

#Altering table;
Alter table g12 Add (sec char(2));

#Updating table;
Update g12
set marks=91
where marks=90;

36
#Update Table:

#Order by:

#Delete:

#Group by:

37
#order by ascending /descending;
select * from g12
Order by names;

#Delete;
delete from g12 where marks=91;

#Group by;
Select Names,marks,dept from g12 group by dept;

Result:
The program to create a table and Implement SQL queries was successfully
executed and the output was verified.

38
Output:
#Database:

39
[Link] of Python with MySQL - update details

Aim:
Program to connect python and mysql and update the table in mysql through
python.

Source code:
import [Link]
con=[Link](host="localhost",username="root",database="practi
cals",password="123456")
if con.is_connected():
print("Database connection Successful!")
cur=[Link]()
[Link]("Select * from empl")
dat1=[Link]()
for i in dat1:
print(i)
[Link]("Select empid,empname,DOJ, Salary*10 from empl")
dat2=[Link]()
print("\nAfter incrementation of salary:")
for x in dat2:
print(x)
[Link]()

Result:
The program to connect python and mysql and update the table in mysql through
python was successfully executed and the output was verified.

40
Output:
#Calories > 120:

#Desc order of calories:

#Increasing price by 10%:

#Price range( 12 <= price && price <= 18 ):

41
18. Displaying Data from Table Using SQL Queries

Aim:
To create a table SOFT DRINKS and write queries for given conditions and
execute it.

i)To display names and drink codes of those drinks that have more than 120
calories.
ii)To display drink codes, names and calories of all drinks, in descending
order of calories.
iii)To display names and price of drinks that have price in the range 12 to 18
(both 12 and 18)
iv)Increase the price of all drinks in the given table by 10%

Source code:
1. Select * from SOFTDRINKS where CALORIES>120;
2. select DRINKCODE,DNAME,CALORIES from SOFTDRINKS order by
CALORIES desc;
3. select DNAME,PRICE from SOFTDRINKS where 12<=price &&
price<=18;
4. select DRINKCODE,DNAME,PRICE+PRICE*0.1,CALORIES from
SOFTDRINKS;

Result:
The program to create a table SOFT DRINK and execution of given queries was
successfully executed and the output was verified.

42
Output:

43
19. Integration of Python with MySQL to Search the Employee Details

Aim:
To connect python and Mysql and search the employee details.

Source code:
import [Link]
con=[Link](host="localhost",username="root",database="practi
cals",password="123456")
if con.is_connected():
print("Database connection Successful!")
cur=[Link]()
i=input("Enter your employee id to search the record:")
check="select empid,empname,empaddress,DOJ,Salary from empl where
empid=%s"
[Link](check,(i,))
d=[Link]()
if d:
i,n,a,da,s=d
print("Empid:",i)
print("Name:",n)
print("Residence:",a)
print("Salary",s)
print("DOJ:",da)
else:
print("Employee not found")

Result:
The program to connect python and Mysql and search the employee details was
successfully executed and the output was verified.

44
Output:
School

Admin

45
20. Displaying Data from Table Using SQL Queries

Aim:
To execute queries with respect to table SCHOOL and ADMIN

Source code:
1. Select Designation,Count (*) From Admin Group By Designation Having Count
(*) <2;
2. Select max(Experience) from school;
3. Select Teacher from school where experience>12 order by teacher;
4. Select count(*),Gender from admin group by Gender;

Result:
The program to execute queries with respect to table SCHOOL and ADMIN was
successfully executed and the output was verified.

46

You might also like