1
PYTHON PROGRAMMING LAB
Exercise 1 – Basics
a) Running instructions in Interactive interpreter and a Python Script
Running Instructions in Interactive Interpreter
>>> print("welcome to Python")
welcome to Python
>>> a=10
>>> b=20
>>> sum=a+b
>>> print a
10
>>> print b
20
>>> print sum
30
>>> print("sum is",sum)
('sum is', 30)
>>> print " sum is",sum
sum is 30
>>> print('sum is',sum)
('sum is', 30)
>>> a=input("enter a value:")
enter a value:34
>>> print(a)
34
>>>
Running Instructions in an Python Script
Write a program [Link] that takes 2 numbers as command line arguments and prints its sum.
Source Code:
x=input("Enter x value:")
y=input("Enter y value:")
sum=x+y
2
print " Sum of x and y is : ",sum
out-put 1
Enter x value:34
Enter y value:78
Sum of x and y is : 112
out-put 2
Enter x value:56
Enter y value:23
Sum of x and y is : 79
b) Write a program to purposefully raise Indentation Error and Correct it
Source Code:-
Python provides no braces to indicate blocks of code for class and function definitions or flow control.
Blocks of code are denoted by line indentation, which is rigidly enforced.
The number of spaces in the indentation is variable, but all statements within the block must be indented
the same amount. For example:
Thus, in Python all the continuous lines indented with same number of spaces would form a block. The
following example has various statement blocks:
Note: Do not try to understand the logic at this point of time. Just make sure you
understood various blocks even if they are without braces.
3
4
Exercise 2 - Operations
a) Write a program to compute distance between two points taking input from the user
(Pythagorean Theorem)
Source code:-
from math import sqrt
x1=input("Enter x1 value :")
x2=input("Enter x2 value :")
y1=input("Enter y1 value :")
y2=input("Enter y2 value :")
distance=sqrt((x2-x1)**2+(y2-y1)**2)
print "Two points x1 y1 and x2 y2 are :",x1,y1,"and",x2,y2
print "Distance b/w two points is:",distance
out-put 1
Enter x1 value :2
Enter x2 value :5
Enter y1 value :3
Enter y2 value :8
Two points x1 y1 and x2 y2 are : 2 3 and 5 8
Distance b/w two points is: 5.83095189485
out-put 2
Enter x1 value :5
Enter x2 value :9
Enter y1 value :3
Enter y2 value :7
Two points x1 y1 and x2 y2 are : 5 3 and 9 7
Distance b/w two points is: 5.65685424949
5
b) Write a program [Link] that takes 2 numbers as command line arguments and prints its sum.
Source Code:
x=input("Enter x value:")
y=input("Enter y value:")
sum=x+y
print " Sum of x and y is : ",sum
out-put 1
Enter x value:34
Enter y value:78
Sum of x and y is : 112
out-put 2
Enter x value:56
Enter y value:23
Sum of x and y is : 79
Exercise - 3 Control Flow
a) Write a Program for checking whether the given number is a even number or
not.
Source Code:
n=input("Enter a number:")
if(n%2==0):
print "The number is Even"
else:
print "The number is not Even"
out-put 1
Enter a number:28
6
The number is Even
out-put 2
Enter a number:53
The number is not Even
b) Using a for loop, write a program that prints out the decimal equivalents of 1/2,
1/3, 1/4, . . . ,1/10
Source Code:
from fractions import Fraction
for i in range(2,11):
a=Fraction(1,i)
print float(a)
out-put
0.5
0.333333333333
0.25
0.2
0.166666666667
0.142857142857
0.125
0.111111111111
0.1
c) Write a program using a for loop that loops over a sequence. What is
sequence ?
7
Explanation:- We can generate a sequence of numbers using range() function. range(10) will
generate numbers from 0 to 9 (10 numbers).
We can also define the start, stop and step size as range(start,stop,step size). step size defaults to 1
if not provided.
This function does not store all the values in memory, it would be inefficient. So it remembers
the start, stop, step size and generates the next number on the go.
Source Code:
for i in range(10):
print i
print "---------------"
for i in range(1,10):
print i
print "---------------"
for i in range(4,10):
print i
print "---------------"
for i in range(3,10,2):
print i
print "---------------"
x=[25,1,7,6]
for i in x:
print i
out-put
0
8
---------------
---------------
8
9
---------------
---------------
25
d) Write a program using a while loop that asks the user for a number, and prints a countdown from
that number to zero.
Source Code:
n=input("Enter n value :")
while n>=0:
print n
n=n-1
out-put 1
Enter n value :5
0
10
out-put 2
Enter n value :10
10
Exercise 4 - Control Flow – Continued
a) Find the sum of all the primes below two million.
Source code:-
sum=0
for num in range(2,2000000):
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
sum=sum+num
print "sum of all Prime numbers between 2 and 2000000 is :",sum
out-put:-
sum of all Prime numbers between 2 and 2000000 is : 1709600813
11
b) Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting
with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the
sum of the even-valued terms.
Source code:-
x=0
y=1
z=x+y
sum=0
while (z<4000000):
if(z%2==0):
sum=sum+z
x=y
y=z
z=x+y
print "Sum of the even valued fibonacci sequence upto 10 is",sum
out-put:-
Sum of the even valued fibonacci sequence upto 10 is 4613732
Exercise - 5 - DS
a) Write a program to count the numbers of characters in the string and store them in a
dictionary data structure
Source code:-
x=input("enter the string in x:")
y=input("enter the string in y:")
dict1={x:len(x),y:len(y)}
print dict1
out-put 1
enter the string in x:'msr'
enter the string in y:'satyam'
{'satyam': 6, 'msr': 3}
out-put 2
enter the string in x:"cse"
enter the string in y:"python"
12
{'cse': 3, 'python': 6}
b) Write a program to use split and join methods in the string and trace a birthday with a
dictionary data structure.
Source code:-
str="abc 12-09-1992 vij ap india"
list=[Link]()
print list
s="->"
seq=("a","b","c","d")
print [Link](seq)
dict={"name":"abc",
"dob":"12-09-1992",
"city":"vij",
"state":"ap",
"country":"india"
}
print dict
for i in dict:
if(i=="dob"):
print dict[i]
out-put
['abc', '12-09-1992', 'vij', 'ap', 'india']
a->b->c->d
{'dob': '12-09-1992', 'city': 'vij', 'state': 'ap', 'name': 'abc', 'country': 'india'}
12-09-1992
13
Exercise - 6 DS – Continued
a) Write a program combine_lists that combines these lists into a dictionary.
Source code:-
keys=[1,2,3,4]
print keys
values=[10,20,30,40]
print values
dictionary=dict(zip(keys,values))
print dictionary
out-put
[1, 2, 3, 4]
[10, 20, 30, 40]
{1: 10, 2: 20, 3: 30, 4: 40}
b) Write a program to count frequency of characters in a given file. Can you use character
frequency to tell whether the given file is a Python program file, C program file or a text file?
Source code:-
fname = input("Enter file name: ")
l=input("Enter letter to be searched:")
k=0
with open(fname, 'r') as f:
for line in f:
words = [Link]()
for i in words:
for letter in i:
if(letter==l):
k=k+1
print("Occurrences of the letter:")
print(k)
sample output:-
Case 1:
Contents of file:
14
hello world hello
hello
Output:
Enter file name: [Link]
Enter letter to be searched:o
Occurrences of the letter:
5
Case 2:
Contents of file:
hello world
test
test test
Output:
Enter file name: [Link]
Enter letter to be searched:e
Occurrences of the letter:
6
Exercise - 7 Files
a) Write a program to print each line of a file in reverse order.
[Link]
hi
how r
u ra
Source code:-
filename=input("Enter file name: ")
for line in reversed(list(open(filename))):
print([Link]())
output:
Enter file name: "[Link]"
u ra
how r
hi
15
b) Write a program to compute the number of characters, words and lines in a file.
fname = input("Enter the name of the file:")
infile = open(fname, 'r')
lines = 0
words = 0
characters = 0
for line in infile:
wordslist = [Link]()
lines = lines + 1
words = words + len(wordslist)
characters = characters + len(line)
print("[Link] Characters:",characters)
print("[Link] Words:",words)
print("[Link] Lines:",lines)
output
Enter the name of the file:"[Link]"
('[Link] Characters:', 47)
('[Link] Words:', 13)
('[Link] Lines:', 3)
Exercise - 8 Files
a) Write a function ball_collide that takes two balls as parameters and computes if they are colliding.
Your function should return a Boolean representing whether or not the balls are colliding.
Hint: Represent a ball on a plane as a tuple of (x, y, r), r being the radius
If (distance between two balls centers) <= (sum of their radii) then (they are colliding)
import math
def ball_collide(x1,y1,r1,x2,y2,r2):
distance=[Link]((x2-x1)**2+(y2-y1)**2)
radsum=r1+r2
if(distance<=radsum):
print("Balls are collide")
else:
16
print("Balls are not collide")
x1,y1,r1=input("enter ball-1 parameters like x1,y1 & r1 values:")
x2,y2,r2=input("enter ball-2 parameters like x2,y2 & r2 values:")
ball_collide(x1,y1,r1,x2,y2,r2)
output 1
enter ball-1 parameters like x1,y1 & r1 values:3,2,2
enter ball-2 parameters like x2,y2 & r2 values:4,3,2
Balls are collide
output 2
enter ball-1 parameters like x1,y1 & r1 values:3,2,2
enter ball-2 parameters like x2,y2 & r2 values:8,6,1
Balls are not collide
b) Find mean, median, mode for the given set of numbers in a list.
from collections import Counter
list=[11,2,3,2,1,2,2,2]
data = Counter(list)
list1=data.most_common() # Returns all unique items and their counts
mode=data.most_common(1) # Returns the highest occurring item
print ("prints mode and no of times occured",mode)
mean=0
sum=0
for i in list:
sum=sum+i
n=len(list)
mean=sum/n
print("mean value is ",mean)
list=[1,5,7,8,9,6]
17
print(len(list))
length=len(list)
mid=int(length/2)
meadian=list[mid]
print ("the meadian=",meadian)
PYTHON PROGRAMMING LAB
Exercise 1 – Basics
c) Running instructions in Interactive interpreter and a Python Script
Running Instructions in Interactive Interpreter
>>> print("welcome to Python")
welcome to Python
>>> a=10
>>> b=20
>>> sum=a+b
>>> print a
10
>>> print b
20
>>> print sum
30
>>> print("sum is",sum)
('sum is', 30)
>>> print " sum is",sum
sum is 30
>>> print('sum is',sum)
('sum is', 30)
>>> a=input("enter a value:")
enter a value:34
>>> print(a)
34
>>>
Running Instructions in an Python Script
18
Write a program [Link] that takes 2 numbers as command line arguments and prints its sum.
Source Code:
x=input("Enter x value:")
y=input("Enter y value:")
sum=x+y
print " Sum of x and y is : ",sum
out-put 1
Enter x value:34
Enter y value:78
Sum of x and y is : 112
out-put 2
Enter x value:56
Enter y value:23
Sum of x and y is : 79
d) Write a program to purposefully raise Indentation Error and Correct it
Source Code:-
Python provides no braces to indicate blocks of code for class and function definitions or flow control.
Blocks of code are denoted by line indentation, which is rigidly enforced.
The number of spaces in the indentation is variable, but all statements within the block must be indented
the same amount. For example:
19
Thus, in Python all the continuous lines indented with same number of spaces would form a block. The
following example has various statement blocks:
Note: Do not try to understand the logic at this point of time. Just make sure you
understood various blocks even if they are without braces.
20
Exercise 2 - Operations
a) Write a program to compute distance between two points taking input from the user
(Pythagorean Theorem)
Source code:-
from math import sqrt
x1=input("Enter x1 value :")
x2=input("Enter x2 value :")
y1=input("Enter y1 value :")
y2=input("Enter y2 value :")
distance=sqrt((x2-x1)**2+(y2-y1)**2)
print "Two points x1 y1 and x2 y2 are :",x1,y1,"and",x2,y2
print "Distance b/w two points is:",distance
out-put 1
21
Enter x1 value :2
Enter x2 value :5
Enter y1 value :3
Enter y2 value :8
Two points x1 y1 and x2 y2 are : 2 3 and 5 8
Distance b/w two points is: 5.83095189485
out-put 2
Enter x1 value :5
Enter x2 value :9
Enter y1 value :3
Enter y2 value :7
Two points x1 y1 and x2 y2 are : 5 3 and 9 7
Distance b/w two points is: 5.65685424949
b) Write a program [Link] that takes 2 numbers as command line arguments and prints its sum.
Source Code:
x=input("Enter x value:")
y=input("Enter y value:")
sum=x+y
print " Sum of x and y is : ",sum
out-put 1
Enter x value:34
Enter y value:78
Sum of x and y is : 112
out-put 2
Enter x value:56
22
Enter y value:23
Sum of x and y is : 79
Exercise - 3 Control Flow
e) Write a Program for checking whether the given number is a even number or
not.
Source Code:
n=input("Enter a number:")
if(n%2==0):
print "The number is Even"
else:
print "The number is not Even"
out-put 1
Enter a number:28
The number is Even
out-put 2
Enter a number:53
The number is not Even
f) Using a for loop, write a program that prints out the decimal equivalents of 1/2,
1/3, 1/4, . . . ,1/10
Source Code:
from fractions import Fraction
for i in range(2,11):
a=Fraction(1,i)
print float(a)
23
out-put
0.5
0.333333333333
0.25
0.2
0.166666666667
0.142857142857
0.125
0.111111111111
0.1
g) Write a program using a for loop that loops over a sequence. What is
sequence ?
Explanation:- We can generate a sequence of numbers using range() function. range(10) will
generate numbers from 0 to 9 (10 numbers).
We can also define the start, stop and step size as range(start,stop,step size). step size defaults to 1
if not provided.
This function does not store all the values in memory, it would be inefficient. So it remembers
the start, stop, step size and generates the next number on the go.
Source Code:
for i in range(10):
print i
print "---------------"
for i in range(1,10):
print i
24
print "---------------"
for i in range(4,10):
print i
print "---------------"
for i in range(3,10,2):
print i
print "---------------"
x=[25,1,7,6]
for i in x:
print i
out-put
0
---------------
1
25
---------------
---------------
---------------
25
6
26
h) Write a program using a while loop that asks the user for a number, and prints a countdown from
that number to zero.
Source Code:
n=input("Enter n value :")
while n>=0:
print n
n=n-1
out-put 1
Enter n value :5
out-put 2
Enter n value :10
10
1
27
Exercise 4 - Control Flow – Continued
c) Find the sum of all the primes below two million.
Source code:-
sum=0
for num in range(2,2000000):
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
sum=sum+num
print "sum of all Prime numbers between 2 and 2000000 is :",sum
out-put:-
sum of all Prime numbers between 2 and 2000000 is : 1709600813
d) Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting
with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the
sum of the even-valued terms.
Source code:-
x=0
y=1
z=x+y
sum=0
while (z<4000000):
if(z%2==0):
sum=sum+z
x=y
28
y=z
z=x+y
print "Sum of the even valued fibonacci sequence upto 10 is",sum
out-put:-
Sum of the even valued fibonacci sequence upto 10 is 4613732
Exercise - 5 - DS
a) Write a program to count the numbers of characters in the string and store them in a
dictionary data structure
Source code:-
x=input("enter the string in x:")
y=input("enter the string in y:")
dict1={x:len(x),y:len(y)}
print dict1
out-put 1
enter the string in x:'msr'
enter the string in y:'satyam'
{'satyam': 6, 'msr': 3}
out-put 2
enter the string in x:"cse"
enter the string in y:"python"
{'cse': 3, 'python': 6}
b) Write a program to use split and join methods in the string and trace a birthday with a
dictionary data structure.
Source code:-
str="abc 12-09-1992 vij ap india"
list=[Link]()
print list
s="->"
seq=("a","b","c","d")
print [Link](seq)
dict={"name":"abc",
"dob":"12-09-1992",
"city":"vij",
"state":"ap",
29
"country":"india"
}
print dict
for i in dict:
if(i=="dob"):
print dict[i]
out-put
['abc', '12-09-1992', 'vij', 'ap', 'india']
a->b->c->d
{'dob': '12-09-1992', 'city': 'vij', 'state': 'ap', 'name': 'abc', 'country': 'india'}
12-09-1992
Exercise - 6 DS – Continued
b) Write a program combine_lists that combines these lists into a dictionary.
Source code:-
keys=[1,2,3,4]
print keys
values=[10,20,30,40]
print values
dictionary=dict(zip(keys,values))
print dictionary
out-put
[1, 2, 3, 4]
[10, 20, 30, 40]
{1: 10, 2: 20, 3: 30, 4: 40}
b) Write a program to count frequency of characters in a given file. Can you use character
frequency to tell whether the given file is a Python program file, C program file or a text file?
30
Source code:-
fname = input("Enter file name: ")
l=input("Enter letter to be searched:")
k=0
with open(fname, 'r') as f:
for line in f:
words = [Link]()
for i in words:
for letter in i:
if(letter==l):
k=k+1
print("Occurrences of the letter:")
print(k)
sample output:-
Case 1:
Contents of file:
hello world hello
hello
Output:
Enter file name: [Link]
Enter letter to be searched:o
Occurrences of the letter:
5
Case 2:
Contents of file:
hello world
test
test test
Output:
Enter file name: [Link]
Enter letter to be searched:e
Occurrences of the letter:
6
Exercise - 7 Files
c) Write a program to print each line of a file in reverse order.
31
[Link]
hi
how r
u ra
Source code:-
filename=input("Enter file name: ")
for line in reversed(list(open(filename))):
print([Link]())
output:
Enter file name: "[Link]"
u ra
how r
hi
d) Write a program to compute the number of characters, words and lines in a file.
fname = input("Enter the name of the file:")
infile = open(fname, 'r')
lines = 0
words = 0
characters = 0
for line in infile:
wordslist = [Link]()
lines = lines + 1
words = words + len(wordslist)
characters = characters + len(line)
print("[Link] Characters:",characters)
print("[Link] Words:",words)
print("[Link] Lines:",lines)
32
output
Enter the name of the file:"[Link]"
('[Link] Characters:', 47)
('[Link] Words:', 13)
('[Link] Lines:', 3)
Exercise - 8 Files
a) Write a function ball_collide that takes two balls as parameters and computes if they are colliding.
Your function should return a Boolean representing whether or not the balls are colliding.
Hint: Represent a ball on a plane as a tuple of (x, y, r), r being the radius
If (distance between two balls centers) <= (sum of their radii) then (they are colliding)
import math
def ball_collide(x1,y1,r1,x2,y2,r2):
distance=[Link]((x2-x1)**2+(y2-y1)**2)
radsum=r1+r2
if(distance<=radsum):
print("Balls are collide")
else:
print("Balls are not collide")
x1,y1,r1=input("enter ball-1 parameters like x1,y1 & r1 values:")
x2,y2,r2=input("enter ball-2 parameters like x2,y2 & r2 values:")
ball_collide(x1,y1,r1,x2,y2,r2)
output 1
enter ball-1 parameters like x1,y1 & r1 values:3,2,2
enter ball-2 parameters like x2,y2 & r2 values:4,3,2
Balls are collide
output 2
enter ball-1 parameters like x1,y1 & r1 values:3,2,2
enter ball-2 parameters like x2,y2 & r2 values:8,6,1
Balls are not collide
b) Find mean, median, mode for the given set of numbers in a list.
33
from collections import Counter
list=[11,2,3,2,1,2,2,2]
data = Counter(list)
list1=data.most_common() # Returns all unique items and their counts
mode=data.most_common(1) # Returns the highest occurring item
print ("prints mode and no of times occured",mode)
mean=0
sum=0
for i in list:
sum=sum+i
n=len(list)
mean=sum/n
print("mean value is ",mean)
list=[1,5,7,8,9,6]
print(len(list))
length=len(list)
mid=int(length/2)
meadian=list[mid]
print ("the meadian=",meadian)
9)a) Write a function nearly_equal to test whether two strings are nearly equal. Two
strings a and b
are nearly equal when a can be generated by a single mutation on b.
def nearly_equal():
a=raw_input("Enter First Word'")
b=raw_input("Enter Second Word")
if a == b:
print ("Both are equal")
else:
34
print ("Both are not equal")
while(True):
print "for continue enter 1 or exit enter 0"
n=input("enter 1 or 0")
if(n==0):
break
else:
nearly_equal()
b) Write a function dups to find all duplicates in the list.
import collections
def dups():
a = [1,2,3,2,1,5,6,5,5,5]
print [item for item, count in [Link](a).items() if count > 1]
dups()
c) Write a function unique to find all the unique elements of a list.
def unique():
a = [1, 2, 2, 3,4,5,55,6,6,6]
b = []
for i in a:
if i not in b:
[Link](i)
print (b)
unique()
10. a) Write a function cumulative_product to compute cumulative product of a list of numbers.
35
list=[1,2,3,4]
def cumulative_product():
p=1
for i in list:
p *= i
return p
res=cumulative_product()
print "cumulative product=",res
b) Write a function reverse to reverse a list. Without using the reverse function.
def reverse():
list=[7,4,5,3]
list1=[]
l=len(list)
print l
for i in range(l):
[Link](list[l-1])
l=l-1
print list1
reverse()
c) Write function to compute gcd, lcm of two numbers. Each function shouldn’t exceed one line.
gcd=lambda a,b: gcd(b,a%b) if b else a
res=gcd(10,5)
print "gcd=",res
lcm=lambda a,b:(a*b)/gcd(a,b)
l=lcm(25,45)
print "lcm=",l
Exercise - 13 OOP
a) Class variables and instance variable
i) Robot
36
ii) ATM Machine
class AtmCard:
def connecttoserver():
print "connecting to server"
class AndhraCard(AtmCard):
def connecttoserver(self):
print "connecting to Andhra Bank server......"
class SbiCard(AtmCard):
def connecttoserver(self):
print "connecting to Sbi server......."
class AxisCard(AtmCard):
def connecttoserver(self):
print "connecting to axis bank server...."
class AtmMachine:
def __init__(self):
c=raw_input("insert your card")
if(c=="Andhra"):
a=AndhraCard();
[Link]()
elif(c=="Sbi"):
s=SbiCard()
[Link]()
else :
ax=AxisCard()
[Link]()
atm=AtmMachine()
37
O/p
Insert your Card
Andhra
Connecting to Andhra Bank Server
class Robot:
def __init__(self,version,speed,memory):
[Link]=version
[Link]=speed
[Link]=memory
print "version=",[Link]
print "speed=",[Link]
print "memory=",[Link]
def play(self):
print "playing games"
def task(self):
print "performing task"
def service(self):
print "providing service"
r1=Robot(2.0,"2GHZ","5TB")
[Link]()
[Link]()
o/p
version= 2.0
speed= 2GHZ
memory= 5TB
playing games
providing service
38
Exercise - 14 GUI, Graphics
1. Write a GUI for an Expression Calculator using tk
from Tkinter import *
import math
class calc:
def getandreplace(self):
"""replace x with * and ÷ with /"""
[Link] = [Link]()
[Link]=[Link]([Link],'/')
[Link]=[Link]('x','*')
def equals(self):
"""when the equal button is pressed"""
[Link]()
try:
[Link]= eval([Link]) #evaluate the expression using the eval function
except SyntaxError or NameErrror:
[Link](0,END)
[Link](0,'Invalid Input!')
else:
[Link](0,END)
[Link](0,[Link])
def squareroot(self):
"""squareroot method"""
[Link]()
try:
[Link]= eval([Link]) #evaluate the expression using the eval function
except SyntaxError or NameErrror:
[Link](0,END)
[Link](0,'Invalid Input!')
else:
[Link]=[Link]([Link])
[Link](0,END)
[Link](0,[Link])
def square(self):
"""square method"""
39
[Link]()
try:
[Link]= eval([Link]) #evaluate the expression using the eval function
except SyntaxError or NameErrror:
[Link](0,END)
[Link](0,'Invalid Input!')
else:
[Link]=[Link]([Link],2)
[Link](0,END)
[Link](0,[Link])
def clearall(self):
"""when clear button is pressed,clears the text input area"""
[Link](0,END)
def clear1(self):
[Link]=[Link]()[:-1]
[Link](0,END)
[Link](0,[Link])
def action(self,argi):
"""pressed button's value is inserted into the end of the text area"""
[Link](END,argi)
def __init__(self,master):
"""Constructor method"""
[Link]('Calulator')
[Link]()
self.e = Entry(master)
[Link](row=0,column=0,columnspan=6,pady=3)
self.e.focus_set() #Sets focus on the input text area
[Link]='÷'
[Link]=[Link]('utf-8')
#Generating Buttons
Button(master,text="=",width=10,command=lambda:[Link]()).grid(row=4,column=4,columnspan=2)
Button(master,text='AC',width=3,command=lambda:[Link]()).grid(row=1, column=4)
Button(master,text='C',width=3,command=lambda:self.clear1()).grid(row=1, column=5)
Button(master,text="+",width=3,command=lambda:[Link]('+')).grid(row=4, column=3)
Button(master,text="x",width=3,command=lambda:[Link]('x')).grid(row=2, column=3)
Button(master,text="-",width=3,command=lambda:[Link]('-')).grid(row=3, column=3)
Button(master,text="÷",width=3,command=lambda:[Link]([Link])).grid(row=1, column=3)
40
Button(master,text="%",width=3,command=lambda:[Link]('%')).grid(row=4, column=2)
Button(master,text="7",width=3,command=lambda:[Link]('7')).grid(row=1, column=0)
Button(master,text="8",width=3,command=lambda:[Link](8)).grid(row=1, column=1)
Button(master,text="9",width=3,command=lambda:[Link](9)).grid(row=1, column=2)
Button(master,text="4",width=3,command=lambda:[Link](4)).grid(row=2, column=0)
Button(master,text="5",width=3,command=lambda:[Link](5)).grid(row=2, column=1)
Button(master,text="6",width=3,command=lambda:[Link](6)).grid(row=2, column=2)
Button(master,text="1",width=3,command=lambda:[Link](1)).grid(row=3, column=0)
Button(master,text="2",width=3,command=lambda:[Link](2)).grid(row=3, column=1)
Button(master,text="3",width=3,command=lambda:[Link](3)).grid(row=3, column=2)
Button(master,text="0",width=3,command=lambda:[Link](0)).grid(row=4, column=0)
Button(master,text=".",width=3,command=lambda:[Link]('.')).grid(row=4, column=1)
Button(master,text="(",width=3,command=lambda:[Link]('(')).grid(row=2, column=4)
Button(master,text=")",width=3,command=lambda:[Link](')')).grid(row=2, column=5)
Button(master,text="√",width=3,command=lambda:[Link]()).grid(row=3, column=4)
Button(master,text="x²",width=3,command=lambda:[Link]()).grid(row=3, column=5)
#Main
root = Tk()
obj=calc(root) #object instantiated
[Link]()
output:_
41
B). Write a program to implement the following figures using turtle.
import turtle
def draw_square(some_turtle):
for i in range (1,5):
some_turtle.forward(200)
some_turtle.right(90)
def draw_art():
window = [Link]()
[Link]("black")
#Turtle Brad
brad = [Link]()
[Link]("turtle")
[Link]("yellow")
42
[Link](6)
[Link](2)
for i in range(1,37):
draw_square(brad)
[Link](10)
#Turtle Angie
angie = [Link]()
[Link]("turtle")
[Link]("blue")
[Link](5)
[Link](2)
size=1
while (True):
[Link](size)
[Link](91)
size = size + 1
[Link]()
draw_art()
OUTPUT: -
43
import turtle
imp = 0
while imp != 5:
wn = [Link]()
Cicle = [Link]()
[Link](30)
44
print("1) Use just one color (Default orange)")
print("2) Use two colors (Default: red and blue)")
print("3) Use three colors (Default: red, blue and orange)")
print("4) Use four colors (Default: red, blue, yellow, black)")
print("5) If you want to exit")
imp = eval(input("Make your choice: "))
number = eval(input("How many cycles do you want to draw? "))
radius= eval(input("Define the radius: "))
if imp == 1:
for x in range(number):
[Link]("orange")
[Link](radius)
[Link](int(360/number))
if imp == 2:
wn = [Link]()
Cicle = [Link]()
[Link](15)
for x in range(number):
if x % 2 == 0:
[Link]("blue")
else:
[Link]("red")
[Link](radius)
[Link](int(360/number))
45
if imp == 3:
wn = [Link]()
Cicle = [Link]()
[Link](15)
for x in range(number):
if x:
[Link]("red")
if x + 1:
[Link]("blue")
if x + 2:
[Link]("orange")
[Link](radius)
[Link](int(360/number))