1-Python Program to shift Numbers
Example :
let a list contains = [-2, 1, -3, -15, 16, -17, 5, -3, -6]
after processing the list should look like this
[1, 16, 5, -6, -3, -17, -15, -3, -2]
list1 = [-2, 1, -3, -15, 16, -17, 5, -3, -6]
list2 = []
n = len(list1)
for x in range(n):
if list1[x] > 0:
list2.append(list1[x])
for x in range(n-1, -1, -1):
if(list1[x]) < 0:
list2.append(list1[x])
print(list2)
Output
[1, 16, 5, -6, -3, -17, -15, -3, -2]
2-EMI Calculator using Python
# program to find out EMI using formula
# EMI = (p*r(1+r)**t)/((1+r)**t-1)
from math import pow
def emi_calculate(p, r, t):
r = r/(12*100) # rate for one month
t = t*12 # one month time
emi = (p*r*pow(1+r, t))/(pow(1+r, t)-1)
return emi
p = int(input('Enter pricipal amount :'))
r = int(input('Enter rate of interest :'))
t = int(input('Enter time in years :'))
emi = emi_calculate(p, r, t)
print('Monthly Installment :%.2f' % emi)
Enter pricipal amount :1250000
Enter rate of interest :9
Enter time in years :10
Monthly Instalment : 15834.47
3-GCD using Looping method
# Program to find out GCD of two number using iterative
method
a = int(input('Enter any number'))
b = int(input('Enter another number'))
if(a > b):
number = a
divider = b
else:
number = b
divider = a
rem = a % b
While (rem! = 0):
a = b
b = rem
rem = a % b
print('Your GCD is :', b)
Output
Enter any number8
Enter another number24
Your GCD is : 8
4-Python recursion Function to find out GCD
def gcd(a, b):
if(b == 0):
return a
else:
return gcd(b, a % b)
a = int(input('Enter first number '))
b = int(input('Enter second number '))
result = gcd(a, b)
print('GCD of {} and {} is {}'.format(a, b, result))
5-Binary Search
x =[1,2,3,5,7,8,9,10,12,14,15,18,20,22]
data = 10
found =0
first=0
last =13
while (first<=last and found ==0):
mid = int((first+last)/2)
if(x[mid]==data):
found =1
if(x[mid]data):
last = mid-1
if(found ==0):
print("Data not found")
else:
print("Data found")
6-Binary Search Using Recursion
def binarySearch (arr, l, r, x):
if r >= l:
mid = (l + (r - l))//2
if arr[mid] == x:
return mid
elif arr[mid] > x:
return binarySearch(arr, l, mid-1, x)
else:
return binarySearch(arr, mid+1, r, x)
else:
return -1
li = [1,2,3,4,5,6,7,8,9,10]
result = binarySearch(li,9,len(li),6)
if(result!=-1):
print('Data found at index :',result)
else:
print(' Data not found')
7-Recursive function to find out the sum of list elements
# program to find out sum of element of a list using
recursion
def sum_element(l):
if(len(l) == 1):
return l[0]
else:
value = l.pop()
return value+sum_element(l)
list1 = [1, 2, 34, 5, 6]
result = sum_element(list1)
print('sum of element :', result)
8-The Fibonacci number using Looping
a = 0
b = 1
for i in range(1, 20):
if i == 1:
print(a, end=" ")
if i == 2:
print(b, end=" ")
if i > 2:
c = a+b
print(c, end=" ")
a = b
b = c
9-The Fibonacci number using recursion
# User defined recursive function to find out nth
fibonacci number
# and its implementation in a python program
def fab(n):
if(n == 1):
return 0
elif(n == 2):
return 1
else:
return fab(n-1)+fab(n-2)
if __name__ == "__main__":
for x in range(1, 21):
print(fab(x), end=" ")
10-Factorial of Number N using Loopin
# program to find out factorial of any number n using
looping method
n = int(input('Enter any number n: '))
fact = 1
for i in range(1, n+1):
fact =fact* i
print('Factorial of {} is {}'.format(n, fact))
11-Factorial of Number N using recursion
def factorial(n):
if n==1:
return 1
else:
return n*(factorial(n-1))
#function call
n = int(input("Enter any number "))
result = factorial(n)
print("factorial of {} is {} ".format(n,result))
12-character Rhombus In Python
nm=input("Your String is here ...")
x=len(nm)
""" Steps to print first part of rombus"""
for i in range(0,len(nm)):
for j in range(len(nm)-i,0,-1):
print(" ",end=" ")
for k in range(0,i+1):
print(nm[k]," ",end=" ")
print()
""" steps to print bottom of rhombus"""
for i in range(0,len(nm)):
for j in range(-2,i):
print(" ",end=" ")
for k in range(0,len(nm)-i-1):
print(nm[k]," ",end=" ")
print()
13-Python Program to Draw Line Chart
# program to print scatter graph on the screen
import matplotlib.pyplot as plt
import numpy as np
x = ['Delhi', 'Banglore', 'Chennai', 'Pune']
y = [250, 300, 260, 400]
plt.xlabel('City')
plt.ylabel('Sales in Million')
plt.title('Sales Recorded in Major Cities')
plt.plot(x, y)
plt.show()
Output
14-Python Program to draw Bar chart
# program to print bar graph on the screen
import matplotlib.pyplot as plt
x = ['Delhi', 'Banglore', 'Chennai', 'Pune']
y = [250, 300, 260, 400]
plt.xlabel('City')
plt.ylabel('Sales in Million')
plt.title('Sales Recorded in Major Cities')
plt.bar(x, y)
plt.show()
Output
15-Insert Record In MySQL Using Python
import MySQLdb
data = MySQLdb.connect("localhost", "root", "",
"binarynote")
cursor = data.cursor()
uname = input("Enter your user ID :")
upass = input("Enter your Password :")
Name = input(“Enter your username :”)
Password = input (“Enter your password :”)
Sql = “insert into user(uname, upass) value (‘”. Uname.
“’,’”. Upass .”’);”;
sql = "insert into user(uname,upass)
values('{}','{}');".format(uname, upass)
cursor.execute(sql)
data.close()
print("Record Added................")
16-Python Program to delete a record from MySQL Table
import MySQLdb
db = MySQLdb.connect(“localhost”,”root”,””,”cable”)
cursor = db.cursor()
name = input(“Enter any name : “)
sql =”delete from customer where name like ‘%” + name + “‘;”
cursor.execute(sql)
db.commit()
db.close()
print(“Row deleted successfully”)
17-Python Program to Update a record in MySQL Table
import MySQLdb
db = MySQLdb.connect("localhost", "root", "", "binarynote")
cursor = db.cursor()
name = input("Enter current name : ")
new_name = input("Enter new name :")
sql = "update user set uname={} where name like
'%{}';".format(name, new_name)
cursor.execute(sql)
db.commit()
db.close()
print("Row deleted successfully")
Display Records from MySQL Table Using Python
18-Single Word output
import MySQLdb
# Open database connection
db = MySQLdb.connect("localhost", "root", "", "binarynote")
cursor = db.cursor()
sql = "select count(*) from question"
cursor.execute(sql)
result = cursor.fetchone()
print(result[0])
db.close()
19-Single Row Output
import MySQLdb
from prettytable import PrettyTable
# Open database connection
db = MySQLdb.connect("localhost", "root", "", "binarynote")
cursor = db.cursor()
sql = "select * from question where qid=10"
cursor.execute(sql)
results = cursor.fetchall()
t = PrettyTable(['ID', 'Question', 'A', 'B', 'C', 'D',
'Ans', 'Exp', 'gid', 'sid', 'tid'])
for idr, question, a, b, c, d, ans, exp, gid, sid, tid in
results:
t.add_row([idr, question, a, b, c, d, ans, exp, gid,
sid, tid])
print(t)
db.close()
20-Display MultiRow records
import MySQLdb
from prettytable import PrettyTable
# Open database connection
db = MySQLdb.connect("localhost", "root", "", "binarynote")
cursor = db.cursor()
sql = "select * from question"
cursor.execute(sql)
results = cursor.fetchall()
t = PrettyTable(['ID', 'Question', 'A', 'B', 'C', 'D',
'Ans', 'Exp', 'gid', 'sid', 'tid'])
for idr, question, a, b, c, d, ans, exp, gid, sid, tid in
results:
t.add_row([idr, question, a, b, c, d, ans, exp, gid,
sid, tid])
# print(idr,name,fname,add,phone,email)
print(t)
db.close()
21-Reading Data from Text File
file = open("abcd.txt")
data1 = file.read()
print(data1)
file.close()
Program to find out the total number of words in any given test file
file = open(r"abcd.txt")
words = lines = 0
for line in file.readlines():
lines += 1
words += len(line.split())
file.close()
print("Total Words in this File :", words)
print("Total Lines in this File :", lines)
22-Program to find out total number of lines that start with alphabet
‘A’
file = open(r"abcd.txt",'r')
count=0;
for line in file.readlines():
if line[0]=='A':
count+=1
file.close()
print("Total lines that start with alphabet 'A' :",count)
23-Python program to search a word in a text File
word = input('Enter any word that you want to find in text
File :')
word1= '"'+word+'"'
word2= "'"+word+"'"
f = open("rakesh.txt","r")
data = f.read().split()
if word in data or word1 in data or word2 in data:
print('Word Found in Text File')
else:
print('Word not found in Text File')
24-Python program to search a word in a text File
word = input('Enter any word that you want to find in text
File :')
f = open("rakesh.txt","r")
if word in f.read().split():
print('Word Found in Text File')
else:
print('Word not found in Text File')
25-Program to create Text File using Python
file = open("Testing.txt","w")
file.write("This is rakesh and this is my first file
handling program in Python \n")
file.write("This is second line and i am learning new things
in pythin")
file.writelines("third line of the same program")
file.close()
print("File Generated please check")
26-Program to create Text File using Python
file = open("Testing.txt","a")
file.write("This is rakesh and this is my first file
handling program in Python \n")
file.write("This is second line and i am learning new things
in pythin")
file.writelines("third line of the same program")
file.close()
print("File updated please check")
27-Program to create a list of n numbers from keyboard and create a
frequency table for all unique number
numbers = []
n = int(input('Enter value of n :'))
for i in range(n):
x = int(input('Enter any number :'))
numbers.append(x)
unique = []
frequency = []
for a in numbers:
if a not in unique:
unique.append(a)
count = numbers.count(a)
frequency.append(count)
# print unique numbers and frequency table
print('Unique Number\t\t Frequency')
for i in range(len(unique)):
print(unique[i], frequency[i], sep='\t\t')
28-Selection sort Python Program
x =[3,56,2,56,78,56,34,23,4,78,8,123,45]
for i in range(0,len(x)-1):
pos = i
low = x[pos]
for j in range(i+1,len(x)):
if(low>x[j]):
pos = j
low = x[j]
x[i],x[pos] = x[pos],x[i]
print("Sorted Array :")
print(x)
29-Connect Python with MySQL server
#Database connectivity mysql
import MySQLdb
# Open database connection
db = MySQLdb.connect("localhost", "root", "", "cable" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# execute SQL query using execute() method.
cursor.execute("SELECT VERSION()")
# Fetch a single row using fetchone() method.
data = cursor.fetchone()
print("Database version : %s " % data )
# disconnect from server
db.close()
30-Python program to check whether the entered string is palindrome
or not
word = input('Enter any word :')
l = len(word)
found =0
for i in range(0,l//2):
if(word[i]!=word[l-1-i]):
found=1
if(found ==1):
print("not a palindrom")
else:
print("Its a palindrome")
Or
word=input("Please enter a word")
revs=word[::-1]
if word == revs:
print("This word is a palindrome")
else:
print("This word is not a palindrome")
31-Hangman Game (is a letter guessing game)
import random as r
# steps to select a random word from sowpods.txt file
with open("sowpods.txt") as file:
data = file.read().split()
number = r.randint(0, len(data))
word = data[number]
# create a list of underscore -
# it contains exactly same number of underscore as the
length of our random word
lines = []
for i in word:
lines.append('_')
# counter variable is used to track number of wrong
letters.
# a user can make If it is 6 then terminate the program
and print message
counter = 0
while True:
letter = input('\nGuess your letter :')
if letter in word:
for i in range(0, len(word)):
if word[i] == letter:
lines[i] = letter
else: # letter is not in the word
counter += 1
# print the word with inserted letters
for i in lines:
print(i, end=" ")
# check letters remained in the list
cnt = "".join(lines).count('_')
if cnt == 0 or counter == 6:
break
# end of while loop
if counter >= 6:
print("\n\n\n You looser..............Think properly")
else:
print("\n\n\n Yes!!!!!!!!!!! You WON this match")