Skip to main content

Pyhton Programming

Programs to Read and Write Files

#program to read files
f=open("abc.txt",'r')
f.read()
f.close

#program for writing files
f=open("abc.txt",'w')
f.write("HEllO WOrld")
f.close

#programs based on read and write files
a=open("text.txt","w")
a.write(“welcome to python”)
a.write(“This my first line\n”)
a.write(“This is my second line\n”)
a.write(“This is third line\n”)
a.close()

#Program to write lines of text 
Obj=open(“text.txt”,”w”)
Lot=[“Python is the software “,”\n which is used for create and run the program “,”\n Python programming language”]
Obj.writelines(Lot)
Obj.close() 

#Create a program to first check to see if the file name is exist .So if it will give an error massage if it will not create the file 
import os
def create_file()
        if os.path.isfile(“text.txt”):
             print(“file already exists”)
        else:
              f=open(“text.txt”,”w”)
              f.write(“create a new text file”)
              f.close()
create_file()

#write a python program to read an entire text file.
def file_read(fname):
    txt = open(fname)
    print(txt.read())
file_read("text.txt")

#write a python program to append text to a file and display the text
def file_read(fname):
    from itertools import islice
    with open(fname,"w")as myfile:
        myfile.write("python exercise\t")
        myfile.write("Java exercise\t")
    txt=open(fname)
    print(txt.read())
file_read("abc.txt")   

Programs to demonstrate exception handling

#Demonstrate Exception.
try:
  fh = open("fycs.txt", "w")
  fh.write("This is my test file for exception handling!!")
finally:
  print ("Error: can\'t find file or read data")

#Open a file and write  the file comes out Gracefully.
try:
   fh = open("fycs7.txt", "r+")
   fh.write("This is my test file for exception handling!!")
except IOError:
   print ("Error: can\'t find file or read data" )
else:

   print ("Written content in the file successfully")

#Program to take input and print integer is Valid or Not.
while True:
  try:
    n=int(input("Enter an integer: "))    
  except ValueError:
      print("You have entered Wrong integer.")
  else:
      print("You have entered Valid integer.")

Programs to demonstrate use of regular expressions

Below program must be executed in python shell

Import re
Print(re.split(r’ \s*’,’my first RE program’))

Import re
Print(re.split(r’[a-e]’,’my beautiful daughter’))

Import  re
Print(‘\nfind the digits’)
Print(re.findall(r’ \d’,’meera 18927 road’))
Print (‘n\find the non-digits’)
Print(re.findall(r’\D’,’meera 18927 road’))
Print(‘\nfind the non-space’)
Print(re.findall(r’\s’,’meera 18927 road’))


Import  re
Print(‘\nfind the digits’)

Print(re.findall(r’\d{1,3}\s\w+’,’meera 18927 road’))

Programs to show draw shapes and GUI controls

#create line with rectangle
from tkinter import*
root=Tk()
w=Canvas(root,width=200,height=100,bg="red")
w.pack()
w.create_line(0,0,200,100)
w.create_line(0,100,200,0,fill="red",dash=(4,4))
w.create_rectangle(50,25,150,75,fill="blue")

root.mainloop()

#program to create arc
import tkinter
import tkinter.messagebox
top=tkinter.Tk()
c=tkinter.Canvas(top,bg="blue",height="250",width="300")
coord=10,50,240,210
arc=c.create_arc(coord,start=0,extent=150,fill="red")
c.pack()

top.mainloop()

#program for creating line
from tkinter import*
root=Tk()
w=Canvas(root,width=300,height=300,bg="red")
w.pack()
w.create_line(0,20,250,20,fill="yellow")
root.mainloop()

#program to create two lines
from tkinter import*
root=Tk()
l=Canvas(root,width=200,height=100,bg="red")
l.pack()
l.create_line(0,0,100,80,fill="blue")
l.create_line(0,0,80,100,fill="blue")
mainloop()

#program to create rectangle
from tkinter import*
master=Tk()
w=Canvas(master,width=200,height=100)
w.pack()
w.create_rectangle(50,25,150,75,fill="black")
mainloop()

#program to create two rectangles of colour yello and green
from tkinter import*
window=Tk()
s=Canvas(window,width=300,height=300)
s.pack()
s.create_rectangle(50,20,150,150,fill="#476042")
s.create_rectangle(70,50,200,230,fill="yellow")

#create a main window
fromtkinter import *
root=Tk()
root.mainloop()

#display variable using text variable option 
fromtkinter import *
root=Tk()
var=StringVar()
var.set("LONE_WOLFS")
l=Label(root,textvariable=var)
l.pack()

#display label and option 
fromtkinter import *
root=Tk()
L1=Label(root, text="Email")
L1.pack()
L2=Label(root, text="Password")
L2.pack()
b1=Button(root,text="Login")
b1.pack()
b2=Button(root,text="SignUp")
b2.pack()
root.mainloop()

#display label, entry box and button
fromtkinter import *
root=Tk()
L1=Label(root, text="Email")
L1.pack()
e1=Entry(root, bd=5)
e1.pack()
L2=Label(root, text="Password")
L2.pack()
e2=Entry(root, bd=5)
e2.pack()
b1=Button(root,text="Login")
b1.pack()
b2=Button(root,text="Cancel")
b2.pack()
root.mainloop()

#loading application
Using Pack() method
fromtkinter import *
root=Tk()
L=Label(root, text="FACEBOOK LOGIN", font=("ALGERIAN", 20), fg="BLUE")
L.pack()
L1=Label(root, text="Email")
L1.pack()
e1=Entry(root, bd=5)
e1.pack()
L2=Label(root, text="Password")
L2.pack()
e2=Entry(root, bd=5)
e2.pack()
b1=Button(root,text="Login")
b1.pack()
b2=Button(root,text="Cancel")
b2.pack()
root.mainloop()

#using grid method
fromtkinter import *
root=Tk()
L=Label(root, text="FACEBOOK LOGIN", font=("ALGERIAN", 20), fg="BLUE")
L.grid(column=1)
L1=Label(root, text="Email")
L1.grid(row=1)
L2=Label(root, text="Password")
L2.grid(row=2)
e1=Entry(root, bd=5)
e1.grid(row=1, column=1)
e2=Entry(root, bd=5)
e2.grid(row=2, column=1)
b1=Button(root,text="Login", fg="white", bg="GREEN")
b1.grid(column=1)
b2=Button(root,text="Cancel",fg="white", bg="RED")
b2.grid(column=1)
root.mainloop()

#textbox
fromtkinter import *
root = Tk()
T = Text(root, height=3, width=30)
T.pack()
T.insert(END, "Hi Friend\nWe are the Friends FOREVER\nThe Lone Wolfs.")
mainloop()

#entry box
fromtkinter import *
top = Tk()
L1 = Label(top, text="User Name")
L1.pack( side = LEFT)
E1 = Entry(top, bd =5)
E1.pack(side = RIGHT)
top.mainloop()

#frame
fromtkinter import*
root=Tk()
frame=Frame(root)
frame.pack()
bottomframe=Frame(root)
bottomframe.pack(side=BOTTOM)
red=Button(frame,text="red",fg="red")
red.pack(side=LEFT)
green=Button(frame,text="Green",fg="green")
green.pack(side=LEFT)
blue=Button(frame,text="Blue",fg="blue")
blue.pack(side=LEFT)
black=Button(bottomframe,text="Black",fg="black")
black.pack(side=LEFT)
root.mainloop()

#loading application using messagebox
fromtkinter import *
fromtkinter import messagebox
root=Tk()
def login():
username=e1.get()
password=e2.get()
if username="sandyjais" and password="Sudhir":
messagebox.showinfo("login","You Have Logged In Successfully.")
else:
messagebox.showinfo("login","Login Failed.")
def cancel():
root.destroy()
Label(root, text="FACEBOOK LOGIN", font=("ALGERIAN", 20), fg="BLUE").grid(column=1)
Label(root, text="username").grid(row=1)
e1=Entry(root, bd=5)
e1.grid(row=1, column=1)
Label(root, text="Password").grid(row=2)
e2=Entry(root, bd=5)
e2.grid(row=2, column=1)
b1=Button(root,text="Login", command=login)
b1.grid(row=3,column=1)
b2=Button(root,text="Cancel",command=cancel)
b2.grid(row=4,,column=1)
root.mainloop()

#checkbotton
fromtkinter import *
top = Tk()
CheckVar1 = IntVar()
CheckVar2 = IntVar()
C=Label(top,text="Select Your Favourite Programming Language.",fg="RED")
C.pack()
C1=Checkbutton(top,text="Python",variable=CheckVar1,onvalue=1,offvalue=0,height=5,
width=20)
C2=Checkbutton(top,text="Java",variable=CheckVar2,onvalue=1,offvalue=0,height=5, width=20)
C1.pack()
C2.pack()
top.mainloop()

#radiobutton
fromtkinter import *
defsel():
selection="You selected the option"+str(Var.get())
label.config(text=selection)
root=Tk()
Var=IntVar()
R1=Radiobutton(root,text="option1",variable=Var,value=1,command=sel)
R1.pack(anchor='c')
R2=Radiobutton(root,text="option2",variable=Var,value=2,command=sel)
R2.pack(anchor='c')
label=Label(root)
label.pack()
mainloop()

#messagebox
fromtkinter import *
fromtkinter import messagebox
root=Tk()
messagebox.showinfo("LOGIN","WELCOME SANDY_JAIS")
messagebox.showwarning("LOGIN","LOGIN FAILED.")
root.mainloop()

#listbox
fromtkinter import*
fromtkinter import messagebox
root=Tk()
l1=Listbox(root,relief=RAISED,selectmode="single")
l1.insert(1,"python")
l1.insert(2,"php")
l1.insert(3,"c")
l1.insert(4,"java")
l1.insert(5,"ruby")
l1.pack()
root.mainloop()

#messagebox
fromtkinter import*
root=Tk()
var=StringVar()
label=Message(root,textvariable=var,relief=RAISED)
label.pack()
var.set("welcome\nThe world of world of PROGRAMMING.")
root.mainloop()

#illsutrate the use of relief to widget
fromtkinter import*
root=Tk()
b1=Button(root,text="FLATE",relief=FLAT)
b2=Button(root,text="RAISED",relief=RAISED)
b3=Button(root,text="GROOVE",relief=GROOVE)
b4=Button(root,text="RIDGE",relief=RIDGE)
b5=Button(root,text="SUNKEN",relief=SUNKEN)
b1.pack()
b2.pack()
b3.pack()
b4.pack()
b5.pack()
root.mainloop()

#event handler using mousebutton
fromtkinter import *
root=Tk()
defcallback(event):
frame.focus_set()
print("clicked at",event.x,event.y)
frame=Frame(root,width=300,height=300,bg="RED")
frame.bind("<Button-1>", callback)
frame.pack()
mainloop()

#event handler using keyboard buttons 
fromtkinter import *
root=Tk()
def key(event):
print("Pressed",repr(event.char))
defcallback(event):
frame.focus_set()
print("clicked at",event.x,event.y)
frame=Frame(root,width=300,height=300,bg="RED")
frame.bind("<Key>",key)
frame.bind("<Button-1>", callback)
frame.pack()
mainloop()

#spinbox.
fromtkinter import *
master = Tk()
w = Spinbox(master, from_=0, to=10)
w.pack()
mainloop()

#spinbox color changing
fromtkinter import*
root=Tk()
t1=('green','red','blue','gray')
def colour():
str=w.get()
w.config(bg=str)
w=Spinbox(root,from_=0,to=10,value=t1,command=colour)
w.pack()
root.mainloop()

#create an application using different widget of tkinter
fromtkinter import *
root=Tk()
L=Label(root, text="FACEBOOK SIGNUP", font=("ALGERIAN", 20), fg="BLUE")
L.grid(row=1,column=3)

L1=Label(root, text="Full_Name")
L1.grid(row=2,column=1)
e1=Entry(root, bd=5)
e1.grid(row=2, column=2)
e2=Entry(root, bd=5)
e2.grid(row=2, column=3)
e3=Entry(root, bd=5)
e3.grid(row=2, column=4)

y=Label(root, text="LastName")
y.grid(row=3,column=2)
y1=Label(root, text="FirstName")
y1.grid(row=3,column=3)
y2=Label(root, text="MiddleName")
y2.grid(row=3,column=4)

L2=Label(root, text="Username")
L2.grid(row=4,column=1)
e4=Entry(root, bd=5)
e4.grid(row=4, column=2)

z1=Label(root, text=" ")
z1.grid(row=5,column=1)

L3=Label(root, text="Password")
L3.grid(row=6,column=1)
e5=Entry(root, bd=5)
e5.grid(row=6, column=2)

z2=Label(root, text=" ")
z2.grid(row=7,column=1)

L4=Label(root, text="Confirm Password")
L4.grid(row=8,column=1)
e6=Entry(root, bd=5)
e6.grid(row=8, column=2)

z3=Label(root, text=" ")
z3.grid(row=9,column=1)
L5=Label(root, text="Date of Birth")
L5.grid(row=10,column=1)
e7=Entry(root, bd=5)
e7.grid(row=10, column=2)
L6=Label(root, text="(dd/mm/yyyy)")
L6.grid(row=11,column=2)

z4=Label(root, text=" ")
z4.grid(row=9,column=1)

L5=Label(root, text="Gender")
L5.grid(row=12,column=1)

Var=IntVar()
R1=Radiobutton(root,text="Male",variable=Var,value=1)
R1.grid(row=12,column=2)
R2=Radiobutton(root,text="Female",variable=Var,value=2)
R2.grid(row=13,column=2)
R3=Radiobutton(root,text="Other",variable=Var,value=3)
R3.grid(row=14,column=2)

z5=Label(root, text=" ")
z5.grid(row=15,column=1)

L6=Label(root, text="Mobile_Number")
L6.grid(row=16,column=1)
e8=Entry(root, bd=5)
e8.grid(row=16, column=2)

z6=Label(root, text=" ")
z6.grid(row=17,column=1)

L7=Label(root, text="Location")
L7.grid(row=18,column=1)

t1=('India','UK','USA','Pakistan')
def colour():
str=w.get()
w.config(text=str)

w=Spinbox(root,from_=0,to=4,value=t1,command=colour)
w.grid(row=18,column=2)

z7=Label(root, text=" ")
z7.grid(row=19,column=1)
CheckVar1 = IntVar()
CheckVar2 = IntVar()
C1=Checkbutton(root,text="Accept terms and Conditions",variable=CheckVar1,onvalue=1,offvalue=0) 
C1.grid(row=20,column=2)

z8=Label(root, text=" ")
z8.grid(row=21,column=1)

b1=Button(root,text="SIGNUP", fg="white", bg="GREEN")
b1.grid(row=22,column=2)
b2=Button(root,text="CANCEL",fg="white", bg="RED")
b2.grid(row=22,column=3)
root.mainloop()

#create an oval
fromtkinter import *
root=Tk()
w=Canvas(root, width=300,height=300,bg="GRAY")
w.pack()
w.create_oval(60,60,250,250,fill="RED")
root.mainloop()

#create a face using canvas
fromtkinter import *
root=Tk()
f=Canvas(root, width=300,height=300)
f.create_oval(40,40,254,254,fill="red")
f.create_oval(90,80,113,101,fill="blue")
f.create_oval(193,80,212,103,fill="blue")
f.create_oval(87,199,199,209,fill="blue")
f.pack()
mainloop()

#program for mousehandler
from tkinter import *
root=Tk()
def callback(event):
    frame.focus_set()
    print("clicked at",event.x,event.y)
frame=Frame(root,width=300,height=300,bg="RED")
frame.bind("<Button-1>", callback)
frame.pack()
mainloop()

#program for keyboard handling
from tkinter import *
root=Tk()
def key(event):
    print("Pressed",repr(event.char))
def callback(event):
    frame.focus_set()
    print("clicked at",event.x,event.y)
frame=Frame(root,width=300,height=300,bg="RED")
frame.bind("<Key>",key)
frame.bind("<Button-1>", callback)
frame.pack()
mainloop()

#creating a table
import os
import sqlite3
conn1=sqlite3.c
onnect('sample_database')
csr=conn1.cursor()
str='create table employee1(E_id integer,name text)'
csr.execute(str)
conn1.close()

#inserting a values in table
import os
import sqlite3
conn1=sqlite3.connect('sample_database')
csr=conn1.cursor()
str1="insert into student values(1003,'sudhir')"
str2="insert into student values(1004,'Ashwin')"
str3="insert into student values(1005,'Deepak')"
str4="insert into student values(1006,'ramesh')"
try:
     csr.execute(str1)
     csr.execute(str2)
     csr.execute(str3)
     csr.execute(str4)
     conn1.commit()
except:
     conn1.rollback()
     conn1.close()

#Selecting from Student and printing Roll_no and Name column .
import os
import sqlite3
conn1=sqlite3.connect('sample_database')
csr=conn1.cursor()
sql="SELECT * FROM STUDENT"
try:
     csr.execute(sql)
     result=csr.fetchall()
     print("ROLL_NO   NAME   ")
     for row in result:
          rno=row[0]
          sname=row[1]
          print("%d      %s      "%(rno,sname))
except:
     print"Error:unable to fetch data"
conn1.close()

#Connect mysql.connector and give statement.
import mysql.connector
from mysql.connector import Error
try:
     conn=mysql.connector.connect(host='localhost',
                                  database='ritesh',
                                  user='root',
                                  password='')
     if conn.is_connected():
          print('connected to Mysql database')
     csr=conn.cursor()
     str="select * from Item"
     csr.execute(str)
     result=csr.fetchall()
     print("INO      INAME            PRICE          QUANTITY")
     for row in result:
          ino=row[0]
          iname=row[1]
          p=row[2]
          q=row[3]
          print(" %d      %s       %d             %d  "%(ino,iname,p,q))
except Error as e:
     print(e)
finally:
     conn.close()


#Sending mail using SMTP
import smtplib
# creates SMTP session
s = smtplib.SMTP('smtp.gmail.com', 587)
# start TLS for security
s.starttls()
# Authentication
s.login("sender_email_id", "sender_email_id_password") 
# message to be sent
message = "Message_you_need_to_send"
# sending the mail
s.sendmail("sender_email_id", "receiver_email_id", message)
# terminating the session
s.quit()

#Sending mail to multiple persons.
import smtplib 
# list of email_id to send the mail
li = ["xxxxx@gmail.com", "yyyyy@gmail.com"]
for i in range(len(li)):
    s = smtplib.SMTP('smtp.gmail.com', 587)
    s.starttls()
    s.login("sender_email_id", "sender_email_id_password")
    message = "Message_you_need_to_send"
    s.sendmail("sender_email_id", li[i], message)
    s.quit()




















Comments