0% found this document useful (0 votes)
2 views

Python-Codes

The document provides various Python programming code examples covering topics such as inheritance, polymorphism, constructors, variable declaration, array operations, control statements, and GUI programming with Tkinter. Each section includes sample code snippets demonstrating the respective concepts. It serves as a comprehensive reference for basic Python programming techniques and GUI widget usage.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Python-Codes

The document provides various Python programming code examples covering topics such as inheritance, polymorphism, constructors, variable declaration, array operations, control statements, and GUI programming with Tkinter. Each section includes sample code snippets demonstrating the respective concepts. It serves as a comprehensive reference for basic Python programming techniques and GUI widget usage.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Important Programing Codes

Q. Python Program for Inheritance?


class Animal:
def speak(self):
print("Animal Speaking")
#child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self):
print("dog barking")
d = Dog()
d.bark()
d.speak()

Q. Python Program for Polymorphism?


class India():
def capital(self):
print("New Delhi is the capital of India.")
def language(self):
print("Hindi is the most widely spoken language of
India.")
def type(self):
print("India is a developing country.")
class USA():
def capital(self):
print("Washington, D.C. is the capital of USA.")
def language(self):
print("English is the primary language of USA.")
def type(self):
print("USA is a developed country.")
obj_ind = India()
obj_usa = USA()
for country in (obj_ind, obj_usa):
country.capital()
country.language()
country.type()

Q. Python Program for Constructor?


class Employee:
def __init__(self, name, id):
self.id = id
self.name = name
def display(self):
print("ID: %d \nName: %s" % (self.id, self.name))
emp1 = Employee("John", 101)
emp2 = Employee("David", 102)

R.C.Patel I.M.R.D, Shirpur


Important Programing Codes

# accessing display() method to print employee 1 information


emp1.display()
# accessing display() method to print employee 2 information
emp2.display()

Q.Variable Declaration in python?

add()
a=2
def add():
b=3
c=a+b
print(c)
Output: 5

Q. Python Program to find sum of array?


def _sum(arr):
sum=0
for i in arr:
sum = sum + i
return(sum)
arr=[ ]
arr = [12, 3, 4, 15]
n = len(arr)
ans = _sum(arr)
print ('Sum of the array is ', ans)

Q. Python Program to find largest element in an array?


def largest(arr,n):

max = arr[0]
for i in range(1, n):
if arr[i] > max:
max = arr[i]
return max

arr = [10, 324, 45, 90, 9808]


n = len(arr)
Ans = largest(arr,n)
print ("Largest in given array is",Ans)

Q. Python Program for array rotation?


def rotateArray(arr, n, d):

R.C.Patel I.M.R.D, Shirpur


Important Programing Codes

temp = []
i = 0
while (i < d):
temp.append(arr[i])
i = i + 1
i = 0
while (d < n):
arr[i] = arr[d]
i = i + 1
d = d + 1
arr[:] = arr[: i] + temp
return arr
arr = [1, 2, 3, 4, 5, 6, 7]
print("Array after left rotation is: ", end=' ')
print(rotateArray(arr, len(arr), 2))

Q. Python Program for If Else Statement?


if True:
print "True"
else:
print "False"

Q. Python Program for While Loop?


count = 0
while (count < 9):
print 'The count is:', count
count = count + 1

print "Good bye!"

Q. Python Program for For Loop?

for letter in 'Python': # First Example


print 'Current Letter :', letter
fruits = ['banana', 'apple', 'mango']
for fruit in fruits: # Second Example
print 'Current fruit :', fruit

print "Good bye!"

Q. Python Program for Nested Loop?


i = 2

R.C.Patel I.M.R.D, Shirpur


Important Programing Codes

while(i < 100):


j = 2
while(j <= (i/j)):
if not(i%j): break
j = j + 1
if (j > i/j) : print i, " is prime"
i = i + 1
print "Good bye!"

Q. Python Program for Break Statement?


for letter in 'Python': # First Example
if letter == 'h':
break
print 'Current Letter :', letter
var = 10 # Second Example
while var > 0:
print 'Current variable value :', var
var = var -1
if var == 5:
break

print "Good bye!"

Q. Python Program for Multi-line Statement?


total = item_one + \
item_two + \
item_three
Example:
days = ['Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday']

Q. Python Program for Assigning Values to Variables?


counter = 100 # An integer assignment
miles = 1000.0 # A floating point
name = "John" # A string

print counter
print miles
print name

Q. Python Program for Dictionary?

R.C.Patel I.M.R.D, Shirpur


Important Programing Codes

dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}

print dict['one'] # Prints value for 'one' key


print dict[2] # Prints value for 2 key
print tinydict # Prints complete dictionary
print tinydict.keys() # Prints all the keys
print tinydict.values() # Prints all the values

Python GUI Programming – Python Tkinter


Q. Python Program for GUI Architecture?
1) GUI Architecture :
>>> import tkinter
>>> top=tkinter.Tk()
>>> top.mainloop()

2) Python Tkinter Widgets - Button :


>>> from tkinter import *
>>> top=Tk()
>>> top.geometry('600x200'
''
>>> def helloCallBack():
msg=messagebox.showinfo("Hello, User","Hello, Guest")
>>> B=Button(top,text="Initiate",command=helloCallBack)
>>> B.place(x=300,y=100)

3) Python Tkinter Widgets - Canvas :

>>> from tkinter import *


>>> from tkinter import messagebox
>>> top=Tk()
>>> C=Canvas(top,bg="cyan",height=100,width=100)
>>> coord=10,50,90,70
>>> arc=C.create_arc(coord,start=0,extent=97,fill='black')
>>> line=C.create_line(10,10,50,70,fill='white')
>>> C.pack()

4) Python Tkinter Widgets - Checkbutton:

>>> from tkinter import *


>>> top=Tk()

R.C.Patel I.M.R.D, Shirpur


Important Programing Codes

>>> CheckVar1=IntVar()
>>> CheckVar2=IntVar()
>>> C1=Checkbutton
>>> C1=Checkbutton(top,text="Pizza",variable=CheckVar1,onvalue=1,offvalue=0,height=5,width=20)
>>> C2=Checkbutton(top,text="Fries",variable=CheckVar2,onvalue=1,offvalue=0,height=5,width=20)
>>> C1.pack()
>>> C2.pack()

5) Python Tkinter Widgets - Entry:

>>> from tkinter import *


>>> top=Tk()
>>> L1=Label(top,text="Enrolment Number")
>>> L1.pack(side=LEFT)
>>> E1=Entry(top,bd=3)
>>> E1.pack(side=RIGHT)

6) Python Tkinter Widgets - Frame:

>>> from tkinter import *


>>> top=Tk()
>>> frame=Frame(top)
>>> frame.pack()
>>> frametwo=Frame(top)
>>> frametwo.pack(side=BOTTOM)
>>> redbutton=Button(frame,text="One",fg="red")
>>> redbutton.pack(side=LEFT)
>>> bluebutton=Button(frame,text="Two",fg="blue")
>>> bluebutton.pack(side=LEFT)
>>> greenbutton=Button(frametwo,text="Three",fg="green")
>>> greenbutton.pack(side=BOTTOM)

7) Python Tkinter Widgets - Listbox:

>>> from tkinter import *


>>> top=Tk()
>>> LB1=Listbox(top)
>>> LB1.insert(1,"Hindi")
>>> LB1.insert(2,"Romanian")
>>> LB1.insert(3,"English")
>>> LB1.insert(4,"Gujarati")
>>> LB1.pack()

8) Python Tkinter Widgets – Menu Button:

>>> from tkinter import *


>>> top=Tk()

R.C.Patel I.M.R.D, Shirpur


Important Programing Codes

>>> mb=Menubutton(top,text="style",relief=RAISED)
>>> mb.grid()
>>> mb.menu=Menu(mb,tearoff=0)
>>> mb["menu"]=mb.menu
>>> balayageVar=IntVar()
>>> sombreVar=IntVar()
>>> mb.menu.add_checkbutton(label='Balayage',variable=balayageVar)
>>> mb.menu.add_checkbutton(label='Sombre',variable=sombreVar)
>>> mb.pack()

9) Python Tkinter Widgets – Radiobutton:


>>> from tkinter import *
>>> def sel():
selection=f"Enjoy your {var.get()}"
label.config(text=selection)
>>> top=Tk()
>>> var=StringVar()
>>> R1=Radiobutton(top,text="pizza
slice",variable=var,value='pizza',command=sel
>>> R1.pack(anchor=W)
>>> R2=Radiobutton(top,text="burger",variable=var,value='burger',command=sel)
>>> R2.pack(anchor=W)
>>> R3=Radiobutton(top,text="fries",variable=var,value='fries',command=sel)
>>> R3.pack(anchor=W)
>>> label=Label(top)
>>> label.pack()

10) Python Tkinter Widgets – Scrollbar:


>>> from tkinter import *
>>> top=Tk()
>>> scrollbar=Scrollbar(top)
>>> scrollbar.pack(side=RIGHT,fill=X)
>>> scrollbar.pack(side=RIGHT,fill=Y)
>>> list=Listbox(top,yscrollcommand=scrollbar.set)
>>> for line in range(22):
list.insert(END,f"Line {str(line)}")
>>> list.pack(side=LEFT,fill=BOTH)
>>> scrollbar.config(command=list.yview)

R.C.Patel I.M.R.D, Shirpur

You might also like