Program Python by Shailesh
Program Python by Shailesh
Case 2:
Enter any number: 25
The number is not a Perfect number!
PROGRAM:3
3 : Python program to check if the number is an
Armstrong number or not
Output:1
Enter a number: 663
663 is not an Armstrong number
Output:2
Enter a number: 407
407 is an Armstrong number
PROGRAM :4
4 . Python program to find the factorial of a
number.
num = 7
# To take input from the user
#num = int(input("Enter a number: "))
factorial = 1
OUTPUT:
The factorial of 7 is 5040
PROGRAM:5
5. Write a Program to enter the number of terms and
to print the Fibonacci Series.
OUTPUT:
How many terms? 7
Fibonacci sequence:
0
8
PROGRAM:6
my_str = 'aIbohPhoBiA'
# make it suitable for caseless comparison
my_str = my_str.casefold()
# reverse the string
rev_str = reversed(my_str)
# check if the string is equal to its reverse
if list(my_str) == list(rev_str):
print("The string is a palindrome.")
else:
print("The string is not a palindrome.")
OUTPUT:
def ser( a , b ) :
d = int ( ( b - a ) / 3 )
print("Series = " , a , a + d , a + 2*d , b )
ser(first , last )
OUTPUT:
Enter first Term = 1
Enter last Term = 7
Series = 1 3 5 7
PROGRAM:8
8. Read a file line by line and print it.
with open("data_file.txt") as f:
content_list = f.readlines()
Output:
['honda 1948\n', 'mercedes 1926\n', 'ford 1903']
['honda 1948', 'mercedes 1926', 'ford 1903']
PROGRAM :9
9.Remove all the lines that contain the
character “a” in a file and write it into another
file
myfile.close()
newfile.close()
print("Newly created file contains")
print("------------")
newfile = open("nswer.txt","r")
line = ""
while line:
line = newfile.readline()
print(line)
newfile.close()
PROGRAM: 10
10: Read a text file and display the number of
vowels/consonants/uppercase/lowercase
characters in the file.
def counting(filename):
# Opening the file in read mode
txt_file = open(filename, "r")
# Initialize three variables to count number of
vowels,
# lines and characters respectively
vowel = 0
line = 0
character = 0
# Make a vowels list so that we can
# check whether the character is vowel or not
vowels_list = ['a', 'e', 'i', 'o', 'u',
'A', 'E', 'I', 'O', 'U']
# Iterate over the characters present in file
for alpha in txt_file.read():
# Checking if the current character is vowel or not
if alpha in vowels_list:
vowel += 1
# Checking if the current character is
# not vowel or new line character
elif alpha not in vowels_list and alpha != "\n":
character += 1
# Checking if the current character
# is new line character or not
elif alpha == "\n":
line += 1
# Print the desired output on the console.
print("Number of vowels in ", filename, " = ", vowel)
print("New Lines in ", filename, " = ", line)
print("Number of characters in ", filename, " = ",
character)
# Calling the function counting which gives the desired
output
counting('Myfile.txt')
OUTPUT:
Number of vowels in MyFile.txt = 23
New Lines in MyFile.txt = 2
Number of characters in MyFile.txt = 54
PROGRAM:11
11. Create a binary file with name and roll no.
Search for a given roll number and display the
name, if not found display appropriate
message.
import pickle
student=[]
f=open('student.dat','wb')
ans='y'
while ans.lower()=='y':
roll = int(input("Enter Roll Number :"))
name = input("Enter Name :")
student.append([roll,name])
ans=input("Add More ?(Y)")
pickle.dump(student,f)
f.close()
f=open('student.dat','rb')
student=[]
while True:
try:
student = pickle.load(f)
except EOFError:
break
ans='y'
while ans.lower()=='y':
found=False
r = int(input("Enter Roll number to search :"))for s in student:
if s[0]==r:
print("## Name is :",s[1], " ##") found=True
break
if not found:
print("####Sorry! Roll number not found ####")
ans=input("Search more ?(Y) :")
f.close()
OUTPUT:
Enter Roll Number :1
Enter Name :Amit
Add More ?(Y)y
Enter Roll Number :2
Enter Name :Jasbir
Add More ?(Y)y
Enter Roll Number :3
Enter Name :Vikral
Add More ?(Y)n
Enter Roll number to search :2
## Name is : Jasbir ##
Search more ?(Y) :y
Enter Roll number to search :1
##Name is : Amit ##
Search more ?(Y) :y
Enter Roll number to search :4
####Sorry! Roll number not found ####
Search more ?(Y) :n
PROGRAM:12
12. Write a random number generator that
generates random numbers between 1 and
6(simulates a dice).
import random
min = 1
max = 6
roll_again = "y"
while roll_again == "y" or roll_again == "Y":
print("Rolling the dice...")
val = random.randint (min, max)
print("You get... :", val)
roll_again = input("Roll the dice again? (y/n)...")
OUTPUT:
Rolling the dice...
You get... : 3
Roll the dice again? (y/n)...y
Rolling the dice...
You get... : 1
Roll the dice again? (y/n)...n
PROGRAM:13
13. Write a python program to implement a
stack using a list data structure.
stack = []
#Function to print top element of stack
def top(stack):
if stack != []:
print(stack[-1] + " is top element")
else:
print("Stack Empty!!!")
#Function to print size of stack
def size(stack):
print("Size of stack is " + str(len(stack)))
#Function to check if a stack is empty
def empty(stack):
if stack == []:
print("True")
else:
print("False")
# append() function is used to push element in the stack
stack.append('a')
stack.append('b')
stack.append('c')
size(stack)
print(stack)
top(stack)
# pop() function to pop element from stack in LIFO order
print(stack.pop() + " is popped")
print(stack)
empty(stack)
print(stack.pop() + " is popped")
print(stack.pop() + " is popped")
print(stack)
empty(stack)
Output:
Size of stack is 3
['a', 'b', 'c']
c is top element
c is popped
['a', 'b']
False
b is popped
a is popped
[] True
PROGRAM:14
14. Take a sample of ten phishing e-mails (or
any text file) and find most commonly
occurring words.
file = open("gfg.txt","r")
frequent_word = ""
frequency = 0
words = []
line_word = line.lower().replace(',','').replace('.','').split("
");
for w in line_word:
words.append(w);
for i in range(0, len(words)):
count = 1;
for j in range(i+1, len(words)):
if(words[i] == words[j]):
count = count + 1;
if(count > frequency):
frequency = count;
frequent_word = words[i];
print("Most repeated word: " + frequent_word)
print("Frequency: " + str(frequency))
file.close();
Output:
Most repeated word: well
Frequency: 3
PROGRAM:15
15. Read a text file line by line and display
each word separated by a #.
def word_sep_by_hash():
fobj=open(“myfile.txt”,”r”)
lns=fobj.readlines()
for l in lns:
wds=l.split()
for w in wds:
print(w+”#”,end=””)
print(“”)
fobj.close()
n=int(input(“Lines in text file:”))
f=open(“myfile.txt”,”w”)
for i in range(n):
print(“Enter”,i+1,”line:”,end=” “)
val=input()
f.write(val)
f.write(“\n”)
f.close()
word_sep_by_hash()
OUTPUT:
PROGRAM:16
16. Create a student table and insert data.
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
#Switched to a
database
mysql> USE GVKCV;
Database changed
#Creating table student
mysql> create table student
-> (ROLLNO INT NOT NULL PRIMARY KEY,
-> NAME CHAR(10),
-> TELUGU CHAR(10),
-> HINDI CHAR(10),
-> MATHS CHAR(10));
Query OK, 0 rows affected (1.38 sec)
#Inserting values into table
mysql> insert into student
-> values(101,"student1",50,51,52),
-> (102,"student2",60,61,62),
-> (103,"student3",70,71,72),
-> (104,"student4",80,81,82),
-> (105,"student5",90,91,92),
-> (106,"student6",40,41,42),
-> (107,"student7",63,64,65);
Query OK, 7 rows affected (0.24 sec)
Records: 7 Duplicates: 0 Warnings: 0
#Adding new attribute computers
mysql> alter table student
-> add (computers char(10));
Query OK, 0 rows affected (1.13 sec)
Records: 0 Duplicates: 0 Warnings: 0
#Describing table
mysql> desc student;
+-----------+----------+------+-----+---------+-------
+
| Field | Type | Null | Key | Default | Extra
|
+-----------+----------+------+-----+---------+-------
+
| ROLLNO | int | NO | PRI | NULL |
|
| NAME | char(10) | YES | | NULL |
|
| TELUGU | char(10) | YES | | NULL |
|
| HINDI | char(10) | YES | | NULL |
|
| MATHS | char(10) | YES | | NULL |
|
| computers | char(10) | YES | | NULL |
|
+-----------+----------+------+-----+---------+-------
+
6 rows in set (0.21 sec)
#Modifying the datatype
mysql> alter table student
-> modify column computers varchar(10);
Query OK, 7 rows affected (2.38 sec)
Records: 7 Duplicates: 0 Warnings: 0
mysql> desc student;
+-----------+-------------+------+-----+---------
+-------+
| Field | Type | Null | Key | Default |
Extra |
+-----------+-------------+------+-----+---------
+-------+
| ROLLNO | int | NO | PRI | NULL |
|
| NAME | char(10) | YES | | NULL |
|
| TELUGU | char(10) | YES | | NULL |
|
| HINDI | char(10) | YES | | NULL |
|
| MATHS | char(10) | YES | | NULL |
|
| computers | varchar(10) | YES | | NULL |
|
+-----------+-------------+------+-----+---------
+-------+
6 rows in set (0.11 sec)
#Droping a attribute
mysql> alter table student
-> drop column computers;
Query OK, 0 rows affected (0.93 sec)
Records: 0 Duplicates: 0 Warnings: 0
#Describing table
mysql> desc student;
+--------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+----------+------+-----+---------+-------+
| ROLLNO | int | NO | PRI | NULL | |
| NAME | char(10) | YES | | NULL | |
| TELUGU | char(10) | YES | | NULL | |
| HINDI | char(10) | YES | | NULL | |
| MATHS | char(10) | YES | | NULL | |
+--------+----------+------+-----+---------+-------+
5 rows in set (0.14 sec)
#UPDATE DATA TO MODIFY DATA
#ACTUAL DATA
mysql> select *from student;
+--------+----------+--------+-------+-------+
| ROLLNO | NAME | TELUGU | HINDI | MATHS |
+--------+----------+--------+-------+-------+
| 101 | student1 | 50 | 51 | 52 |
| 102 | student2 | 60 | 61 | 62 |
| 103 | student3 | 70 | 71 | 72 |
| 104 | student4 | 80 | 81 | 82 |
| 105 | student5 | 90 | 91 | 92 |
| 106 | student6 | 40 | 41 | 42 |
| 107 | student7 | 63 | 64 | 65 |
+--------+----------+--------+-------+-------+
7 rows in set (0.00 sec)
#UPDATE THE MARKS FOR ATTRIBUTE TELUGU FOR THE
STUDENT101
mysql> UPDATE STUDENT
-> SET TELUGU=99
-> WHERE ROLLNO=101;
Query OK, 1 row affected (0.12 sec)
Rows matched: 1 Changed: 1 Warnings: 0
#DATA IN THE TABLE AFTER UPDATING
mysql> SELECT *FROM STUDENT;
+--------+----------+--------+-------+-------+
| ROLLNO | NAME | TELUGU | HINDI | MATHS |
+--------+----------+--------+-------+-------+
| 101 | student1 | 99 | 51 | 52 |
| 102 | student2 | 60 | 61 | 62 |
| 103 | student3 | 70 | 71 | 72 |
| 104 | student4 | 80 | 81 | 82 |
| 105 | student5 | 90 | 91 | 92 |
| 106 | student6 | 40 | 41 | 42 |
| 107 | student7 | 63 | 64 | 65 |
+--------+----------+--------+-------+-------+
7 rows in set (0.00 sec)
#ORDER BY DESCENDING ORDER
mysql> SELECT *FROM STUDENT
-> ORDER BY HINDI DESC;
+--------+----------+--------+-------+-------+
| ROLLNO | NAME | TELUGU | HINDI | MATHS |
+--------+----------+--------+-------+-------+
| 105 | student5 | 90 | 91 | 92 |
| 104 | student4 | 80 | 81 | 82 |
| 103 | student3 | 70 | 71 | 72 |
| 107 | student7 | 63 | 64 | 65 |
| 102 | student2 | 60 | 61 | 62 |
| 101 | student1 | 99 | 51 | 52 |
| 106 | student6 | 40 | 41 | 42 |
+--------+----------+--------+-------+-------+
7 rows in set (0.05 sec)
#ORDER BY ASCENDING ORDER
mysql> SELECT *FROM STUDENT
-> ORDER BY HINDI ASC;
+--------+----------+--------+-------+-------+
| ROLLNO | NAME | TELUGU | HINDI | MATHS |
+--------+----------+--------+-------+-------+
| 106 | student6 | 40 | 41 | 42 |
| 101 | student1 | 99 | 51 | 52 |
| 102 | student2 | 60 | 61 | 62 |
| 107 | student7 | 63 | 64 | 65 |
| 103 | student3 | 70 | 71 | 72 |
| 104 | student4 | 80 | 81 | 82 |
| 105 | student5 | 90 | 91 | 92 |
+--------+----------+--------+-------+-------+
7 rows in set (0.00 sec)
#DELETING A TUPLE FROM THE TABLE
mysql> DELETE FROM STUDENT
-> WHERE ROLLNO=101;
Query OK, 1 row affected (0.14 sec)
mysql> SELECT *FROM STUDENT;
+--------+----------+--------+-------+-------+
| ROLLNO | NAME | TELUGU | HINDI | MATHS |
+--------+----------+--------+-------+-------+
| 102 | student2 | 60 | 61 | 62 |
| 103 | student3 | 70 | 71 | 72 |
| 104 | student4 | 80 | 81 | 82 |
| 105 | student5 | 90 | 91 | 92 |
| 106 | student6 | 40 | 41 | 42 |
| 107 | student7 | 63 | 64 | 65 |
+--------+----------+--------+-------+-------+
6 rows in set (0.06 sec)
#ORDER BY BRANCH
#ACTUAL DATA
mysql> SELECT *FROM STUDENT;
+--------+--------+----------+--------+-------+-------
+
| ROLLNO | BRANCH | NAME | TELUGU | HINDI | MATHS
|
+--------+--------+----------+--------+-------+-------
+
| 102 | MPC | student2 | 60 | 61 | 62
|
| 103 | BIPC | student3 | 70 | 71 | 72
|
| 104 | BIPC | student4 | 80 | 81 | 82
|
| 105 | BIPC | student5 | 90 | 91 | 92
|
| 106 | BIPC | student6 | 40 | 41 | 42
|
| 107 | MPC | student7 | 63 | 64 | 65
|
+--------+--------+----------+--------+-------+-------
+
6 rows in set (0.00 sec)
mysql> SELECT BRANCH,COUNT(*)
-> FROM STUDENT
-> GROUP BY BRANCH;
+--------+----------+
| BRANCH | COUNT(*) |
+--------+----------+
| MPC | 2 |
| BIPC | 4 |
+--------+----------+
2 rows in set (0.01 sec)
#e min, max, sum, count and average
mysql> SELECT MIN(TELUGU) "TELUGU MIN MARKS"
-> FROM STUDENT;
+------------------+
| TELUGU MIN MARKS |
+------------------+
| 40 |
+------------------+
1 row in set (0.00 sec)
mysql> SELECT MAX(TELUGU) "TELUGU MAX MARKS"
-> FROM STUDENT;
+------------------+
| TELUGU MAX MARKS |
+------------------+
| 90 |
+------------------+
1 row in set (0.00 sec)
mysql> SELECT SUM(TELUGU) "TELUGU TOTAL MARKS"
-> FROM STUDENT;
+--------------------+
| TELUGU TOTAL MARKS |
+--------------------+
| 403 |
+--------------------+
1 row in set (0.00 sec)
mysql> SELECT COUNT(ROLLNO)
-> FROM STUDENT;
+---------------+
| COUNT(ROLLNO) |
+---------------+
| 6 |
+---------------+
1 row in set (0.01 sec)
mysql> SELECT AVG(TELUGU) "TELUGU AVG MARKS"
-> FROM STUDENT;
+-------------------+
| TELUGU AVG MARKS |
+-------------------+
| 67.16666666666667 |
PROGRAM:17
17. Integrate SQL with Python by importing
the MySQL module.
import mysql.connector
from mysql.connector import Error
try:
connection =
mysql.connector.connect(host='localhost',
database='Electronics',
user='pynative',
password='pynative@#29')
if connection.is_connected():
db_Info = connection.get_server_info()
print("Connected to MySQL Server version ",
db_Info)
cursor = connection.cursor()
cursor.execute("select database();")
record = cursor.fetchone()
print("You're connected to database: ", record)
except Error as e:
print("Error while connecting to MySQL", e)
finally:
if connection.is_connected():
cursor.close()
connection.close()
print("MySQL connection is closed")
Output.
PROGRAM:18
.
18 Integrate SQL with Python by importing
the pymysql module.
import pymysql
def mysqlconnect():
# To connect MySQL database
conn = pymysql.connect(
host='localhost',
user='root',
password = "pass",
db='College',
)
cur = conn.cursor()
cur.execute("select @@version")
output = cur.fetchall()
print(output)
# To close the connection
conn.close()
# Driver Code
if __name__ == "__main__" :
mysqlconnect()
OUTPUT:
(('5.7.30-0ubuntu0.18.04.1',),)
PROGRAM:19
19. Write a program in Python to add,
delete and display elements from a queue
using list.
queue = []
queue.append('a')
queue.append('b')
queue.append('c')
print("Initial queue")
print(queue)
print("\nElements dequeued from queue")
print(queue.pop(0))
print(queue.pop(0))
print(queue.pop(0))
print("\nQueue after removing elements")
print(queue)
OUTPUT:
Initial queue
['a', 'b', 'c']
Elements dequeued from queue
a
b
c
Queue after removing elements
[]
PROGRAM:20
20. Write a program in Python to add, delete
and display elements from a queue using list
rite a Python program to implement all basic
operations of a stack, such as adding element
(PUSH operation), removing element (POP
operation) and displaying the stack elements
(Traversal operation) using lists.
PROGRAM:21
21. Write a Program to show MySQL
database connectivity in python.
import mysql.connector
from mysql.connector import Error
try:
connection = mysql.connector.connect(host='localhost',
database='Electronics',
user='pynative',
password='pynative@#29')
if connection.is_connected():
db_Info = connection.get_server_info()
print("Connected to MySQL Server version ", db_Info)
cursor = connection.cursor()
cursor.execute("select database();")
record = cursor.fetchone()
print("You're connected to database: ", record)
except Error as e:
print("Error while connecting to MySQL", e)
finally:
if connection.is_connected():
cursor.close()
connection.close()
print("MySQL connection is closed")
OUTPUT:
Connected to MySQL Server version 5.7.19
You're connected to database: ('electronics',)
MySQL connection is closed