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

Python

Uploaded by

shalini Kotecha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views

Python

Uploaded by

shalini Kotecha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 93

20EC413

Scripting language Lab Manual

Subject Code: 3EC14


Semester: 6th
Academic Year: 2022-23

Name of Student: SHALINI R. KOTECHA

Id No.:20EC413

BACHELOR OF TECHNOLOGY
ELECTRONICS AND COMMUNICATION

BIRLA VISHVAKARMA MAHAVIDHYALAYA ENGINEERING


COLLEGE
(An Autonomous Institution)

Vallabh Vidyanagar - 388120

1
20EC413

BIRLA VISHVAKARMA MAHAVIDYALAYA


ELECTRONICS AND COMMUNICATION DEPARTMENT

Certificate

This is to certify that Ms. Shalini R. Kotecha with ID. No.


20EC413 of Electronics & Communication has satisfactorily
completed the entire practical in the subject of 3EC14 : Scripting
Language Laboratory.

Subject In-Charge Head of Department


(Prof. Anish Vahora) (Dr. Bhargav Goradiya)

2
20EC413

INDEX

Sr.No.
AIM Date Pg. Sign

Programs from Halterman Python Book.


• Chapter –-2
1.
• Chapter - 3
• Chapter - 4
Write a program on Python Lists, Tuples, Sets, & Dictionaries.
2.

Operations :
a) Write a program to compute distance between two points
taking input from the user (Pythagorean Theorem)
3.
b) Write a program add.py that takes 2 numbers as command
line arguments and prints its sum.

Control Flow :
a) Write a Program for checking whether the given number is
an even number or not.
b) Using a for loop, write a program that prints out the decimal
4. equivalents of 1/2, 1/3, 1/4, . . . ,1/10
c) Write a program using for loop that loops over a sequence.
What is sequence?
d) Write a program using a while loop that asks the user for a
number, and prints a countdown from that number to zero.
Control Flow – Continued :
a) Find the sum of all the primes below two million. Each new
term in the Fibonacci sequence is generated by adding the
previous two terms. By starting with 1 and 2, the first 10
5. terms will be: 1, 2, 3, 5,
8, 13, 21, 34, 55, 89,
b) By considering the terms in the Fibonacci sequence whose
values do not exceed four million, find the sum of the even
valued terms.

3
20EC413

Data Structures :
a) Write a program to count the numbers of characters in the
string and store them in a dictionary data structure
b) Write a program to use split and join methods in the string
and trace a birthday with a dictionary data structure.
6. c) Write a program combine lists that combines these lists into
a dictionary.
d) 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?
Files :
a) Write a program to print each line of a file in reverse order.
7.
b) Write a program to compute the number of characters, words
and lines in a file.

Functions:
a) Write a function ball collides that takes two balls as
Parameters and computes if they are colliding. Your
8. function should return a
Boolean representing whether or not the balls are colliding
b) Write a function to find mean, median, mode for the given
set of numbers in a list.
Functions – Continued :
a) Write a function nearly equal to test whether two strings
are nearly equal. Two strings a and b are nearly equal when
9. a can be generated by a single mutation on b.
b) Write a function dup to find all duplicates in the list.
c) Write a function unique to find all the unique elements of a
list.

Functions - Problem Solving :


a) Write a function cumulative product to compute
cumulative product of a list of numbers.
10. b) Write a function reverse to reverse a list. Without using the
reverse function.
c) Write function to compute gcd, lcm of two numbers. Each
function shouldn’t exceed one line.

4
20EC413

Multi-D Lists :
a) Write a program that defines a matrix and prints
b) Write a program to perform addition of two square
11.
matrices
c) Write a program to perform multiplication of two square
matrices
OOP :
Class variables and instance variable and illustration of the self -
12. variable
i. Robot
ii. ATM Machine

GUI , Graphics :
a) Write a GUI for an Expression Calculator using tk .
b) Write a program to implement the following figures using
turtle.
13.

5
20EC413

PRACTICAL-1
AIM: Program from HALTERMAN PYTHON BOOK

CHAPTER-2
LISTING 2.1
x=10
print(x)

OUTPUT:

LISTING 2.2
x=10
print('x = ' +str))
x = 20
print('x = ' +str))
x = 30
print('x = ' +str))

OUTPUT:

LISTING 2.3

6
20EC413

x = 10
print('x = ' + str(x))
x = 20
print('x = ' + str(x))
x = 30
print('x = ' + str(x))

OUTPUT:

LISTING 2.4
x,y,z = 100, -45, 0
print('x =', x, ' y=', y, ' z=', z)

OUTPUT:

7
20EC413

LISTING 2.5
a = 20
print('first, variable a has value', a, 'and type', type(a))
a = 'abc'
print('now, variable ahas value', a, 'and type', type(a))

OUTPUT:

LISTING 2.6
pi = 3.14159;
print("pi =", pi)
print("or", 3.14, "for short")

OUTPUT:

LISTING 2.7
avagadros_number = 6.022e23
c = 2.998e8
print("Avogadro's number =", avagadros_number)
print("Speed of light =", c)

8
20EC413

OUTPUT:

LISTING 2.8
print('A\nB\nC')
print('D\tE\tF')
print('wx\byz')
print('1\a2\a3\a4\a5\a6')

OUTPUT:

LISTING 2.9
print("Did you know that 'word is word?")
print('Did you know that "word" is word?')
print('Did you know that \'word\' is word?')
print("Did you know that \"word\" is word?")

9
20EC413

OUTPUT:

LISTING 2.10
filename = 'C:\\users\\rick'
print(filename)

OUTPUT:

LISTING 2.11
print('Please enter some text:')
x = input()
print('Text entered:', x)
print('Type:', type(x))

OUTPUT:

10
20EC413

LISTING 2.12
print('Please enter an integer value:')
x = input()
print('Please enter another integer value:')
y = input()
num1 = int(x)
num2 = int(y)
print(num1, '+', num2, '=', num1 + num2)

OUTPUT:

LISTING 2.13
x = input('Please enter an integer value:')
y = input('Please enter another integer value:')
num1 = int(x)
num2 = int(y)
print(num1, '+', num2, '=', num1 + num2)

OUTPUT:

11
20EC413

LISTING 2.14
num1 = int(input('Please enter an integer value: '))
num2 = int(input('Please enter another integer value: '))
print(num1, '+', num2, '=', num1 + num2)

OUTPUT:

LISTING 2.15
x1 = eval(input('Entry x1? '))
print('x1 =', x1, ' type:', type(x1))
x2 = eval(input('Entry x2? '))
print('x2 =', x2, ' type:', type(x2))
x3 = eval(input('Entry x3? '))
print('x3 =', x3, ' type:', type(x3))
x4 = eval(input('Entry x4? '))
print('x4 =', x4, ' type:', type(x4))

12
20EC413

OUTPUT:

LISTING 2.16
num1, num2 = eval(input('Please enter number 1, number 2: '))
print(num1, '=', num2, '=', num1 + num2)

OUTPUT:

LISTING 2.17
print(eval(input()))

OUTPUT:

LISTING 2.18
print('A', end='')
print('B', end='')
print('C', end='')
13
20EC413

print()
print('X')
print('Y')
print('Z')

OUTPUT:

LISTING 2.19
w, x, y, z = 14, 15, 16, 17
print(w, x, y, z)
print(w, x, y, z, sep=',')
print(w, x, y, z, sep='')
print(w, x, y, z, sep=':')
print(w, x, y, z, sep='-----')

OUTPUT:

14
20EC413

CHAPTER-3

LISTING 3.1
value1 = eval(input('Please enter a number: '))
value2 = eval(input('Please enter another number: '))
sum = value1 + value2
print(value1, '+', value2, '=', sum)

OUTPUT:

LISTING 3.2
one = 1.0
one_third = 1.0/3.0
zero = one - one_third - one_third - one_third
print('one =', one, ' one_third =', one_third, ' zero =', zero)

OUTPUT:

15
20EC413

LISTING 3.3
one = 1.0
one_tenth = 1.0/10.0
zero = one - one_tenth - one_tenth - one_tenth \
- one_tenth - one_tenth - one_tenth \
- one_tenth - one_tenth - one_tenth \
- one_tenth
print('one =', one, ' one_tenth =', one_tenth, ' zero =', zero)

OUTPUT:

LISTING 3.4
#File dividedanger.py
#Get two integers from the user
dividend, divisor = eval(input('Please enter two numbers to divide: '))
#Divide them and report the result
print(dividend, '/', divisor, "=", dividend/divisor)

OUTPUT:

16
20EC413

LISTING 3.5
# Get a number from the user
value = eval(input('Please enter a number to cut in half: '))
# Report the result
print(value/2)

OUTPUT:

LISTING 3.6
degreesF = eval(input('Enter the temperature in degrees F: '))
degreesC = 5/9*(degreesF - 32);
print(degreesF, 'degrees F =', degreesC, 'degrees C')

OUTPUT:

LISTING 3.7
seconds = eval(input("Please enter the number of seconds:"))
hours = seconds // 3600 # 3600 seconds = 1 hours
seconds = seconds % 3600
minutes = seconds // 60 # 60 seconds = 1 minute
seconds = seconds % 60
17
20EC413

print(hours, "hr,", minutes, "min,", seconds, "sec")

OUTPUT:

LISTING 3.8
seconds = eval(input("Please enter the number of seconds:"))
hours = seconds // 3600 # 3600 seconds = 1 hours
seconds = seconds % 3600
minutes = seconds // 60 # 60 seconds = 1 minute
seconds = seconds % 60
print(hours, ":", sep="", end="")
tens = minutes // 10
ones = minutes % 10
print(tens, ones, ":", sep="", end="")
tens = seconds // 10
ones = seconds % 10
print(tens, ones, sep ="")

OUTPUT:

LISTING 3.9

18
20EC413

Degrees F, degrees C = 0, 0
Degrees C = 5/9*(degrees F - 32)
Degrees F = eval(input('Enter the temperature in degrees F: '))
print(degrees F, 'degrees F =', degrees C, 'degrees C')

OUTPUT:

19
20EC413

CHAPTER-4

LISTING 4.1
a =True
b =False
print('a=', a,'b=', b)
a =False;
print('a=', a,'b=', b)

OUTPUT:

LISTING 4.2
dividend, divisor = eval(input('Please enter two numbers to divide:'))
If divisor != 0:
print(dividend,'/', divisor,"=", dividend/divisor)

OUTPUT:

LISTING 4.3
dividend, divisor = eval(input('Please enter two numbers to divide:'))
If divisor != 0:

20
20EC413

quotient = dividend/divisor
print(dividend,'/', divisor,"=", quotient)
print('Program finished')

OUTPUT:

LISTING 4.5
dividend, divisor = eval(input('Please enter two numbers to divide:'))
If divisor != 0:
print(dividend,'/', divisor,"=", dividend/divisor)
else:
print('Division by zero is not allowed')

OUTPUT:

LISTING 4.6
d1 = 1.11 - 1.10
d2 = 2.11 - 2.10
print('d1=', d1,'d2=', d2)
ifd1 == d2:

21
20EC413

print('Same')
else:
print('Different')
OUTPUT:

LISTING 4.9
value = eval (input ("Please enter an integer value in the range 0...10:")
if value >= 0:
If value <= 10:
print (value, "is in range")
else:
print (value, "is too large")
else:
print (value, "is too small")
Print ("Done")

OUTPUT:

LISTING 4.15
dividend, divisor = eval(input('Enter dividend, divisor: '))
msg = dividend/divisor

22
20EC413

if divisor != 0
else 'Error, cannot divide by zero'
print(msg)

OUTPUT:

LISTING 4.16
n = eval(input("Enter a number: "))
print('|', n, '| = ', (-n if n < 0 else n), sep='')

OUTPUT:

23
20EC413

PRACTICAL - 2
AIM: Write a program on Python Lists, Tuples, Sets, & Dictionaries.

Python Lists:
Ex 1:
fruits = ["apple", "banana", "cherry"]
print(fruits[1])

OUTPUT:

Ex 2:
fruits = ["apple", "banana", "cherry"]
fruits[0] = "kiwi"

OUTPUT:

Ex 3:
fruits = ["apple", "banana", "cherry"]
fruits.append("orange")

OUTPUT:

24
20EC413

Ex 5:
fruits = ["apple", "banana", "cherry"]
fruits.remove("banana")

OUTPUT:

Ex 6:
fruits = ["apple", "banana", "cherry"]
print(fruits[-1])

OUTPUT:

Ex 7:
fruits = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(fruits[2:5])

OUTPUT:

Ex 8:
fruits = ["apple", "banana", "cherry"]
print(len(fruits))
25
20EC413

OUT PUT:

26
20EC413

Python Tuples:
Ex 1:
fruits = ("apple", "banana", "cherry")
print(fruits[0])

OUTPUT:

Ex 2:
fruits = ("apple", "banana", "cherry")
print(len(fruits))

OUTPUT:

Ex 3:
fruits = ("apple", "banana", "cherry")
print(fruits[-1])

OUTPUT:

Ex 4:

27
20EC413

fruits = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")


print(fruits[2:5])

OUTPUT:

28
20EC413

Python Sets:
Ex 1:
fruits = {"apple", "banana", "cherry"}
if "apple" in fruits:
print("Yes, apple is a fruit!")

OUTPUT:

Ex 2:
fruits = {"apple", "banana", "cherry"}
fruits.add("orange")

OUTPUT:

Ex 3:
fruits = {"apple", "banana", "cherry"}
more_fruits = ["orange", "mango", "grapes"]
fruits.update(more_fruits)

OUTPUT:

Ex 4:

29
20EC413

fruits = {"apple", "banana", "cherry"}


fruits.remove("banana")

OUTPUT:

Ex 5:
fruits.remove("banana")
fruits.discard("banana")

OUTPUT:

30
20EC413

Python Dictionaries:
Ex 1:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(car.get("model"))

OUTPUT:

Ex 2:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car["year"] = 2020

OUTPUT:

Ex 3:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car["color"] = "red"

31
20EC413

OUTPUT:

Ex 4:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car.pop("model")

OUTPUT:

Ex 5:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car.clear()

OUTPUT:

32
20EC413

PRACTICAL:3(a)
AIM: Write a program to compute distance between two points taking Input from
the user (Pythagorean Theorem)

DESCRIPTION:
• The Pythagorean theorem is the basis for computing distance between two
points. Let (x1,y1) and (x2,y2) be the co-ordinates of points on xy-plane.

• From Pythagorean theorem, the distance between two points is calculated


using the formulae:

• To find the distance, we need to use the method sqrt(). This method is not
accessible directly, so we need to import math module and then we need to
call this method using math static object.To find the power of a number, we
need to use ** operator.we use split() method to splits a string into a list.

CODE:
import math
a=input("enter first coordinate: ")
p1 = a.split(",")
b=input("enter, second coordinate: ")
p2 = b.split(",")
distance = math.sqrt(((int(p1[0])-int (p2[0]))*2)+((int(p1[1])-int (p2[1]))*2))
print("distance between ", a, "and", b, "is", distance)

33
20EC413

Output:

Conclusion: We gets the knowledge on math functions and how the values are
passed from the command line.

34
20EC413

PRACTICAL:3(b)

AIM: Write a program add.py that takes 2 numbers as command line arguments
and prints its sum.

DESCRIPTION:
• Command line arguments are the arguments that are passed to the program
when the program is invoked for execution.

• Python provides a getopt module that helps us to pass command line


arguments and options. The Python sys module provides access to any
command line arguments via sys. argv. This serves two purposes:

1. sys.argv is the list of command line arguments.


2. len(sys.argv) is the number of command line arguments.

• The first argument is always script name and it is also being counted in
number of arguments. As the command line arguments are strings, here we
need to type-cast those arguments to the suitable type.

Code:
num1=float(input("enter 1st no."))
num2=float(input("enter second no"))
print (f" sum is {num1+num2}")

35
20EC413

Output:

Conclusion: We gets the knowledge on math functions and how the values are
passed from the command line.

36
20EC413

PRACTICAL:4(a)

AIM: Write a Program for checking whether the given number is a even number
or not.

DESCRIPTION:
• If a number is exactly divisible by 2(Remainder is 0) then it is said to be an
Even number otherwise, the number is said to be an Odd number. In Python,
We use modulus(%) operator to find the remainder. executed. We can use
if…else statement to check whether the number is even or odd.
if…else statement
is a two-way decision making statement that decides what to do when the condition
is true and what to do when the condition is false. The general form of if…else
statement is as follows:
if condition:
intended statement block for true condition
else:
intended statement block for false condition

Code:
a=int(input("enter the no.:"))
if (a % 2 == 0):
print("no. is even")
else:
print("no. is not even or is odd" )

37
20EC413

Output:

Conclusion: We gets the knowledge on conditional statements and looping


statements.

38
20EC413

PRACTICAL:4(b)

AIM: Using a for loop, write a program that prints out the decimal equivalents of
1/2, 1/3, 1/4, . . . ,1/10

DESCRIPTION:
• A loop statement allows us to execute a statement or group of statements
multiple times. We can use for loop to calculate the decimal equivalents of
given set of numbers.

for loop statement:


• It has the ability to iterate over the items of any sequence, such as a list or a
string. Iterating over a sequence is called Traversal. The general form of for
loop statement is as follows:
for iterating_var in sequence:
Statement(s)

• The format() method takes the passed arguments, formats them, and places
them in the string where the placeholders {}

CODE:
for x in range(2,11):
y=1/x
mydecimal="{}"
print (mydecimal.format(y))

39
20EC413

OUTPUT:

CONCLUSION: We gets the knowledge on conditional statements and looping


statements.

40
20EC413

PRACTICAL:4(c)

AIM: Write a program using for loop that loops over a sequence. What is
sequence?

DESCRIPTION:
• A Sequence is the generic form for an ordered set. There are several types of
sequences in Python. The following 3 are most important.
• Lists: There are the most versatile sequence type. The elements of a list can
be any object and lists are mutable.
• Tuples: These are like lists, But Tuples are immutable.
• Strings: These are a special type of sequence that can store only characters
and having special notations.

CODE:
mySeqCkt =["Shalini","20EC413", "BVM"]
for x in mySeqCkt:
print(x)

OUTPUT:

CONCLUSION We gets the knowledge on conditional statements and looping


statements.

41
20EC413

PRACTICAL:4(d)

AIM: Write a program using a while loop that asks the user for a number, and
prints a countdown from that number to zero.

DESCRIPTION:
• A loop statement allows us to execute a statement or group of statements
multiple times. Here, We are using while loop.
while loop statement:
• It repeatedly executes a target statement as long as the given condition is
true. The general form while statement is as follows:
while expression:
statements(s)
Here, the statement(s) may be a single a statement or a block of statements. The
condition may be any expression, and is true for any non-zero value. The loop
iterates while the condition is true. When the condition becomes false, program
control passes to the line immediately following the loop.

CODE:
N=int(input("enter the num: "))
while (N>=0):
print (N)
N-=1

42
20EC413

OUTPUT:

Conclusion: We gets the knowledge on conditional statements and looping


statements.

43
20EC413

PRACTICAL:5(a)

AIM: Find the sum of all the primes below two million. 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, ...

DESCRIPTION:
• A Prime number is a natural number greater than 1 that has no positive
divisors other than 1 and itself. A natural number greater than 1 and that is
not a prime number is called a composite number. Here, We are using a
while loop.

CODE:
flag = 200
i=2
sum = 0
counter = 0
while(i != flag):
for j in range(2, i + 1):
if i % j == 0:
counter += 1
if counter == 1:
sum+=i
counter = 0
i += 1;
print("The result is :",sum)

44
20EC413

OUTPUT:

CONCLUSION We gets the knowledge on conditional statements and looping


statements.

45
20EC413

PRACTICAL:5(b)
AIM: By considering the terms in the Fibonacci sequence whose values do not
exceed four million, find the sum of the even-valued terms.

DESCRIPTION:
• The Fibonacci sequence is a series of numbers where a number is found by
adding up the two numbers before it. Starting with 0 and 1, the series will be
0,1,1,2,3,5,8,13 and so forth. In mathematical terms, the sequence Fn of
Fibonacci numbers is defined by the Recurrence relation.
Fn = Fn -1 + Fn –2
With initial values F0 = 0 and F1 = 1

CODE:
flag = 100 # Setting the number of the iteration.
a=1
b=2
temp = 0
print("The Fibonacci sequence is :")
print("\n",a," \n",b)
while(flag>=0):
temp = a + b
a =b
b = temp
flag = flag - 1
print(" \n",temp)

46
20EC413

OUTPUT:

CONCLUSION We gets the knowledge on conditional statements and looping


statements.

47
20EC413

PRACTICAL:6(a)
AIM: Write a program to count the numbers of characters in the string and store
them in a dictionary data structure.

DESCRIPTION:
• Traverse each character in the string and its occurrence is stored in the
dictionary. Here, we are using a String and a Dictionary
String:
A String is a sequence of characters. Strings can be created by enclosing characters
inside a single quote or double quotes. Even triple quotes can be used in Python
but generally used to represent multiline strings and docstrings.
Dictionary:
The dictionary is Python's built-in mapping type. Dictionaries map keys to values
and these pairs provide a useful way to store data in python. The only way to
access the value part of the dictionary is by using the key.

CODE:
string=input('Enter string whose characters is to be count: ')
dic={}
dic.update({string:len(string)})
print(dic)
OUTPUT:

CONCLUSION We get knowledge on strings and dictionaries data structure.

48
20EC413

PRACTICAL:6(b)
AIM: Write a program to use split and join methods in the string and trace a
birthday with a dictionary data structure.

DESCRIPTION:
• Compare the entered birthdate with each and every person‟s date of birth in
the dictionary and check whether the entered birthdate is present in the
dictionary or not. Here, We are using two built-in methods of the string:
split() and join().

• split():
This method breaks up a string using the specified separator and returns a
list of strings. The general form of split() is as follows:
str.split(separator)
• join():
This method provides a flexible way to concatenate a string. This method
returns a string in which the string elements of a sequence have been joined
by „sep‟ separator. The general form of join() is as follows:
sep.join(sequence)

CODE:
bdayin=input("enter the birth date:")
bdaylist=bdayin.split("/")
bday='-'.join(bdaylist)
mybday={"birthday": bday}
if 'birthday' in mybday:
print (mybday['birthday'])

49
20EC413

OUTPUT:

CONCLUSION We get the knowledge on split () and join () in dictionary data


structure.

50
20EC413

PRACTICAL:6(c)
AIM: Write a program to use split and join methods in the string and trace a
birthday with a dictionary data structure.

DESCRIPTION:
• Python offers a range of compound data types often referred to as
Sequences. List is one of the most frequently used and very versatile data
type used in Python.

• In Python Programming, a List is created by placing all the elements inside a


square bracket [], separated by commas. It can have any number of items
and they may be of different types.

CODE:
def test(keys, values):
return dict(zip(keys, values))
l1 = ['a', 'b', 'c', 'd', 'e', 'f']
l2 = [1, 2, 3, 4, 5]
print("Original lists:")
print(l1)
print(l2)
print("\nCombine the values of the said two lists into a dictionary:")
print(test(l1, l2))

51
20EC413

OUTPUT:

CONCLUSION We gets the knowledge on list and dictionaries data structure.

52
20EC413

PRACTICAL:6(d)
AIM: 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?

DESCRIPTION:
• Opening a file refers to getting the file ready either for reading or for
writing. This can be done using the open () function.
• This function returns a file object and takes two arguments, one that accepts
the file name and another that accepts the mode (Access Mode).
• The file should exist in the same directory as the Python script, otherwise the
full address of the file should be written.
• Given a string, the task is to find the frequencies of all the characters in that
string and return a dictionary with key as the character and its value as its
frequency in the given string.
• Simply iterate through the string and form a key in dictionary of newly
occurred element or if element is already occurred, increase its value by 1.

CODE:
string = input("Enter a string :")
freq = [None] * len(string);
for i in range(0,len(string)):
freq[i] = 1;
for j in range(i+1, len(string)):
if(string[i] == string[j]):
freq[i] = freq[i] + 1;

#Set string[j] to 0 to avoid printing visited character


string = string[ : j] + '0' + string[j+1 : ];

53
20EC413

#Displays the each character and their corresponding frequency


print("Characters and their corresponding frequencies");
for i in range(0, len(freq)):
if(string[i] != ' ' and string[i] != '0'):
print(string[i] + "-" + str(freq[i]));

OUTPUT:

CONCLUSION Student gets the knowledge on basic operations on files,


dictionaries and lists.

54
20EC413

PRACTICAL:7(a)
AIM: Write a program to print each line of a file in reverse order.

DESCRIPTION:
• Opening a file refers to getting the file ready either for reading or for
writing. This can be done using the open() function.
• The rstrip() method removes any trailing characters (characters at the end a
string, space is the default trailing character to remove.
CODE:
f=input("Enter file name: ")
for line in reversed(list (open(f))):
print(line.rstrip())
OUTPUT:

CONCLUSION Student gets the knowledge on basic concepts of files and lists.

55
20EC413

PRACTICAL:7(b)
AIM: Write a program to compute the number of characters, words and lines in a
file.

DESCRIPTION:
• Traverse each character in the file so that we can find number of characters,
words and lines in a text file. Here, We are using the some of the basic
methods of files.
• We already discussed about open() and close() in the previous programs.
read():
• If we need to extract string that contains all characters in the file, We can use
read(). The Syntax for read() in Python is:
str = file_object.read()

CODE:
f = open("my.txt", "r")
Number_of_lines = 0
Number_of_words = 0
Number_of_characters = 0
for line in f:
line = line.strip("\n")
words = line.split()
Number_of_lines += 1
Number_of_words += len(words)
number_of_characters += len(line)
f.close()

56
20EC413

print("lines:", number_of_lines, "words:", number_of_words, "characters:",


number_of_characters)

OUTPUT:

CONCLUSION Student gets the knowledge on basic concepts of files and lists.

57
20EC413

PRACTICAL:8(a)
AIM: 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.

DESCRIPTION:
• A ball on a plane is a tuple of (x, y, r), r being the radius.
• If (distance between two balls centers) <= (sum of their radii) then (they are
colliding)

CODE:
import math

def ball_collide(ball1, ball2): import math

def ball_collide (x1,y1,r1,x2,y2,r2):

dist=math.sqrt((x2-x1)**2+(y2-y1)**2);
print("Distance b/w two balls: ",dist)
center=dist/2;
print("Collision point", center);
r=r1+r2;
print("Sum of radious",r)

58
20EC413

if(center<=r):

print("They are Colliding")

return True;

else:
print("Not Colliding")

return False;

c=ball_collide (4,4,3,2,2,3)
print(c)
print(c)
c=ball_collide (100, 200, 20, 200, 100,10)

OUTPUT:

CONCLUSION We get the knowledge of functions, lists and tuples.

59
20EC413

PRACTICAL:8(b)
AIM: Find mean, median, mode for the given set of numbers in a list.

DESCRIPTION:
Mean: The mean is the average of all numbers and is sometimes called the
arithmetic mean.
Median: The median is the middle number in a group of numbers.
Mode: The mode is the number that occurs most often within a set of numbers.

CODE:
import statistics
a = [11,10,50,70,80,55,66,74,78,55,87,98,95,70]
z = statistics.mode(a) #for mode
x = statistics.mean(a) #for mean
y = statistics.median(a) #for median
print("mean",x, "median = ", y,"mode = ",z) #prints the result

OUTPUT:

CONCLUSION We get knowledge on functions, lists and tuples and mean,


median, mode.

60
20EC413

PRACTICAL:9(a)
AIM: 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.
DESCRIPTION:
• Two strings are said to be nearly equal if a single mutation applied to one
string will result in another string. That means, Given two strings s1 and s2,
find if s1 can be converted to s2 with exactly one edit(mutation).
• If yes, then the function should return a True value as the result. Otherwise,
it must return a False value as the result.

CODE:
def nearly_equal(a,b):
#case 1 : one character less or more
if abs(len(a)-len(b))>1:
return False
if len(a)<len(b):
k = len(a)
else:
k = len(b)
if(len(a)!=len(b)):
for i in range(0,k):
if a[i] != b[i]:
return False
if(len(a)==len(b)):
count = 0
for i in range(0,len(a)):

61
20EC413

if a[i]!=b[i]:
count+=1 #print(count)
if count>1:
return False
return True
a = input()
b = input()
if (nearly_equal(a,b) == True ):
print("Nearly equal")
else:
print("Not Nearly equal")
k = nearly_equal(a,b)

OUTPUT:

CONCLUSION We get knowledge on Continued functions.

62
20EC413

PRACTICAL:9(b)
AIM: Write a function dup to find all duplicates in the list.

DESCRIPTION:
• We need to write a function dups to find all duplicate elements in the list.
• If an element is repeated more than once in the list, then add that repeated
element to the resultant list.

CODE:
lst = [ 1,2,3,4,3,5,15,6,4,7,8,8]
dupitems = []
uniqitems={}
for x in lst:
if x not in uniqitems: uniqitems[x] = 1
else:
if uniqitems[x] == 1:
dupitems.append(x)
uniqitems[x] += 1
print("original List is")
print(lst)
print("Duplicate items")
print(dupitems)

63
20EC413

OUTPUT:

CONCLUSION We get knowledge on functions & lists.

64
20EC413

PRACTICAL:9(c)
AIM: Write a function unique to find all the unique elements of a list.

DESCRIPTION:
• We need to write a function unique to find all unique elements in the list.
• If an element is found only once in the list, then add that element to the
resultant list.

CODE:
def unique(lst):
return list(set(lst))

my_list = [1, 2, 2, 3, 3, 3, 4, 5, 5]
unique_list = unique(my_list)
print(unique_list) # Output: [1, 2, 3, 4, 5]
OUTPUT:

CONCLUSION We get knowledge on functions & lists.

65
20EC413

PRACTICAL:10(a)
AIM: Write a function cumulative_product to compute cumulative product of a list
of numbers.

DESCRIPTION:
• We need to write a function cumulative_product to find cumulative product
of numbers in the list. A Cumulative product is a sequence of partial
products of a given sequence.
• For example, The cumulative product of sequence [a,b,c,…..] are
a,ab,abc,…..

CODE:
def cumulative_product(numlist):
product=1
cp=[]
for ele in numlist: product=product*ele cp.append(product)
return cp
numlist=[]
n=int(input("Enter number of elements to be insert:"))
for i in range(n):
ele=int(input("Enter element:")) numlist.append(ele)
cp=cumulative_product(numlist)
print("Cumulative product of list elements is ",cp)

66
20EC413

OUTPUT:

CONCLUSION We get knowledge on functions & lists also cumulative product.

67
20EC413

PRACTICAL:10(b)
AIM: Write a function reverse to reverse a list. Without using the reverse function.

DESCRIPTION:
• We need to write a function reverse to reverse the given elements in a list.
• Reversing of a list is done by using the feature called slicing.
• Python‟s list objects have an interesting feature called slicing.
• We can view it as an extension of the square brackets indexing syntax. It
includes a special case where slicing a list with “[::-1]” produces a reversed
copy.

CODE:
def reverse(numlist):
i=0
j=len(numlist)-1
while(i<=j):
temp=numlist[i]
numlist[i]=numlist[j]
numlist[j]=temp
i=i+1
j=j-1
return numlist
numlist=[]
n=int(input("Enter number of elements to be insert:"))
for i in range(n):
ele=int(input("Enter element:"))
numlist.append(ele)

68
20EC413

reverse(numlist)
print("After reverse list elements are:\n",numlist)

OUTPUT:

CONCLUSION We get knowledge on functions & lists Without using the reverse
function.

69
20EC413

PRACTICAL:10(c)
AIM: Write function to compute gcd, lcm of two numbers. Each function
shouldn’t exceed one line

DESCRIPTION:
• We need to write a function to compute gcd, lcm of numbers. But here the
constraint is each function should not exceed one line. For this, we are using
lambda function.
lambda function:
• We can use lambda keyword to create small anonymous functions.
• Lambda functions can have any number of arguments but contain only one
expression.
• The expression is evaluated and returned.
• They cannot contain commands or multiple expressions.
• The general form of lambda function is as follows:
lambda arguments: expression

CODE:
gcd=lambda a,b: a if b==0 else gcd(b,a%b)
lcm=lambda a,b: (a*b)/gcd(a,b)
num1=int(input("Enter first number:")) #enter number 1
num2=int(input("Enter second number:")) #enter number 2
print("LCM of %d and %d is %d"%(num1,num2,lcm(num1,num2))) #prints lcm
print("GCD of %d and %d is %d"%(num1,num2,gcd(num1,num2))) #prints gcd

70
20EC413

OUTPUT:

CONCLUSION: We get knowledge on lambda function.

71
20EC413

PRACTICAL:11(a)
AIM: Write a program that defines a matrix and prints

DESCRIPTION:
• A matrix is a two-dimensional data structure. In python, matrix is a nested
list.
• A list is created by placing all the items (elements) inside a square bracket [],
separated by commas.
Accessing the elements of a matrix:
• Similar to list we can access elements of a matrix by using square brackets []
after the variable like a[row-number] [col_number].
CODE:
R = int (input ("Enter the number of rows:"))
C = int (input ("Enter the number of columns:"))
# Initialize matrix
matrix = []
print ("Enter the entries rowwise:")
# For user input
for i in range(R): # A for loop for row entries
a = []
for j in range(C): # A for loop for column entries
a.append(int (input ()))
matrix.append(a)
# For printing the matrix
for i in range(R):
for j in range(C):
print(matrix[i][j], end = " ")

72
20EC413

print ()
OUTPUT:

CONCLUSION: We get knowledge on multi-Dimensional lists & matrix.

73
20EC413

PRACTICAL:11(b)
AIM: Write a program to perform addition of two square matrices.

DESCRIPTION:
• In order to perform addition of two matrices, the two matrices must have
same number of rows and same number of columns.
• We should use nested for loops to iterate through each row and each column.
• At each point, we add the corresponding elements in the two matrices and
store it in the result.

CODE:
# 1st matrix
matrix_1 = []
print("Enter the entries rowwise for 3x3:")
# For user input
for i in range(3): # A for loop for row entries
a =[]
for j in range(3): # A for loop for column entries
a.append(int(input()))
matrix_1.append(a)
# For printing the matrix
for i in range(3):
for j in range(3):
print(matrix_1[i][j], end = " ")
print()
# 2nd matrix
matrix_2 = []
74
20EC413

print("Enter the entries rowwise for 3x3:")


# For user input
for i in range(3): # A for loop for row entries
a =[]
for j in range(3): # A for loop for column entries
a.append(int(input()))
matrix_2.append(a)
# For printing the matrix
for i in range(3):
for j in range(3):
print(matrix_2[i][j], end = " ")
print()
result = [[0,0,0], [0,0,0], [0,0,0]]
# iterate through rows
for i in range(len(matrix_1)):
# iterate through columns
for j in range(len(matrix_1[0])):
result[i][j] = matrix_1[i][j] + matrix_2[i][j]
print("Result is")
for r in result:
print(r)

75
20EC413

OUTPUT:

CONCLUSION: We get knowledge of multi-Dimensional lists & how to add two


matrices.

76
20EC413

PRACTICAL:11(c)
AIM: Write a program to perform multiplication of two square matrices

DESCRIPTION:
• In order to perform multiplication of two matrices, then the number of
columns in first matrix should be equal to the number of rows in second
matrix.
• When we multiply two matrices by each other, the resulting matrix will have
as many columns as the biggest matrix in the equation.
• For example, If we are multiplying a 3*3 by a 3*4 matrix, the resulting
matrix will be a 3*4.

CODE:
result = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
# 1st matrix
A = []
print("Enter the entries rowwise for 3x3:") # For user input
for i in range(3): # A for loop for row entries
a =[]
for j in range(3): # A for loop for column entries
a.append(int(input()))
A. append(a)
# For printing the matrix
for i in range(3):
for j in range(3):
print(A[i][j], end = " ")
print()

77
20EC413

# 2nd matrix
B = []
print("Enter the entries rowwise for 3x3:")
# For user input
for i in range(3): # A for loop for row entries
a =[]
for j in range(3): # A for loop for column entries
a.append(int(input()))
B. append(a)
# For printing the matrix
for i in range(3):
for j in range(3):
print(B[i][j], end = " ")
print()
# iterating by row of A
for i in range(len(A)):
# iterating by coloum by B
for j in range(len(B[0])):
# iterating by rows of B
for k in range(len(B)):
result[i][j] += A[i][k] * B[k][j]
for r in result:
print(r)

78
20EC413

OUTPUT:

CONCLUSION: We get knowledge of multi-Dimensional lists & how to


multiplication two matrix.

79
20EC413

PRACTICAL:12(a)
AIM: Class variables and instance variables and illustration of the self - variable i)
Robot ii) ATM Machine

DESCRIPTION:
• Class variable: A variable that is shared by all instances of a class. Class
variables are defined within a class but outside any of the class's methods.
Class variables are not used as frequently as instance variables are.
• Instance variable: A variable that is defined inside a method and belongs
only to the current instance of a class.
• Self-variable: The first argument to every method inside a class is a special
variable self.
• Every time a class refers to one of its variables or methods, it must precede
them by itself.
• The purpose of self is to distinguish class‟s variables and methods from
other variables and functions in the program.
• For implementing Class Robot, a class variable called count, instance
variable called name and self variable self is used.
• To distinguish their usage, class variables are accessed using classname with
dot(.) operator.
• Where as, instance variables are accessed using self with dot(.) operator.
• For implementing Class ATM Machine, an instance variable called balance
and self variable self is used to call the instance variable within the method
of a class.

CODE:
Code(i):
class Robot:
population = 0
def __init__(self, name):
self.name = name

80
20EC413

print('(Initializing {0})'.format(self.name))
Robot.population += 1
def __del__(self):
'''I am dying.'''
print('{0} is being destroyed!'.format(self.name))
Robot.population -= 1

if Robot.population == 0:
print('{0} was the last one.'.format(self.name))
else:
print('There are still {0:d} robots working.'.format(Robot.population))

def sayHi(self):
'''Greeting by the robot.
Yeah, they can do that.'''

print('Greetings, my masters call me {0}.'.format(self.name))

def howMany():
'''Prints the current population.'''

print('We have {0:d} robots.'.format(Robot.population))


howMany = staticmethod(howMany)

droid1 = Robot('R2-D2')

81
20EC413

droid1.sayHi()
Robot.howMany()
droid2 = Robot('C-3PO')
droid2.sayHi()
Robot.howMany()
print("\nRobots can do some work here.\n")
print("Robots have finished their work. So let's destroy them.")
del droid1
del droid2
Robot.howMany()
Output(i):

Code(ii):
import random class Account:
# Construct an Account object
def init (self, id, balance = 0, annualInterestRate = 3.4): self.id = id
self.balance = balance self.annualInterestRate = annualInterestRate
def getId(self): return self.id
def getBalance(self): return self.balance
82
20EC413

def getAnnualInterestRate(self): return self.annualInterestRate


def getMonthlyInterestRate(self): return self.annualInterestRate / 12
def withdraw(self, amount): self.balance -= amount
def deposit(self, amount): self.balance += amount
def getMonthlyInterest(self): # Nesting of member functions return self.balance *
self.getMonthlyInterestRate()
accounts = []
for i in range(1000, 9999):
account = Account(i, 0) # array of objects accounts.append(account)
while True:
id = int(input("\nEnter account pin: "))
while id < 1000 or id > 9999:
id = int(input("\nInvalid Id.. Re-enter: "))
while True:
print("\n1 - View Balance \t 2 - Withdraw \t 3 - Deposit \t 4 - Exit ") selection =
int(input("\nEnter your selection: "))
for acc in accounts: if acc.getId() == id:
accountObj = acc break
if selection == 1:
print(accountObj.getBalance())
elif selection == 2:
amt = float(input("\nEnter amount to withdraw: "))
ver_withdraw = input("Is this the correct amount, Yes or No ? " + str(amt) + " ") if
ver_withdraw == "Yes":
print("Verify withdraw") else:
break

83
20EC413

if amt < accountObj.getBalance(): accountObj.withdraw(amt)


print("\nUpdated Balance: " + str(accountObj.getBalance()) + "\n") else:
print("\nYou're balance is less than withdrawl amount: " + str(accountObj.getBalan
ce()) + "\n")
print("\nPlease make a deposit.");
elif selection == 3:
amt = float(input("\nEnter amount to deposit: "))
ver_deposit = input("Is this the correct amount, Yes, or No ? " + str(amt) + " ") if
ver_deposit == "Yes":
accountObj.deposit(amt);
print("\nUpdated Balance: " + str(accountObj.getBalance()) + "\n")
else:
break
elif selection == 4: print("\nTransaction is now complete.")
print("Transaction number: ", random.randint(10000, 1000000)) print("Current
Interest Rate: ", accountObj.annualInterestRate)
print("Monthly Interest Rate: ", accountObj.annualInterestRate / 12)
print("Thanks for choosing us as your bank")
exit()
else:
print("nThat's an invalid choice.")

84
20EC413

Output(ii):

CONCLUSION: Student gets the knowledge of Object-Oriented Programming


concepts and functions.

85
20EC413

PRACTICAL-13(A)

AIM: Write a GUI for an Expression Calculator using tk.

Program:

# Write a GUI for an Expression Calculator using tk.


from tkinter import *
win = Tk() # This is to create a basic window
win.geometry("312x324") # this is for the size of the window
win.resizable(0, 0) # this is to prevent from resizing the window
win.title("Calculator")
###################Starting with functions #################### # 'btn_click' function :
# This Function continuously updates the # input field whenever you enters a number
def btn_click(item):
global expression
expression = expression + str(item)
input_text.set(expression)
# 'bt_clear' function :This is used to clear
# the input field def bt_clear(): global expression expression = "" input_text.set("")
# 'bt_equal':This method calculates the expression
# present in input field def bt_equal():
global expression
result = str(eval(expression)) # 'eval':This function is used to evaluates the string expression directly
input_text.set(result)
expression = ""
expression = ""
# 'StringVar()' :It is used to get the instance of input field input_text = StringVar()
# Let us creating a frame for the input field
input_frame = Frame(win, width=312, height=50, bd=0, highlightbackground="black", high-
lightcolor="black", highlightthickness=2)
input_frame.pack(side=TOP)

86
20EC413

#Let us create a input field inside the 'Frame'


input_field = Entry(input_frame, font=('arial', 18, 'bold'), textvariable=in- put_text, width=50, bg="#eee",
bd=0, justify=RIGHT)
input_field.grid(row=0, column=0)
input_field.pack(ipady=10) # 'ipady' is internal padding to increase the height of in- put field
#Let us creating another 'Frame' for the button below the 'input_frame'
btns_frame = Frame(win, width=312, height=272.5, bg="grey")
btns_frame.pack() # first row
clear = Button(btns_frame, text = "C", fg = "black", width = 32, height = 3, bd = 0, bg = " #eee", cursor =
"hand2", command = lambda: bt_clear()).grid(row = 0, column = 0, column- span = 3, padx = 1, pady =
1)
divide = Button(btns_frame, text = "/", fg = "black", width = 10, height = 3, bd = 0, bg = "#eee", cursor =
"hand2", command = lambda: btn_click("/")).grid(row = 0, column = 3, padx
= 1, pady = 1) # second row
seven = Button(btns_frame, text = "7", fg = "black", width = 10, height = 3, bd = 0, bg = " #fff", cursor =
"hand2", command = lambda: btn_click(7)).grid(row = 1, column = 0, padx = 1
, pady = 1)
eight = Button(btns_frame, text = "8", fg = "black", width = 10, height = 3, bd = 0, bg = " #fff", cursor =
"hand2", command = lambda: btn_click(8)).grid(row = 1, column = 1, padx = 1
, pady = 1) nine = Button(btns_frame, text = "9", fg = "black", width = 10, height = 3, bd = 0, bg = "#fff",
cursor = "hand2", command = lambda: btn_click(9)).grid(row = 1, column = 2, padx = 1, pady = 1
)
multiply = Button(btns_frame, text = "*", fg = "black", width = 10, height = 3, bd = 0, bg
= "#eee", cursor = "hand2", command = lambda: btn_click("*")).grid(row = 1, column = 3, padx = 1,
pady = 1)
# third row four = But-
ton(btns_frame, text = "4", fg = "black", width = 10, height = 3, bd = 0, bg = "#fff", cursor = "hand2",
command = lambda: btn_click(4)).grid(row = 2, column = 0, padx = 1, pady = 1
) five = Button(btns_frame, text = "5", fg = "black", width = 10, height = 3, bd = 0, bg = "#fff", cursor =
"hand2", command = lambda: btn_click(5)).grid(row = 2, column = 1, padx = 1, pady = 1
) six = Button(btns_frame, text = "6", fg = "black", width = 10, height = 3, bd = 0, bg = "#fff", cursor =
"hand2", command = lambda: btn_click(6)).grid(row = 2, column = 2, padx = 1, pady = 1
)

87
20EC413

minus = Button(btns_frame, text = "-", fg = "black", width = 10, height = 3, bd = 0, bg = " #eee", cursor =
"hand2", command = lambda: btn_click("-")).grid(row = 2, column = 3, padx =
1, pady = 1) # fourth row one = But-
ton(btns_frame, text = "1", fg = "black", width = 10, height = 3, bd = 0, bg = "#fff", cursor = "hand2",
command = lambda: btn_click(1)).grid(row = 3, column = 0, padx = 1, pady = 1
)
two = Button(btns_frame, text = "2", fg = "black", width = 10, height = 3, bd = 0, bg = "#fff", cursor =
"hand2", command = lambda: btn_click(2)).grid(row = 3, column = 1, padx = 1, pady = 1
)
three = Button(btns_frame, text = "3", fg = "black", width = 10, height = 3, bd = 0, bg = " #fff", cursor =
"hand2", command = lambda: btn_click(3)).grid(row = 3, column = 2, padx = 1
, pady = 1) plus = Button(btns_frame, text = "+", fg = "black", width = 10, height = 3, bd = 0, bg =
"#eee", cursor = "hand2", command = lambda: btn_click("+")).grid(row = 3, column = 3, padx = 1, pady
=
1)
# fourth row zero = But- ton(btns_frame, text = "0", fg = "black", width = 21, height = 3, bd = 0, bg =
"#fff", cur- sor = "hand2", command = lambda: btn_click(0)).grid(row = 4, column = 0, column- span = 2,
padx = 1, pady = 1)
point = Button(btns_frame, text = ".", fg = "black", width = 10, height = 3, bd = 0, bg = " #eee", cursor =
"hand2", command = lambda: btn_click(".")).grid(row = 4, column = 2, padx =
1, pady = 1)
equals = Button(btns_frame, text = "=", fg = "black", width = 10, height = 3, bd = 0, bg = "#eee", cursor =
"hand2", command = lambda: bt_equal()).grid(row = 4, column = 3, padx = 1, pady = 1)
win.mainloop()

88
20EC413

OUTPUT :

89
20EC413

PRACTICAL-13(B)

AIM: Write a program to implement the following figures using turtle

import turtle, random


DESCRIPTION:

Turtle graphics is a popular way for introducing programming to kids.


It was part of the original Logo programming language developed by Wally Feurzig and
Seymour Papert in 1966.
The turtle module provides turtle graphics primitives, in both object-or- iented and procedure?oriented
ways.
Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk
support.
To make use of the turtle methods and functionalities, we need to im- port turtle.”turtle” comes packed
with the standard Python package and need not be installed externally.
The roadmap for executing a turtle program follows 4 steps:

1. Import the turtle module


2. Create a turtle to control.
3. Draw around using the turtle methods.
4. Run turtle.done().

CODE :
colors =["red", "green", "blue", "orange", "purple","pink", "yellow"]

painter = turtle.Turtle()

painter.pensize(3)

for i in range(10):

color =random.choice(colors)

90
20EC413

painter.pencolor (color)

painter.circle(100)

painter.right (30)

painter.left(60)

painter.setposition(0,0)

OUTPUT :

Conclusion: We learn about the tkinter and turtle library of python

91
20EC413

CODE(II) :
import turtle

window = turtle.Screen()

painter = turtle.Turtle()

window.bgcolor("lightgreen")
painter.fillcolor('blue')
painter.pencolor('blue')
painter.pensize(3)
def drawsq(t, s):

for i in range(4):

t.forward(s)

t.left(90)

for i in range(1,180):

painter.left(18)

drawsq(painter, 200)

92
20EC413

OUTPUT :

CONCLUSION: Student gets the knowledge on development of basic turtle module.

93

You might also like