Prince

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 30

Program 1: Program to enter two numbers and print the arithmetic operations like +, -,*, /, // and %.

num1 = int (input ('Enter First number: '))

num2 = int(input('Enter Second number: '))

add = num1 + num2

dif = num1 - num2

mul = num1 * num2

div = num1 / num2

floor_div = num1 // num2

power = num1 ** num2

modulus = num1 % num2

print('Sum of ',num1, 'and',num2, 'is :', add)

print('Difference of ',num1, 'and',num2, 'is :', dif)

print('Product of',num1, 'and',num2, 'is :',mul)

print('Division of ',num1, 'and' 'is :',div)

print('Floor Division of ',num1, 'and',num2, 'is :', floor_div)

print('Exponent of ',num1 ,'and' ,num2 ,'is :',power)

print('Modulus of ',num1, 'and' ,num2, 'is :',modulus)


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!")


Program 3: Write a Program to check if the entered number is Armstrong or not.

no = int (input ("Enter any number to check : "))

no1 = no

sum = 0

while no>0:

ans = no % 10;

sum = sum + (ans * ans * ans)

no = int (no / 10)

if sum == no1:

print ("Armstrong Number")

else:

print ("Not an Armstrong Number")


Program 4: Write a Program to find factorial of the entered number.

num = int(input ("Enter the number for calculating its factorial : "))

fact = 1

i=1

while i<=num:

fact = fact * i

i=i+1

print ("The factorial of ", num, "=", fact)


Program 5: Write a Program to enter the number of terms and to print the Fibonacci Series.

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

n1, n2 = 0, 1

count=0

if nterms <= 0:

print("Please enter a positive integer")

elif nterms == 1:

print ("Fibonacci sequence upto",nterms, ":")

print (n1)

else:

print ("Fibonacci sequence:")

while count < nterms:

print (n1)

nth = n1 + n2

n1 = n2

n2 = nth

count+= 1
Program 6: Write a Program to enter the string and check if it’s palindrome or not using loop.

def isPalindrome (s) :

return s == s[::-1]

s = str(input ("Enter the string data:"))

ans = isPalindrome (s)

if ans:

print ("Yes")

else:

print ("No")
Program 7: Recursively find the factorial of a natural number.

def recur_factorial(n):

if n == 1:

return n

else:

return n*recur_factorial(n-1)

num = int(input("Enter Integer value:"))

if num < 0:

print ("Sorry, factorial does not exist for negative numbers")

elif num == 0:

print ("The factorial of 0 is 1")

else:

print ("The factorial of", num, "is", recur_factorial(num))


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

Assume we have the following file, located in the same folder as Python:

file1 = open('myfile.txt', 'r')

Lines = file1.readlines()

count = 0

for line in Lines:

count += 1

print("Line{}: {}".format(count, line.strip()))


Program 9: Remove all the lines that contain the character "a" in a file and write it into another file.

Assume we have the following file, located in the same folder as Python:

file1 = open ('myfile.txt')

file2 = open ("myfilenew.txt", "w")

for line in file1:

if "a" in line:

line=line.replace("a", " ")

else:

file2.write(line)

file1.close()

file2.close()
Program 10: Read a text file and display the number of vowels/consonants/uppercase/lowercase
characters in the file.

Actual text file

file1 = open (r"myfile.txt","r")

vowels=0

consonants=0

uppercase=0

lowercase=0

str1 = file1.read()

for i in str1:

if i>= "a" and i<= "z":

lowercase += 1

elif i>= "A" and i<= "Z":

uppercase += 1

for j in str1:

j=j.lower()

if j == "a" or j == "e" or j== "i" or j == "o" or j == "u":

vowels += 1

else:

if j.isalpha():

consonants += 1

print ("lower case count", lowercase)

print ("upper case count", uppercase)

print ("vowels count", vowels)

print ("consonants count", consonants)


Program 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

import sys

dict={}

def write_in_file():

file=open("stud2.dat","ab")

no=int(input("ENTER NO OF STUDENTS: "))

for i in range(no):

print ("Enter details of student ", i+1)

dict["roll"]=int(input("Enter roll number: "))

dict["name"]=input("enter the name: ")

dict["marks"]=int(input("Enter the marks"))

pickle.dump(dict, file)

file.close()

def display():

file=open("stud2.dat", "rb")

try:

while True:

stud=pickle.load(file)

print(stud)

except EOFError:

pass

file.close()

def search():

file=open("stud2.dat", "rb")

r=int(input("enter the roll no to search: "))

found=0

try:

while True:
data=pickle.load(file)

if data["roll"]==r:

print ("The roll no = ",r," record found")

print(data)

found = 1

break

except EOFError:

pass

if found==0:

print("The roll no ",r," record is not found")

file.close()

while True:

print("MENU \n 1-Write in a file \n 2-display ")

print(" 3-search\n 4-exit \n")

ch=int(input("Enter your choice = "))

if ch==1:

write_in_file()

elif ch==2:

display()

elif ch==3:

search()

elif ch==4:

print(" Hari Om")

sys.exit()
Program 12: Write a random number generator that generates random numbers between 1 and
6(simulates a dice).

import random

a=[]

for i in range (7):

a.append(random.randint(1, 6))

print ("Randomised list is", a)


Program 13: Write a python program to implement a stack using a list data structure.

Stack concept:

""" Python code to demonstrate Implementing stack using list """

stack = ["One", "Two", "Three"]

stack.append("Four")

stack.append("Five")

print (“The elements in the stack", stack)

print ("pop 1", stack.pop())

print ("After performing first pop", stack)

print ("pop 2", stack.pop())

print ("After performing second pop", stack)

OUTPUT:

Queue concept:

""" Python code to demonstrate Implementing Queue using list """

queue = ["One", "Two", "Three"]

queue.append("Four")

queue.append("Five")

print("The elements in the stack", queue)

print("pop 1",queue.pop(0))

print("After performing first pop", queue)

print("pop 2",queue.pop(0))

print("After performing second pop", queue)

OUTPUT:
Program 14: Take a sample of ten phishing e-mails (or any text file) and find most commonly
occurring word(s)

from collections import Counter

ph1= ["Robocalls are on the rise. Be wary of any pre-recorded messages you might receive"]

ph2=["our access to your library account is expiring soon due to inactivity. To continue to have
access to the library services account, you must reactivate your account. For this purpose, click the
web address below or copy and paste it into your web browser. A successful login will activate your
account and you will be redirected to your library profile"]

ph3=["We detected unknown IP access on our date base computer system our security requires you
to verify your account for secure security kindly Click Here and verify your account"]

ph4=["Password will expire in 2 days Click Here To Validate E-mail account"]

ph5=["As we prepare to start the 2016 Tax filling season, we have undergone slight changes in the
filling process to make filling for your refund easier and to prevent unnecessary delays."]

ph6=["Hello, You have an important email from the Human Resources Department with regards to
your December 2015 Paycheck"]

ph7=["Your parcel (shipping document) arrived at the post office. Here is your Shipping
Document/Invoice and copy of DHL receipt for your tracking which includes the bill of lading and
DHL tracking number, the new Import/Export policy supplied by DHL Express. Please kindly check the
attached to confirm accordingly if your address is correct, before we submit to our outlet office for
dispatch to your destination"]

ph8=["Your Itunes-ID has been disabled .You've place your account under the risk of termination by
not keeping the correct informations .Please verify your account as soon as possible.Ready to check
?Click here to get back your account."]

ph9=["Hello, Please refer to the vital info I've shared with you using Google Drive. Click
https://www.google.com/drive/docs/file0116 and sign in to view details.."]

ph10=["I recently read your last article and it was very useful in my field of research. I wonder, if
possible, to send me these articles to use in my current research:This email is enclosed in the
Marquette University secure network, hence access it below.Access the documents here
<http://gabrielramon.be/<link removed>,***Ensure your login credentials are correct to avoid
cancellations** Part of the changes include updating our database with your information."]

words1=ph1[0].split()+ph2[0].split()+ph3[0].split()+ph4[0].split()+ph5[0].split()+ph6[0].split()+ph7[0].
split()+ph8[0].split()+ph9[0].split()+ph10[0].split()

stopwords=['to','the','and','or','you','your','with','have','had','has','of','in','our','is','for','it','will']

words=[]

for i in words1:

if i not in stopwords:

words.append(i)
word_counts = Counter(words)

top_five = word_counts.most_common(5)

print(top_five)
Program 15: Read a text file line by line and display each word separated by a #.

#myfile.txt has following data

"""welcome to python class

welcome to CBSE class 12 program 15

School programming"""

fh=open(r"myfile.txt","r")

item=[]

a=""

while True:

a=fh.readline()

words=a.split()

for j in words:

item.append(j)

if a =="":

break

print("#".join(item))
Program 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: Integrate SQL with Python by importing the MySQL module.

import mysql.connector as sqltor

mycon=sqltor.connect(host="localhost",user="root",passwd="tiger",database="gvkcv")

if mycon.is_connected()==False:

print("error connecting to database")

cursor=mycon.cursor()

cursor.execute("select *from student10")

data=cursor.fetchall()

for i in data:

print(i)

mycon.close()
Program 18: Integrate SQL with Python by importing the pymysql module

import pymysql as pym

mycon=sqltor.connect(host="localhost",user="root",passwd="tiger",database="gvkcv")

cursor=mycon.cursor()

cursor.execute("select *from student10")

data=cursor.fetchall()

for i in data:

print(i)

mycon.close()

You might also like