Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
102 views

Program Python by Shailesh

The programs demonstrate various Python programming concepts like: 1) Taking user input, performing arithmetic operations and printing results 2) Checking if a number is perfect, Armstrong or factorial 3) Generating Fibonacci series, checking palindromes, and defining functions 4) Reading and writing to files, searching and replacing text, binary search 5) Implementing stacks and finding most frequent words in text The programs cover basic to intermediate Python programming concepts through small examples and exercises.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
102 views

Program Python by Shailesh

The programs demonstrate various Python programming concepts like: 1) Taking user input, performing arithmetic operations and printing results 2) Checking if a number is perfect, Armstrong or factorial 3) Generating Fibonacci series, checking palindromes, and defining functions 4) Reading and writing to files, searching and replacing text, binary search 5) Implementing stacks and finding most frequent words in text The programs cover basic to intermediate Python programming concepts through small examples and exercises.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 48

Program 1

1.Program to enter two numbers and print the


arithmetic operations like +,-,*, /, // and %.
Solution:
#Input first number
num1 = int(input("Enter first number: "))
#Input Second number
num2 = int(input("Enter second number: "))
#Printing the result for all arithmetic operations
print("Results:-")
print("Addition: ",num1+num2)
print("Subtraction: ",num1-num2)
print("Multiplication: ",num1*num2)
print("Division: ",num1/num2)
print("Modulus: ", num1%num2)
print("Floor Division: ",num1//num2)
print("Exponentiation: ",num1 ** num2)
OUTPUT:
Enter first number: 8
Enter second number: 3
Results:-
Addition: 11
Subtraction: 5
Multiplication: 24
Division: 2.6666666666666665
Modulus: 2
Floor Division: 2
Exponentiation: 512
PROGRAM:2

Program 2: Write a program to find whether an inputted


number is perfect or not.

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


sum1 = 0
for i in range(1, n):
if(n % i == 0):
sum1 = sum1 + i
if (sum1 == n):
print("The number is a Perfect number!")
else:
print("The number is not a Perfect number!")
Output :
Case 1:
Enter any number: 6
The number is a Perfect number!

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

# take input from the user


num = int(input("Enter a number: "))
# initialize sum
sum = 0
# find the sum of the cube of each digit
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp //= 10
# display the result
if num == sum:
print(num,"is an Armstrong number")
else:
print(num,"is not an Armstrong number")

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.

# change the value for a different result

num = 7
# To take input from the user
#num = int(input("Enter a number: "))

factorial = 1

# check if the number is negative, positive or zero


if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)

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.

nterms = int(input("How many terms? "))


# first two terms
n1, n2 = 0, 1
count = 0
# check if the number of terms is valid
if nterms <= 0:
print("Please enter a positive integer")
# if there is only one term, return n1
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
# generate fibonacci sequence
else:
print("Fibonacci sequence:")
while count < nterms:
print(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1

OUTPUT:
How many terms? 7
Fibonacci sequence:
0

8
PROGRAM:6

6 .Write a Program to enter the string and to check if


it’s palindrome or not using loop.

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:

The string is a palindrome.


PROGRAM:7
7 .Write a program that generates a series using
a function while takes first and last values of the
series and then generates four terms that are
equidistant e.g., if two number passed are 1 and
7 then function returns 1 3 5 7

def ser( a , b ) :
d = int ( ( b - a ) / 3 )
print("Series = " , a , a + d , a + 2*d , b )

first = int(input("Enter first Term = "))


last = int(input("Enter last Term = "))

ser(first , last )
OUTPUT:
Enter first Term = 1
Enter last Term = 7
Series = 1 3 5 7

Enter first Term = 7


Enter last Term = 1
Series = 7 5 3 1

Enter first Term = 2


Enter last Term = 8
Series = 2 4 6 8

Enter first Term = 100


Enter last Term = 60
Series = 100 87 74 60

PROGRAM:8
8. Read a file line by line and print it.

with open("data_file.txt") as f:
content_list = f.readlines()

# print the list


print(content_list)

# remove new line characters


content_list = [x.strip() for x in content_list]
print(content_list)

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 = open("Answer.txt", "r")


newfile = open("nswer.txt", "w")
line = ""
while line:
line = myfile.readline()
if 'a' not in line:
newfile.write(line)

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.

Connected to MySQL Server version 5.7.19


You're connected to database: ('electronics',)
MySQL connection is closed

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.

# Stack implementation in python


# Creating a stack
def create_stack():
stack = []
return stack
# Creating an empty stack
def check_empty(stack):
return len(stack) ==
# Adding items into the stack
def push(stack, item):
stack.append(item)
print("pushed item: " + item
# Removing an element from the stack
def pop(stack):
if (check_empty(stack)):
return "stack is empty
return stack.pop()
stack = create_stack()
push(stack, str(1))
push(stack, str(2))
push(stack, str(3))
push(stack, str(4))
print("popped item: " + pop(stack)) print("stack after popping
an element: " + str(stack))

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

You might also like