#1.
ASSIGN TWO VARIABLES AND PRINT SUM OF IT
a=10
b=20
c=a+b
print("Sum of A & B is : ",c)
#2.Write a simple Python Program to INPUT two variables and print
Addition, Subtraction, Multiplication and Division of both numbers.
a=int(input("Enter Number 1 : "))
b=int(input("Enter Number 2 : "))
print("Addition is : ",a+b)
print("Subtraction is : ",a-b)
print("Multiplication is : ",a*b)
print("Division is : ",a/b)
#3.Write a Python Program to input 3 numbers and display greater
number.
a=int(input("Enter Number 1 : "))
b=int(input("Enter Number 2 : "))
c=int(input("Enter Number 3 : "))
if(a>b and a>c):
print(a," is greater")
Created By : SANKET B. JETHAVA
elif(b>a and b>c):
print(b," is greater")
elif(c>a and c>b):
print(c," is greater")
else:
print("All are same")
#4.Write a Python Program to input marks of 4 subjects and display
Total, Percentage, Result and Grade. If student is fail (<40) in any
subject then Result should be displayed as “FAIL” and Grade should be
displayed as "With Held**"
m1=int(input("Enter Mark 1 : "))
m2=int(input("Enter Mark 2 : "))
m3=int(input("Enter Mark 3 : "))
m4=int(input("Enter Mark 4 : "))
total=(m1+m2+m3+m4)
per=total/4
if(m1 < 40 or m2 < 40 or m3 < 40 or m4 < 40):
print("Result : Fail")
print("Grade : With Held**")
else:
Created By : SANKET B. JETHAVA
print("Result : Pass")
if(per>=90):
print("Grade : A+")
elif(per>=80 and per<90):
print("Grade : A")
elif(per>=70 and per<80):
print("Grade : B+")
elif(per>=60 and per<70):
print("Grade : B")
elif(per>=50 and per<60):
print("Grade : C")
print("Percentage : ",per)
#5.Write a Python Program to enter 4 digit number and display sum of
all the digits. (You can assume number to be in string format). (Do not
use loop)
a="1234"
b=int(a[0])+int(a[1])+int(a[2])+int(a[3])
print("Sum of 4 digit is : ",b)
Created By : SANKET B. JETHAVA
#Program No. 6
for i in range(1,7):
for j in range(0,i):
print(i,end=" ")
print()
#Program No. 7
for i in range(1,7):
for j in range(0,i):
print(i,end=" ")
print()
#Program No. 8
a=1
for i in range(1,7):
Created By : SANKET B. JETHAVA
for j in range(1,i):
print(a, end=" ")
a=a+1
print()
#Prohram No. 9
a=1
for i in range(1,7):
for j in range(1,i):
if(a%2==0):
print("0", end=" ")
else:
print("1",end=" ")
a=a+1
print()
#Program No. 10
a=['A','B','C','D','E']
for i in range(1,7):
for j in range(0,i-1):
print(a[j],end=" ")
Created By : SANKET B. JETHAVA
print()
#11
n=5
# number of spaces
k = 2*n - 2
# outer loop to handle number of rows
for i in range(0, n):
# inner loop to handle number spaces
# values changing acc. to requirement
for j in range(0, k):
print(end=" ")
# decrementing k after each loop
k=k-1
# inner loop to handle number of columns
# values changing acc. to outer loop
Created By : SANKET B. JETHAVA
for j in range(0, i+1):
# printing stars
print("* ", end="")
# ending line after each row
print("\r")
#15.Write a program to input a number and display whether number is
Prime or not
a=int(input("Enter a Number : "))
flg=0
for i in range(1,a):
for j in range(2,i):
if(i%j==0):
flg=0
break
else:
flg=1
if(flg==1):
Created By : SANKET B. JETHAVA
print("Not Prime")
else:
print("Prime")
#16.Write a program to input a number and display sum of all the digits
of number.
a=input("Enter Number : ")
res=0
for i in range(0,len(a)):
res=(res+int(a[i]))
print("Sum of digit Number is : ",res)
#17.Write a program to input a number and print whether number is
Arm Strong or not
a=int(input("Enter a Number : "))
b=a
res=0
while(b!=0):
re=b%10
res=res + (re*re*re)
b=b//10
Created By : SANKET B. JETHAVA
if(res==a):
print(a," IS ARMSTRONG NUMBER")
else:
print(a," IS NOT ARMSTRONG NUMBER")
#18.Write a program to input a number and print whether number is
Palindrom or not
n=int(input("Enter number:"))
temp=n
rev=0
while(n>0):
d=n%10
rev=rev*10+d
n=n//10
if(temp==rev):
print("number is a palindrome!")
else:
print("number isn't a palindrome!")
Created By : SANKET B. JETHAVA
#19.Write a program to input a string and print whether string is
Palindrom or not
x = input("Enter String : ")
w = ""
for i in x:
w=i+w
if (x==w):
print("String is Palindrome")
if(x!=w):
print("String is not Palindrome")
#21.Write a Python Program to input 10 numbers and display total,
average, maximum and minimum out of all numbers
a=[]
total=0
for i in range(0,10):
a.append(int(input("Enter Number "+ str(i+1) + " : ")))
total=total+a[i]
a.sort()
print("Maximum Number is : "+ str(a[9]))
Created By : SANKET B. JETHAVA
print("Minimum Number is : "+ str(a[0]))
print("Total is : "+ str(total))
print("Average is : "+str(total//10))
#22.Write a Python Program to input 10 numbers and display sum of
only those numbers which have 5 as a digit.
a=[]
for i in range(1,11):
a.append(input("Enter number "+ str(i) +" : "))
b=0
for i in a:
if(str(5) in i):
b=b+int(i)
print("Sum of only those numbers which have 5 as a digit : ",b)
#23.Write a program with a function with two arguments. Return the
total of two arguments.
def fun(a1,a2):
return "Argument 1 value is : "+a1,"Argument 2 value is : "+a2
print(fun("sanket","Jethava"))
Created By : SANKET B. JETHAVA
#24.Write a Python Program to create function which accepts one
argument as a number and return
# Factorial value of the number. (Function must be RECURSIVE function,
not loop)
ans=1
def rec(a):
if(a!=0):
for i in range(1,a+1):
global ans
ans=ans*i
a=a-1
rec(a)
return ans
print("factorial is : ",rec(int(input("Enter Number : "))))
#25.Write a Python Program to make use of Global variables and
nonlocal variables.
def f():
def f2():
global x
x=x+10
Created By : SANKET B. JETHAVA
def f1():
nonlocal x
x=x+1
print("Inner Function x : ",x)
f2()
x=10
print("outer Function x : ", x)
x=x+5
f1()
x=20
print("Global X : ",x)
f()
print("Global X : ",x)
#26.Write a Python Program to create a lambda function to do total of
two values passed.
fun1= lambda a,b : a+b
Created By : SANKET B. JETHAVA
print("Sum of Two number is : " ,fun1(int(input("Enter number 1 :
")),int(input("Enter number 2 : "))))
#27.Write a Python Program to use lambda function along with filter(),
map() and reduce() functions.
def filter1():
print("Start of filter()\n","-"*50)
mylist = [4, 23, 0, 34, -22]
list1 = list(filter(lambda x : x, mylist))
print(list1)
print("End of filter()\n","-"*50)
print("-"*50)
def map1():
print("Start of map()\n","-"*50)
mylist1 = [4, 23, 34, 11, 37, 44]
mylist2 = [10, 10, 10, 10, 10, 10]
list1 = list(map(lambda x, y : x + y, mylist1, mylist2))
print(list1)
print("End of map()")
import functools
def reduce1():
Created By : SANKET B. JETHAVA
mylist1 = [4, 23, 34, 11, 37, 44]
list1 = reduce(map(lambda x, y : x + y, mylist1))
filter1()
map1()
reduce1()
#28.Write a program to make use of split(), rsplit() and splitlines()
function of string.
import os
a=input("Enter String : ")
print("-"*100)
print()
print(str("*"*30),"USE OF SPLIT()",str("*"*30) )
print()
print(a.split())
print("-"*100)
print()
print(str("*"*30),"USE OF SPLIT() WITH MAXSPLIT=1",str("*"*30) )
print()
Created By : SANKET B. JETHAVA
print(a.split(maxsplit=1))
print("-"*100)
print()
print(str("*"*30),"USE OF RSPLIT()",str("*"*30) )
print()
print(a.rsplit())
print("-"*100)
print()
print(str("*"*30),"USE OF RSPLIT() WITH MAXSPLIT=2",str("*"*30) )
print()
print(a.rsplit())
print("-"*100)
print()
print(str("*"*30),"USE OF SPLITLINES()",str("*"*30) )
print()
print(a.splitlines())
print("-"*100)
#29.Write a Python program to make use of all random functions
#i.e. choice(), random(), randrange(), shuffle() and uniform()
Created By : SANKET B. JETHAVA
import random
print(str("^"*30),"USE OF RANDRANGE",str("^"*30))
print("random.randrange() : ",random.randrange(12,100,5))
print()
print(str("^"*30),"USE OF RANDOM",str("^"*30))
print("random.random() : ",random.random())
print(str("^"*30),"USE OF CHOICE",str("^"*30))
l1=[12,32,4,65,76,43,74]
print("random.choice() : ",random.choice(l1))
random.shuffle(l1)
print("random.shuffle() : ", l1)
print("random.uniform() : ", random.uniform(10,60))
#30.Write a program to make use of all parts of exception handling in
Python. (Try to #generate run time exception and display the output)
try:
ans=10/0
print("Division is : " ,ans)
except ValueError as ve:
print("Error : ",ve)
Created By : SANKET B. JETHAVA
except ZeroDivisionError as zd:
print("Error : ",zd)
except:
print("Another Error come")
else:
print("This is else block")
finally:
print("In Finally block")
#31.Write a Python Program to read a file and print the contents of a
file.
f=open(r"E:\FoCA\MCA\SEM 3\PYTHON\PROGRAMS\test.txt","r")
for x in f.read():
print(x,end="")
#32.Write a Python Program to read a file and print the contents as
well as total number of #lines and total number of words in that file.
f=open(r"E:\FoCA\MCA\SEM 3\PYTHON\PROGRAMS\test.txt","r")
words=0
lines=0
Created By : SANKET B. JETHAVA
for x in f.read():
if(x in '\n'):
lines=lines+1
words=words+1
elif(x in [' ']):
words=words+1
print(x,end="")
print("Total Words : ",words,"\nTotal Lines : ", lines)
#33.Write a Python Program to read a file and search particular word in
that file. Output #should print whether word found or not and how
many times.
f=open(r"E:\FoCA\MCA\SEM 3\PYTHON\PROGRAMS\test.txt","r")
wo=input("Enter word for search from file : ")
found=0
l1=[]
s=""
for x in f.read():
s=s+x
Created By : SANKET B. JETHAVA
if(wo in s):
s=""
found=found+1
print(found)
'''36.Write a menu based Python Program for Student Management as
follows. (Use File Handling) Program should have following menu
1. Insert Student Details
2. Search Students
3. List All Students
4. Update Student Details
5. Delete Student
6. Sort Students as per Roll No.
7. Exit
'''
import os
import pickle
def AddStudent():
d = {}
Created By : SANKET B. JETHAVA
d["rollno"] = int(input("Enter Roll No : "))
d["name"] = input("Enter Name : ")
d["age"] = int(input("Enter Age : "))
d["gender"] = input("Enter Gender : ")
d["city"] = input("Enter City : ")
f = open("student.txt", "ab")
pickle.dump(d, f)
f.close()
def SearchStudent():
f = open("student.txt", "rb")
srollno = int(input("Enter Roll No to Search : "))
Created By : SANKET B. JETHAVA
found = False
try:
while(True):
d = pickle.load(f)
if(d["rollno"]==srollno):
found = True
print("Roll NO : ", d["rollno"])
print("Name : ", d["name"])
print("Age : ", d["age"])
print("Gender : ", d["gender"])
print("City : ", d["city"])
except:
f.close()
if(found==False):
print("Sorry!!! No Student Found with this Roll No")
def ListStudents():
f = open("student.txt", "rb")
Created By : SANKET B. JETHAVA
try:
x = " %6s %-20s %3s %6s %-10s" %("RollNo", "Name",
"Age", "Gender", "City")
print("-"*len(x))
print(" %6s %-20s %3s %6s %-10s" %("RollNo", "Name",
"Age", "Gender", "City"))
print("-"*len(x))
while(True):
d = pickle.load(f)
print(" %6d %-20s %3d %1s %-10s" %(d["rollno"],
d["name"], d["age"], d["gender"], d["city"]))
except:
print("-"*len(x))
f.close()
Created By : SANKET B. JETHAVA
def UpdateStudent():
f = open("student.txt", "rb")
ft = open("temp.txt", "wb")
srollno = int(input("Enter Roll No to Update : "))
found = False
try:
while(True):
d = pickle.load(f)
if(d["rollno"]==srollno):
found = True
print("Name : ", d["name"])
d["name"] = input("Enter Updated Name : ")
print("City : ", d["city"])
d["city"] = input("Enter Updated City : ")
pickle.dump(d, ft)
else:
Created By : SANKET B. JETHAVA
pickle.dump(d, ft)
except:
f.close()
ft.close()
os.remove("student.txt")
os.rename("temp.txt", "student.txt")
if(found==False):
print("Sorry!!! No Record Found")
else:
print("Record Updated Successfully")
def DeleteStudent():
f = open("student.txt", "rb")
ft = open("temp.txt", "wb")
srollno = int(input("Enter Roll No to Delete : "))
Created By : SANKET B. JETHAVA
found = False
try:
while(True):
d = pickle.load(f)
if(d["rollno"]==srollno):
print("Roll No : ", d["rollno"])
print("Name : ", d["name"])
print("Age : ", d["age"])
print("Gender : ", d["gender"])
print("City : ", d["city"])
dch = input("Do You Want to Delete This Record
(Y/N) : ")
if(dch in "Nn"):
pickle.dump(d, ft)
else:
found = True
Created By : SANKET B. JETHAVA
else:
pickle.dump(d, ft)
except:
f.close()
ft.close()
if(found==False):
print("Sorry!!! No Record Found or Not Deleted")
else:
print("Record Deleted finally")
os.remove("student.txt")
os.rename("temp.txt", "student.txt")
ch = 1
while(ch>=1 and ch<=5):
os.system("cls")
print("STUDENT MANAGEMENT SYSTEM")
print("-------------------------")
Created By : SANKET B. JETHAVA
print(" 1. Add Student")
print(" 2. Search Student")
print(" 3. List Students")
print(" 4. Update Student")
print(" 5. Delete Student")
print(" 6. Exit")
ch = int(input("Enter Choice (1-6) : "))
if(ch==1):
AddStudent()
elif(ch==2):
SearchStudent()
elif(ch==3):
ListStudents()
elif(ch==4):
UpdateStudent()
elif(ch==5):
DeleteStudent()
Created By : SANKET B. JETHAVA
os.system("pause")
print("Bye Bye")
'''
37.Write a Python Program to Zip and UnZip file
'''
from zipfile import ZipFile
def zip():
f=ZipFile("abc.zip","w")
f.write("p21.py")
f.write("p22.py")
f.write("p23.py")
f.close()
print("File Zip is Completed")
def unzip():
f=ZipFile("abc.zip","r")
f.extractall()
Created By : SANKET B. JETHAVA
#f.extractall(path="e:\\abc")
f.close()
print("File UnZip/extract is Completed")
while(True):
print("1. Zip The File")
print("2. UnZip The File")
print("3. Exit")
ch=int(input("Enter Your Choice : "))
if ch==1:
zip()
elif ch==2:
unzip()
else:
exit()
'''
39.Write a Python Program that creates a simple class with any two
functions
'''
class Ex:
Created By : SANKET B. JETHAVA
#CLASS variable
num = 0
def __init__(self, name, gender, age):
#All following are INSTANCE variables
self.name = name
self.gender = gender
self.age = age
Ex.num = Ex.num + 1
#class method example
def Hello():
print("Hello There")
print("How Are YOu")
def Display(self):
print("Name : ", self.name)
print("Gender : ", self.gender)
print("Age : ", self.age)
print("---------------------")
Created By : SANKET B. JETHAVA
a = Ex("Sanket", "M", 21)
#b = Ex("Hello", "M", 20)
a.Display()
#b.Display()
#print("Total Students : ", Ex.num)
Ex.Hello()
'''
Write a Python Program that creates a student class with appropriate
members and functions to add student, display student, delete student
and search student (Use lists or tuple or named tuple, whatever
applicable)
'''
#already complate this type of program. For ex. program 36
'''
41.Write a Python Program that creates a Student class with various
methods. Use setattr() and getattr() on class object
'''
class Student:
def __init__(self):
#All following are INSTANCE variables
Created By : SANKET B. JETHAVA
self.name = ""
def Display(self):
print("From Method - Name : ", self.name)
print("---------------------")
a = Student()
#b = Student()
setattr(a,"name","sanket")
#setattr(b,"name","Jethava")
a.Display()
#b.Display()
print("Using getattr (a) : ",getattr(a, "name"))
#print("Using getattr (b) : ",getattr(b, "name"))
'''
Created By : SANKET B. JETHAVA
42.Write a Python Program that creates a class with function
overloading
'''
class Ab():
def __init__(self,a=None,b=None,c=None):
if(a==None and b==None and c==None):
print("Function with no Parameter")
elif(a!=None and b==None and c==None):
print("Function with one Parameter")
print("paramter - I : ",a)
elif(a!=None and b!=None and c==None):
print("Function with Two Parameter")
print("paramter - I : ",a)
print("paramter - II : ",b)
elif(a!=None and b!=None and c!=None):
print("Function with Three Parameter")
print("paramter - I : ",a)
print("paramter - II : ",b)
print("paramter - III : ",c)
Created By : SANKET B. JETHAVA
a=Ab()
b=Ab("Sanket")
c=Ab("Sanket","Jethava")
d=Ab("Writer","Sanket","Jethava")
'''
43.Write a Python Program that creates a class and inherit into another
class (Base Class : Student with rollno, name, gender, age)
(Derived Class : Course with coursename, duration, fee)
Use appropriate functions for each class
'''
class Student:
def __init__(self,rollno,name,gender,age):
self.rollno=rollno
self.name=name
self.gender=gender
self.age=age
self.sets()
Created By : SANKET B. JETHAVA
def sets(self):
print("Roll No. : ",self.rollno)
print("Name : ",self.name)
print("Gender : ",self.gender)
print("Age : ",self.age)
class Course(Student):
def __init__(self,cname,duration,fee,rollno,name,gender,age):
super().__init__(rollno,name,gender,age)
self.cname=cname
self.duration=duration
self.fee=fee
self.setc()
def setc(self):
print("Course Name : ",self.cname)
print("Duration : ",self.duration)
print("Fee : ",self.fee)
a=Course("MCA","3 YEAR",85000,3058,"SANKET","M",21)
Created By : SANKET B. JETHAVA
'''
44.Write a Python Program that inherits one class into another.
'''
class A:
def __init__(self):
print("This is Super class")
class B(A):
def __init__(self):
super().__init__()
print("This is Base class")
a=B()
'''
45.Write a Python Program that inherits one class into another class
with does FUNCTION OVERRIDING
'''
class A:
Created By : SANKET B. JETHAVA
def dis(self):
print("This is Super class dis() function")
class B(A):
def dis(self):
super().dis()
print("This is Base class dis() function")
a=B()
a.dis()
'''
46.Write a simple Python Program to make use of PyLab plotting
'''
import pylab as py
py.plot([1,2,3,4],[10,20,30,40])
py.show()
'''
Created By : SANKET B. JETHAVA
47.Write a simple Python Program to make use of Pylab plotting with
title, saving figure, x axis title, y asix title, line width, line color, etc.
options of chart.
'''
import pylab as py
py.figure("Student 1 Detail")
py.xlabel("Subjct")
py.ylabel("Obtained Marks")
py.plot([1,2,3,4],[18,20,19,20],color="g",linewidth=10)
py.savefig("first.png")
py.title("Student 1 record")
py.show()
'''
48.Write a program to create Bar Chart
'''
import pylab as py
x = [1,2,3,4]
y = [10, 11, 34, 25]
Created By : SANKET B. JETHAVA
py.bar(x,y,label="Experience Summary", color="red")
py.xlabel("Years")
py.ylabel("Experience")
py.title("Experience Summary")
py.show()
'''
49.Write a program to create Pie Chart
'''
import pylab as py
courses = ["MCA", "MBA", "Engineering", "Arch"]
students = [190, 150, 120, 90]
mycolors = ["green", "blue", "red", "magenta"]
myexplode=[0.1, 0, 0, 0]
py.pie(students, labels=courses, colors=mycolors, explode=myexplode,
shadow=True,autopct="%.2f%%")
py.show()
'''
50.Write a Python Program to create Data Frame from Excel file
'''
Created By : SANKET B. JETHAVA
import pandas as pd
import sys
# Must set following otherwise dataframe output will not be visible on
screen
sys.__stdout__ = sys.stdout
df1 = pd.read_excel("mydata.xlsx", "Sheet1")
# df2 = pd.read_csv("e:\\mydata1.csv")
# df2 = pd.read_csv("e:\\mydata1.csv", sep='|')
# df2 = pd.DataFrame(mydic)
print(df1)
'''
df1["Name"]
df1[df1.Age>=30]
df1["Name"][df1.Age>=30]
Created By : SANKET B. JETHAVA
df1[["Name", "Age"]]
df1[["Name", "Age"]][df1.Gender=="M"]
# default value for head or tail is 5
df1.head()
df1.head(3)
df1.tail()
df1.tail(3)
df1.shape
#Displays No of rows and columns for particular dataframe
df1.columns
#displayes list of columns
Created By : SANKET B. JETHAVA
# Following command (size) will show you total values in data frames (If
we have 15 rows and 5 columns, it will show 75 because total 75 values
are there)
df1.size
# Following command will display data type of each column. String
types are reffered as objects
df1.dtypes
df1.describe()
#It will take all numerical columns of data frame and show various
statistical calculations on all those numerical columns
df1["Age"].describe()
# Above command will give statistical calculations only for "Age"
column
df1["Age"].max()
#Will show maximum value from "Age" column
Created By : SANKET B. JETHAVA
df1["Age"].min()
df1["Name"][df1.Age==df1["Age"].max()]
# It will display only name of the person having maximum age
df1.index
# to view index column details
df1.set_index("RollNo")
# It will just show rollno index but won't replace original index
df1.set_index("RollNo", inplace=True)
# It will create index on Rollno column. Original index will be on
"RollNo" now
df1.loc[109]
# It will search (locate) above value in indexed column. It will search
rollno 109 in indexed column i.e. rollno
Created By : SANKET B. JETHAVA
df1.sort_values("Age", ascending=True)
#This will return sorted data as per "Age" column in ascending order
# for descending order you can say --> ascending=False
df1.dropna()
# This will drop all the rows which has null values anywhere
df1.fillna("NULL")
# This will show "NULL" value inplace of "NaN" values
df1.fillna({"Name":"No Name", "Age":0})
# This will display "No Name" for all null names, 0 for all null ages. For
other null columns it will display "NaN" only'''
'''
51.Write a Python Program to create Data Frame from .CSV file
'''
import pandas as pd
import sys
sys.__stdout__ = sys.stdout
df1 = pd.read_csv("mydata.csv")
Created By : SANKET B. JETHAVA
print(df1)
#Write a Menu driven program to define the MRO(Method Resolution
Order)
class A:
def DisplayA(self):
print("Display A")
class B:
def DisplayB(self):
print("Display B")
class C:
def DisplayC(self):
print("Display C")
class X(A):
def DisplayX(self):
print("Display X")
Created By : SANKET B. JETHAVA
class Y(B, C):
def DisplayY(self):
print("Display Y")
class AA(Y, X):
def DisplayAA(self):
print("Display A")
'''Write a menu driven program for Bank application and also use pickle
to store detail in file
1. Add Account
2. Withdraw Money
3. Deposite Money
4. View Account Detail
5. Exit
'''
import os
import pickle
def acc():
d = {}
Created By : SANKET B. JETHAVA
d["accountno"] = int(input("Enter Account No : "))
d["name"] = input("Enter Name : ")
d["age"] = int(input("Enter Age : "))
d["gender"] = input("Enter Gender : ")
d["city"] = input("Enter City : ")
d["amount"] = int(input("Enter Amount for initial Stage : "))
f = open("bank.txt", "ab")
pickle.dump(d, f)
f.close()
def withdraw():
f = open("bank.txt", "rb")
f1= open("temp.txt", "wb")
try:
Created By : SANKET B. JETHAVA
while(True):
d = pickle.load(f)
if(d["accountno"]==int(input("Enter Account Number : "))):
a=int(input("Enter amount to Withdraw : "))
b=int(d["amount"])
c=b-a
d["amount"]=c
print("Withdraw Successfully with Amount : ",a)
print("Your updated Amount is : ",d["amount"])
pickle.dump(d,f1)
break
else:
pickle.dump(d,f1)
f.close()
f1.close()
except:
f.close()
f1.close()
f.close()
f1.close()
Created By : SANKET B. JETHAVA
os.remove("bank.txt")
os.rename("temp.txt", "bank.txt")
def deposite():
f = open("bank.txt", "rb")
f1= open("temp.txt", "wb")
try:
while(True):
d = pickle.load(f)
if(d["accountno"]==int(input("Enter Account Number : "))):
a=int(input("Enter amount to Deposite : "))
b=int(d["amount"])
c=b+a
d["amount"]=c
print("Withdraw Successfully with Amount : ",a)
print("Your updated Amount is : ",d["amount"])
pickle.dump(d,f1)
break
else:
pickle.dump(d,f1)
Created By : SANKET B. JETHAVA
except:
f.close()
f1.close()
f.close()
f1.close()
os.remove("bank.txt")
os.rename("temp.txt", "bank.txt")
def view():
f = open("bank.txt", "rb")
try:
x = " %9s %-20s %-9s %3s %6s %-10s" %("AccountNo", "Name",
"Amount", "Age", "Gender", "City")
print("-"*len(x))
print(" %9s %-20s %-9s %3s %6s %-10s" %("AccountNo",
"Name","Amount", "Age", "Gender", "City"))
print("-"*len(x))
while(True):
d = pickle.load(f)
print(" %6d %-20s %9d %3d %1s %-10s" %(d["accountno"],
d["name"], d["amount"] , d["age"], d["gender"], d["city"]))
Created By : SANKET B. JETHAVA
except:
print("-"*len(x))
f.close()
while(1):
print(" 1. Add Account")
print(" 2. Withdraw Money")
print(" 3. Deposite Money")
print(" 4. View Account Detail")
print(" 5. Exit")
ch=int(input("Enter Your Choice ( 1 - 5 ) : "))
if ch==1:
acc()
elif ch==2:
withdraw()
elif ch==3:
deposite()
elif ch==4:
view()
else:
exit()
Created By : SANKET B. JETHAVA
from threading import *
import pylab as pl
import random
from time import *
class test(Thread):
def test1(self):
for i in range(6):
pl.figure("Test "+str(i))
l1=[10,20,30,40]
pl.plot(l1,l1)
pl.show()
self.test2()
def test2(self):
sleep(1)
def pie1(self):
pass
Created By : SANKET B. JETHAVA
def run(self):
self.test1()
c=test().start()
from threading import *
from time import *
l=Lock()
def test():
def test1():
b=0
while(True):
sleep(0.8)
print(b," From test1",current_thread().getName())
b=b+1
def test2():
l.acquire()
for i in range(10):
Created By : SANKET B. JETHAVA
sleep(1)
print(i ," From test2 ",current_thread().getName())
l.release()
t1=Thread(target=test2).start()
t2=Thread(target=test1)
t2.daemon=True
t2.start()
t=Thread(target=test).start()
from threading import *
from time import *
class test():
b=0
def __init__(self):
self.l=Lock()
def test1(self):
self.l.acquire()
for i in range(10):
sleep(1)
print(i," From test1()",current_thread().getName())
Created By : SANKET B. JETHAVA
self.l.release()
def test2(self):
while(True):
#for i in range(15):
sleep(0.9)
print(test.b , " From test2()",current_thread().getName())
test.b=test.b+1
t=test()
t1=Thread(target=t.test1)
t2=Thread(target=t.test1)
t3=Thread(target=t.test2)
t3.daemon=True
t1.start()
t3.start()
t2.start()
'''Write a menu driven program for Bank application and also use pickle
to store detail in file
1. Add Account
Created By : SANKET B. JETHAVA
2. Withdraw Money
3. Deposite Money
4. View Account Detail
5. Exit
'''
import os
import pickle
def acc():
d = {}
d["accountno"] = int(input("Enter Account No : "))
d["name"] = input("Enter Name : ")
d["age"] = int(input("Enter Age : "))
d["gender"] = input("Enter Gender : ")
d["city"] = input("Enter City : ")
Created By : SANKET B. JETHAVA
d["amount"] = int(input("Enter Amount for initial Stage : "))
f = open("bank.txt", "ab+")
pickle.dump(d,f)
f.close()
def withdraw():
f = open("bank.txt", "rb+")
f1= open("temp.txt", "wb+")
try:
i1=int(input("Enter Account Number : "))
while(True):
d = pickle.load(f)
if(d["accountno"]==i1):
a=int(input("Enter amount to Withdraw : "))
b=int(d["amount"])
c=b-a
d["amount"]=c
Created By : SANKET B. JETHAVA
print("Withdraw Successfully with Amount : ",a)
print("Your updated Amount is : ",d["amount"])
pickle.dump(d,f1)
else:
print("Wrong Account Details")
pickle.dump(d,f1)
except:
f.close()
f1.close()
f.close()
f1.close()
os.remove("bank.txt")
os.rename("temp.txt", "bank.txt")
def deposite():
f = open("bank.txt", "rb+")
f1= open("temp.txt", "wb+")
try:
i1=int(input("Enter Account Number : "))
Created By : SANKET B. JETHAVA
while(True):
d = pickle.load(f)
if(d["accountno"]==i1):
a=int(input("Enter amount to Deposite : "))
b=int(d["amount"])
c=b+a
d["amount"]=c
print("Withdraw Successfully with Amount : ",a)
print("Your updated Amount is : ",d["amount"])
pickle.dump(d,f1)
else:
print("Wrong Account Details")
pickle.dump(d,f1)
except:
f.close()
f1.close()
f.close()
f1.close()
os.remove("bank.txt")
os.rename("temp.txt", "bank.txt")
Created By : SANKET B. JETHAVA
def view():
f = open("bank.txt", "rb+")
try:
x = " %9s %-20s %-9s %3s %6s %-10s" %("AccountNo", "Name",
"Amount", "Age", "Gender", "City")
print("-"*len(x))
print(" %9s %-20s %-9s %3s %6s %-10s" %("AccountNo",
"Name","Amount", "Age", "Gender", "City"))
print("-"*len(x))
while(True):
d = pickle.load(f)
print(" %6d %-20s %9d %3d %1s %-10s" %(d["accountno"],
d["name"], d["amount"] , d["age"], d["gender"], d["city"]))
except:
print("-"*len(x))
f.close()
while(1):
print(" 1. Add Account")
print(" 2. Withdraw Money")
print(" 3. Deposite Money")
Created By : SANKET B. JETHAVA
print(" 4. View Account Detail")
print(" 5. Exit")
ch=int(input("Enter Your Choice ( 1 - 5 ) : "))
if ch==1:
acc()
elif ch==2:
withdraw()
elif ch==3:
deposite()
elif ch==4:
view()
else:
exit()
#A program where two threads are acting on the same method to allot
a berth for the passenger.
from threading import *
from time import *
class Gadi():
def __init__(self,total):
self.l=Lock()
Created By : SANKET B. JETHAVA
self.total=total
def booking(self,require):
self.l.acquire()
sleep(3)
if(self.total>=require):
nm=current_thread().getName()
print("Name of Booker : ",nm ," with allocated Ticket is
: ",require)
self.total=self.total-require
print("Available tickets : ",self.total)
else:
print("Ticket Is Not Available")
self.l.release()
g=Gadi(50)
nm1=input("Enter Name of Booker : ")
s1=int(input("How Many Ticket wants to Booked : "))
nm2=input("Enter Name of Booker : ")
s2=int(input("How Many Ticket wants to Booked : "))
Created By : SANKET B. JETHAVA
t1=Thread(target=g.booking,args=(s1,))
t2=Thread(target=g.booking,args=(s2,))
t1.setName(nm1)
t2.setName(nm2)
t1.start()
t2.start()
# This program will input url from user and read the source code of that
particular url
# We use "urllib.request" module and "urlopen()" method for the same
# simply use above method and store it as file object and then display
using "read()" method
import urllib.request
import re
# You can input url using input() but remember enter proper url else it
will not read
#myurl = input("Enter URL of web site : ")
myurl = "https://www.google.co.in/"
try:
file = urllib.request.urlopen(myurl)
Created By : SANKET B. JETHAVA
#print(file.read())
data = file.read()
f=open("test2.txt","w")
f.write(str(data))
f.close()
f=open("test2.txt","r")
ans=[]
for i in f.readlines():
ans=re.findall("<\w+>",i)
#ans=re.findall("html",str(data))
print(ans)
# You can also print file content using f.readlines() method to
print line by line
except:
# It will raise error if url is wrong or any other exception occurs
print("Sorry!!! Wrong URL provided")
# import socket module which is used for networking
import socket
host = input("Enter Web Site Name : ")
Created By : SANKET B. JETHAVA
try:
#gethostbyname() method of socket module is used to know ip
address by giving host name
addr = socket.gethostbyname(host)
print("Web Site : ", host)
print("IP Address : ", addr)
except socket.gaierror:
#gaierror means Get Address Information Error. This will be raised
if website name is wrong
print("The Website Does Not Exist")
# This program will input the URL from user and parse it
# After parsing we can view different parts of URL which we can get
using "urlparse()" function of "urllib.parse" module
# Url generally contains 4 parts as follows
# Part-1 : protolcol which says "http" or "https" or "ftp"
# Part-2 : server name or ip address of a web site
# Part-3 : port number of a website. Generally taken as default which
is 80
# Part-4 : contains the file which we have given in url. Part-4 can also
contain some query string if we have given
Created By : SANKET B. JETHAVA
# Examle :
http://www.marwadieducation.edu.in/MCA/mylessons.html?name=Nil
esh
# urllib.parse.urlparse gives answer in TUPLE format as follows
# import urllib.parse module to find different parts of a URL and other
parsing functions
import urllib.parse
url =
"http://www.marwadieducation.edu.in:991/MCA/mylessons.html?nam
e=Nilesh"
ans_url = urllib.parse.urlparse(url)
print("URL Tuple : ", ans_url)
print("-"*50)
print("Scheme : ", ans_url.scheme)
Created By : SANKET B. JETHAVA
print("Net Location : ", ans_url.netloc)
print("Path : ", ans_url.path)
print("Parameters (if any) : ", ans_url.params)
print("Query String : ", ans_url.query)
print("Port Number : ", ans_url.port)
print("Total Url : ", ans_url.geturl())
print("-"*50)
# This program will input url from user and read the source code of that
particular url
# It will also download the source code to a new file
# We use "urllib.request" module and "urlopen()" method for the same
# simply use above method and store it as file object and then display
using "read()" method
import urllib.request
# You can input url using input() but remember enter proper url else it
will not read
#myurl = input("Enter URL of web site : ")
Created By : SANKET B. JETHAVA
myurl = "http://www.google.co.in"
try:
file = urllib.request.urlopen(myurl)
data = file.read()
print(data.decode())
# You can also print file content using f.readlines() method to
print line by line
# Don't forget to give file mode as write + binary i.e. "wb"
fnew = open("e:\\mca3a.html", "wb")
fnew.write(data)
fnew.close()
except:
# It will raise error if url is wrong or any other exception occurs
print("Sorry!!! Wrong URL provided")
# This program will accept url of image and download it
# We use "urllib.request" module and "urlretrieve()" method for the
same
Created By : SANKET B. JETHAVA
# "urlretrieve()" method has 2 parameters as follows
# Parameter-1 : give full url of an image
# Parameter-2 : specify download image name with path of your pc
import urllib.request
# You can input url using input() but remember enter proper url else it
will not download
#myurl = input("Enter URL of IMAGE : ")
myurl = "https://www.python.org/static/community_logos/python-
logo.png"
try:
print(myurl)
download = urllib.request.urlretrieve(myurl, "mca3b.png")
print("Image Downloaded....")
print(download)
except:
# It will raise error if url is wrong or any other exception occurs
Created By : SANKET B. JETHAVA
print("Sorry!!! Wrong URL provided")
# THis program will use "socket()" method of "socket" module to create
TCP Server
# "socket()" method has two parameters as follows
# Example : s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Parameter-1 : this parameter specifies which protocol we want to
use i.e. IPv4 or IPv6
# For IPv4 we specify, socket.AF_INET (this is default if we don't
give)
# For IPv6 we specify, socket.AF_INET6
# Parameter-2 : this parameter specifies which way we want to use
socket. TCP or UDP
# For TCP we specify, socket.SOCK_STREAM (this is default if we
don't give)
# For UDP we specify, socket.SOCK_DGRAM
import socket
host = "localhost"
port = 5555
Created By : SANKET B. JETHAVA
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# if we give only following line, will also have same effect because
defualt are IPv4 and TCP
# s = socket.socket()
# bind() method of socket object will connect particular port and host
with "s" object. For TCPServer, we use bind() method on server side.
s.bind((host, port))
# listen() method will be make socket ready to listen now onwards. If
we specify "listen(5)", means it will listen to maximum 5 clients.
s.listen(1)
print("Waiting for Client to get connected....")
# accpet() method will put method in accept mode. That means now
this program will run infinitely till it receives any request from client.
The moment it receives any request, it will move forward to the next
line of the program after "accept()" method.
# accept() method will return two values. first object of client and
second address of client
Created By : SANKET B. JETHAVA
c, addr = s.accept()
print("Established Connection from : ", str(addr))
# using send() method we can send messages but must sent in BINARY
format
c.send(b"Hello There... You are connected to TCP Server....")
c.send(b"Bye... Bye....")
c.close()
# THis program will use "socket()" method of "socket" module to create
TCP Client
# It uses the same socket() method but instead of "bind()" method it
will use "connect()"
# "bind()" method identifies that the running program is server proram
# "connect()" method identifies that the running program is client
program
# if you use "bind()" method, you use "send()" method to send data to
client
# if you use "connect()" method, you use "recv()" method to receive the
data from server
Created By : SANKET B. JETHAVA
import socket
host = "localhost"
port = 5555
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# connect() method also uses host and port to connect with server
s.connect((host, port))
# use recv() method to receive specified bytes from server
msg = s.recv(10)
# keep on running loop till messages are received..
# in our server program we have given to send() methods. so our loop
will run 2 times.
# recv() method sends the data in binary format. So use decode()
method to print as a string
Created By : SANKET B. JETHAVA
while msg:
print("Received : ", msg.decode())
msg = s.recv(10)
s.close()
# This program is for creating UDP Server
# We use the same socket() method to create a socket but we will
specify as follows
# Parameter-1 : socket.AF_INET which indicates IPv4
# Parameter-2 : socket.SOCK_DGRAM which indicates its UDP
# UDP Server sends the data using connectionless mechanism
# UDP object has a method called "sendto()" which has two parts as
follows
# s.sendto(b"Your Message", ((host, port))
# Part-1 : This is your message which you want to send (Must send
binary message only)
# Part-2 : Here we specify host and port as a tuple value
import socket
import time
Created By : SANKET B. JETHAVA
host = "localhost"
port = 6666
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
print("Waiting for client to get connect... Will wait for 5 seconds
only.....")
time.sleep(5)
s.sendto(b"Hello There... You are connected to Server Now", (host,
port))
print("Done....")
s.close()
# This program is for creating UDP Client
# We use the same socket() method to create a socket but we will
specify as follows
# Parameter-1 : socket.AF_INET which indicates IPv4
# Parameter-2 : socket.SOCK_DGRAM which indicates its UDP
# UDP Server sends the data using connectionless mechanism
Created By : SANKET B. JETHAVA
# UDP socket object can use bind() method to connect with UDP Server
# UDP client object has a method called "recvfrom()" which has two
parts as follows
import socket
import time
host = "localhost"
port = 6666
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((host, port))
msg, addr = s.recvfrom(1024)
try:
s.settimeout(5)
while(msg):
Created By : SANKET B. JETHAVA
print("Message Received : ", msg.decode())
msg, addr = s.recvfrom(1024)
except:
print("Time is Over... So its terminating")
s.close()
# This is a FILE Server program which will create a TCP socket and send
the data to client
# THis program accepts name of file name with path from client once
connected
# After reading the contents of file, contents will be sent to client
import socket
host = "localhost"
port = 5555
# By default "socket()" method creates IPv4 and socket will be Stream
i.e. TCP
s = socket.socket()
Created By : SANKET B. JETHAVA
s.bind((host, port))
print("Waiting for Client to get Connected....")
s.listen(1)
c, addr = s.accept()
print("A Client has accepted the Connection..........")
# This recv() method will receive name of the file from client
fname = c.recv(1024)
fname = str(fname.decode())
print("File Name from Client : ", fname)
try:
Created By : SANKET B. JETHAVA
f = open(fname, "rb")
data = f.read()
c.send(data)
print("Data sent to Client......")
f.close()
except FileNotFoundError:
c.send(b"Sorry!!! Specified File Does Not Exist...")
except:
c.send(b"Some Error Occured on Server Side...")
c.close()
# THis is File Client Program
# Step-1 This program will first get connected with File Server
# Step-2 After that it will ask user to input file name
# Step-3 File name will be sent to File Server
# Step-4 Server will receive file name and send the content
Created By : SANKET B. JETHAVA
# Step-5 Contents or Error Message will be received from File Server
and printed on Client screen
import socket
host = "localhost"
port = 5555
s = socket.socket()
s.connect((host, port))
fname = input("Enter File name with Path to Read from File Server : ")
# Send the name of file name in binary format using "encode()" method
s.send(fname.encode())
content = s.recv(1024)
print("Contents are as follows")
print("--------------------------------")
Created By : SANKET B. JETHAVA
while(content):
print(content.decode())
content = s.recv(1024)
print("--------------------------------")
s.close()
# This program creates a chat server for two way communication
# The program does not have any new methods in comparison to
previous one
# The only thing is, this program will do "send()" and "recv()" method
both
# It will continue the loop until the data is received from client
import socket
host = "localhost"
port = 6666
s = socket.socket()
Created By : SANKET B. JETHAVA
s.bind((host, port))
s.listen(1)
print("Waiting for client to get connected.....")
c, addr = s.accept()
print("Connted with Client.........")
while True:
data = c.recv(1024)
if not data:
break
print("Data from Client : ", str(data.decode()))
data1 = input("Enter Response : ")
Created By : SANKET B. JETHAVA
c.send(data1.encode())
c.close()
s.close()
# This program creates a chat server for two way communication
# The program does not have any new methods in comparison to
previous one
# The only thing is, this program will do "send()" and "recv()" method
both
# It will continue the loop until the data is received from client
import socket
host = "localhost"
port = 6666
s = socket.socket()
s.connect((host, port))
str = input("Enter Data for Server... Type 'EXIT' to stop: ")
Created By : SANKET B. JETHAVA
while str.upper() != 'EXIT':
s.send(str.encode())
data = s.recv(1024)
print("Message from Server : ", data.decode())
str = input("Enter Data for Server... Type 'EXIT' to stop: ")
s.close()
# THis program will allow you to send mail to any SMTP Mail
# we can import "smtplib" module for sending SMTP mail
# For SMTP mail, we shall create object of "MIMEText" class with Body
Text
import smtplib
from email.mime.text import MIMEText
Created By : SANKET B. JETHAVA
body = '''THis is s test mail which is sent from Python E-Mail.....'''
msg = MIMEText(body)
fromaddr = "[email protected]"
toaddr = "[email protected]"
msg["From"] = fromaddr
msg["To"] = toaddr
msg["Subject"] = "Test Mail from Python"
server = smtplib.SMTP("smtp.gmail.com", 587)
server.starttls()
server.login(fromaddr, "XXX")
server.send_message(msg)
Created By : SANKET B. JETHAVA
print("Mail Sent....")
server.quit()
mylist = [4, 23, 34, 11, 37, 44]
ans = list(filter(lambda x : x>30, mylist))
ans1 = list(filter(lambda x : x>=25 and x<=35, mylist))
print(mylist)
print(ans)
print(ans1)
import functools
mylist = [4, 23, 34, 11, 37, 44]
mylist1 = [1,2,3,4,5]
ans = functools.reduce(lambda x, y : x*y, mylist1)
print(mylist)
print(ans)
import pylab as pl
Created By : SANKET B. JETHAVA
agegroup = [0,10,20,30,40,50,60,70,100]
ages =
[10,34,1,3,4,90,243,23,34,23,56,454,676,44,44,33,56,75,43,45,77,44,1
1,45,75,354,334,73,44,34,55,6,46,77,55,33,23,6,87,5,3,3,23,34,34,22,4
4,55,76, 65]
pl.hist(ages, agegroup, histtype='bar', rwidth=0.9)
pl.show()
import mysql.connector as db
import pandas as pd
import pylab as pl
import re
import all_datatype as al #show code below
con=db.connect(host="localhost",database="test",user="root",passw
ord="")
cur=con.cursor()
def all():
al.call_all()
Created By : SANKET B. JETHAVA
def regex():
n=int(input("How many lines want to write in file : "))
f=open("regex.txt","w")
for i in range(n):
s=input("Enter a Line "+str(i+1)+" : ")+"\n"
f.write(s)
f.close()
pattern=input("Enter Pattern to Mathch with records of file : ")
f=open("regex.txt","r")
for i in f.readlines():
ans=re.findall(pattern,i)
if(ans):
print("Pattern Match")
print(ans)
break
else:
print("Patterb not Match")
def insert_record():
Created By : SANKET B. JETHAVA
id=int(input("Enter id : "))
name=input("Enter dish name : ")
price=int(input("Enter price : "))
s="insert into food values (%d,'%s',%d)" %(id,name,price)
cur.execute(s)
con.commit()
print("Record inserted Successfully")
print_record()
def update_record():
print_record()
id=int(input("Enter id : "))
name=input("Enter Dish Name : ")
price=int(input("Enter price : "))
s="update food set nm='%s',rating=%d where cno=%d"
%(name,price,id)
cur.execute(s)
con.commit()
print("Record updated Successfully")
Created By : SANKET B. JETHAVA
print_record()
def delete_record():
print_record()
id=int(input("Enter id : "))
s="delete from food where cno=%d" %(id)
cur.execute(s)
con.commit()
print("Record deleted Successfully")
print_record()
def print_record():
ans=cur.execute("select * from food")
a=cur.fetchall()
print("%3s %-15s %-6s" %("id","Name","Price"))
for i in a:
print("%3s %-15s %-6s" %(i[0],i[1],i[2]))
def create_csv():
Created By : SANKET B. JETHAVA
with open ("test.csv","w") as f:
s="id,name,price\n"
f.write(s)
for i in a:
s=str(i[0])+","+i[1]+","+str(i[2])+"\n"
f.write(s)
def create_excel():
with open ("test1.xls","w") as f1:
s="id\tname\tprice\n"
f1.write(s)
for i in a:
s=str(i[0])+"\t"+i[1]+"\t"+str(i[2])+"\n"
f1.write(s)
df=pd.read_csv("test.csv")
def show_dataframe():
print(df)
Created By : SANKET B. JETHAVA
def show_graph():
id=list(df["id"])
name=list(df["name"])
price=list(df["price"])
myexplode=[]
mx=max(price)
for i in range(len(price)):
if (price[i]==mx):
myexplode.append(0.1)
else:
myexplode.append(0)
pl.pie(price,labels=name,explode=myexplode)
pl.legend()
pl.show()
while(True):
print("--"*30)
print("1. Show Records from Database [In Tabular Format]")
print("2. Fetch record from database and write CSV file")
print("3. Fetch record from database and write EXCEL file")
Created By : SANKET B. JETHAVA
print("4. Fetch record from Database and write CSV and print
record using DATAFRAME")
print("5. Fetch record from Database and write CSV and print
record using DATAFRAME and draw PIE Graph")
print("6. Insert record in database")
print("7. Update record in database")
print("8. Delete record in database")
print("9. Enter string from user and write it in file and also take
pattern from user and match pattern after fetching record from file
and display result.")
print("10. All Operations of List, Tuple, Dictionary and String")
print("0. Exit")
choice=int(input("Enter Your Choice : "))
if(choice==1):
print_record()
elif(choice==2):
create_csv()
elif(choice==3):
create_excel()
elif(choice==4):
show_dataframe()
Created By : SANKET B. JETHAVA
elif(choice==5):
show_graph()
elif(choice==6):
insert_record()
elif(choice==7):
update_record()
elif(choice==8):
delete_record()
elif(choice==9):
regex()
elif(choice==10):
all()
elif(choice==0 or choice >9 ):
break
all_datatype.py
def call_all():
while(1):
print('1. List')
print('2. Tuple')
print('3. Dictionary')
Created By : SANKET B. JETHAVA
print('4. String')
print('0. Stop')
ch=input('Enter Your Choice : ')
if ch=='1':
#...............................START LIST...........................
l1=[1,2]
while(1):
print('1. Append')
print('2. Count')
print('3. Insert')
print('4. Extend')
print('5. Remove')
print('6. Index')
print('7. Pop')
print('8. Sort')
print('9. Reverse')
print('10. Dislay')
print('0. Stop')
ch=input('Enter Your Choice : ')
if ch=='1':
Created By : SANKET B. JETHAVA
n=int(input('Enter No. :'))
for i in range(1,n+1):
l1.append(int(input('Enter no. for
append : '+str(i)+' = ')))
print(l1)
elif ch=='2':
c=(int(input('Enter no. for count from list :
')))
print('Total no of occurance is
:',l1.count(c))
elif ch=='3':
e=(int(input('Enter no. for insert in list : ')))
i=(int(input('Enter index to store no in list :
')))
l1.insert(i,e)
print('Inserted list is :',l1)
elif ch=='4':
l2=[]
m=int(input('Enter No. for list 2 [l2] :'))
for i in range(1,m+1):
Created By : SANKET B. JETHAVA
l2.append(int(input('Enter no. for
append list 1 : '+str(i)+' = ')))
print('List 1 is : ',l1)
l2.extend(l1)
print('Extend List is :',l2)
elif ch=='5':
print(l1)
a=int(input('Enter sequence no of list
element which u want remove :'))
l1.remove(a)
print('List with Remove Element : ',l1)
elif ch=='6':
print(l1)
b=int(input('Enter element in list to know
index of it :'))
l1.index(b)
print('Index is :',l1.index(b))
elif ch=='7':
print(l1)
f=int(input('Enter sequence no of list
element which u want POP :'))
Created By : SANKET B. JETHAVA
l1.pop(f-1)
print(l1)
elif ch=='8':
print(l1)
l1.sort()
print('Sorted list is : ',l1)
elif ch=='9':
print(l1)
l1.reverse()
print('Reverse list is : ',l1)
elif ch=='10':
print(l1)
elif ch=='0':
break;
print('=================================================
====================================================')
#...............................END LIST...........................
elif ch=='2':
#-------------------------------START TUPLE-------------------------------------
-------
Created By : SANKET B. JETHAVA
t1=(1,123,1234,12255,12,13)
while(1):
print('1. Length of Tuple')
print('2. Delete tuple')
print('3. Check No is in tuple or not')
print('4. Find Minimum from tuple')
print('5. Find Maximum from tuple')
print('6. Display Tuple')
print('0. Stop')
ch=input('Enter Your Choice : ')
if ch=='1':
print('Length of tuple is : ',len(t1))
elif ch=='2':
del t1
print('Tuple is delete successfully')
elif ch=='3':
b=int(input('Enter to check inputed
bumber item is in tuple or not : '))
if b in t1:
print(b,' is in tuple')
Created By : SANKET B. JETHAVA
else:
print('Not in tuple')
elif ch=='4':
print(t1)
print('Minimum number in list is :
',min(t1))
elif ch=='5':
print(t1)
print('Maximum number in list is :
',max(t1))
elif ch=='6':
print('Tuple is : ',t1)
elif ch=='0':
break;
print('=================================================
====================================================')
#-------------------------------END TUPLE----------------------------------------
----
elif ch=='3':
#++++++++++++++++++++++++++++++++++++++++++DICTIONARY
START++++++++++++++++++++++++++++
Created By : SANKET B. JETHAVA
d={}
while(1):
print('1. Add in Dictionary')
print('2. Display Dictionary')
print('3. Remove from Dictionary')
print('4. Delete Whole Dictionary')
print('5. Clear all element in Dictionary')
print('0. Stop')
ch=input('Enter Your Choice : ')
if ch=='1':
n=int(input('Enter how many values in
Dictionary u want : '))
for i in range(1,n+1):
k=input('Enter the key - '+str(i)+' = ')
v=input('Enter the value - '+str(i)+' = ')
d[k]=v
elif ch=='2':
print(d)
elif ch=='3':
Created By : SANKET B. JETHAVA
r=input('Enter key for remove value : ')
del d[r]
elif ch=='4':
del d
elif ch=='5':
d.clear()
elif ch=='0':
break;
print('====++++@@@@++++@@@@========++++@@@@+++
+@@@@========++++@@@@++++@@@@========++++@@@@
++++@@@@========++++@@@@++++@@@@====')
#++++++++++++++++++++++++++++++++++++++++++DICTIONARY
END++++++++++++++++++++++++++++
elif ch=='4':
#==================================STRING
END==================================
st=input('Enter a String : ')
while(1):
print('1. Display String')
Created By : SANKET B. JETHAVA
print('2. Length of String')
print('3. Check Type')
print('4. Split')
print('0. Stop')
ch=input('Enter Your Choice : ')
if ch=='1':
print('String is : '+st)
elif ch=='2':
print('Sting Length is :',len(st))
elif ch=='3':
print(type(st))
elif ch=='4':
print('Spliteed String is : ',end='')
print(st.split())
elif ch=='0':
break;
print('=================================================
====================================================')
#==================================STRING
END==================================
Created By : SANKET B. JETHAVA
elif ch=='0':
break;
print('====++++@@@@'*10)
#A program to read CSV file and upload data into table
import pandas as pd
import mysql.connector as db
d=pd.read_csv("test.csv")
name=list(d["name"])
id=list(d["id"])
price=list(d["price"])
con=db.connect(host="localhost",database="test",user="root",passw
ord="")
cur=con.cursor()
for i in range(len(d["id"])):
s="insert into food values (%d,'%s',%d)" %(id[i],name[i],price[i])
cur.execute(s)
con.commit()
con.close()
Created By : SANKET B. JETHAVA