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

Python Lab Manual-R22

The document is a lab manual for a Python Programming course designed for B.Tech students, outlining course objectives, outcomes, and weekly lab experiments. It includes prerequisites, course structure, and a variety of programming tasks to enhance students' understanding of Python, data structures, and file handling. Additionally, it provides references and resources for further learning and emphasizes the importance of ethical and professional values in engineering.

Uploaded by

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

Python Lab Manual-R22

The document is a lab manual for a Python Programming course designed for B.Tech students, outlining course objectives, outcomes, and weekly lab experiments. It includes prerequisites, course structure, and a variety of programming tasks to enhance students' understanding of Python, data structures, and file handling. Additionally, it provides references and resources for further learning and emphasizes the importance of ethical and professional values in engineering.

Uploaded by

237r5a7307
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 61

LAB MANUAL

PROGRAMMING WITH PYTHON


LAB
R22 CMRTC B. Tech CSE(AI&ML)

Python Programming Laboratory

B.Tech. III Semester L T P C


0 0 3 1.5
Subject Code: 22AM306PC

Prerequisites: A course on Data Structure using C


Co-requites: A course on Python Programming

Course Objectives:
1.To install and run the Python interpreter
2.To learn control structures.
3.To Understand Lists and Dictionaries in python.
4.To Handle Strings and Files in Python

Course Outcomes: After completion of this course, student will be able to:
1.Define python syntax, semantics and flow control.
2.Demonstrate proficiency in handling strings, list tuples and arrays.
3 Develop python programs using core data structures.
4 Conduct experiments on file handling, exception handling and modules.
5.Design the application specific codes using python.

Note: The lab experiments will be like the following experiment examples

Week -1:
1. i) Use a web browser to go to the Python website http://python.org. This page contains
informationabout Python and links to Python-related pages, and it gives you the ability to
search the Python documentation.
ii) Start the Python interpreter and type help() to start the online help utility.
2. Start a Python interpreter and use it as a
Calculator.3.
i) Write a program to calculate compound interest when principal, rate and number of
periods aregiven.
ii) Given coordinates (x1, y1), (x2, y2) find the distance between two points
4. Read name, address, email and phone number of a person through keyboard and print the details.

Week - 2:
1. Print the below triangle using for
loop.5
44
333
2222
11111
2. Write a program to check whether the given input is digit or lowercase character or
uppercasecharacter or a special character (use 'if-else-if' ladder)
3. Python Program to Print the Fibonacci sequence using while loop
4. Python program to print all prime numbers in a given interval (use break)
R22 CMRTC B. Tech CSE(AI&ML)

Week - 3:
1. i) Write a program to convert a list and tuple into arrays.
ii) Write a program to find common values between two arrays.
2. Write a function called gcd that takes parameters a and b and returns their greatest common divisor.
3. Write a function called palindrome that takes a string argument and returnsTrue if it is a
palindromeand False otherwise. Remember that you can use the built-in function len to check
the length of a string.

Week - 4:
1. Write a function called is_sorted that takes a list as a parameter and returns True if the list
is sortedin ascending order and False otherwise.
2. Write a function called has_duplicates that takes a list and returns True if there is any
element thatappears more than once. It should not modify the original list.
i). Write a function called remove_duplicates that takes a list and returns a new list with

ii).
want and the empty string.
iii). Write a python code to read dictionary values from the user. Construct a function to
invert itscontent. i.e., keys should be values and values should be keys.
3. i) Add a comma between the characters. If the given word is 'Apple', it should become 'A,p,p,l,e'
ii) Remove the given word in all the places in a string?
iii) Write a function that takes a sentence as an input parameter and replaces the first letter of
everyword with the corresponding upper case letter and the rest of the letters in the word by
corresponding letters in lower case without using a built-in function?
4. Writes a recursive function that generates all binary strings of n-bit length

Week - 5:
1. i) Write a python program that defines a matrix and prints
ii) Write a python program to perform addition of two square matrices
iii) Write a python program to perform multiplication of two square matrices
2. How do you make a module? Give an example of construction of a module using different
geometricalshapes and operations on them as its functions.
3. Use the structure of exception handling all general purpose exceptions.

Week-6:
1. a. Write a function called draw_rectangle that takes a Canvas and a Rectangle as
arguments anddraws a representation of the Rectangle on the Canvas.
b. Add an attribute named color to your Rectangle objects and modify draw_rectangle
so that ituses the color attribute as the fill color.
c. Write a function called draw_point that takes a Canvas and a Point as arguments and
draws arepresentation of the Point on the Canvas.
d. Define a new class called Circle with appropriate attributes and instantiate a few Circle
objects.Write a function called draw_circle that draws circles on the canvas.
2. Write a Python program to demonstrate the usage of Method Resolution Order (MRO) in
multiplelevels of Inheritances.
3. Write a python code to read a phone number and email-id from the user and
validate it forcorrectness.
R22 CMRTC B. Tech CSE(AI&ML)

Week- 7
1. Write a Python code to merge two given file contents into a third file.
2. Write a Python code to open a given file and construct a function to check for given words
present init and display on found.
3. Write a Python code to Read text from a text file, find the word with most number of occurrences
4. Write a function that reads a file file1 and displays the number of words, number of
vowels, blankspaces, lower case letters and uppercase letters.

Week - 8:
1. Import numpy, Plotpy and Scipy and explore their functionalities.
2. a) Install NumPy package with pip and explore it.
3. Write a program to implement Digital Logic Gates AND, OR, NOT, EX-OR
4. Write a program to implement Half Adder, Full Adder, and Parallel Adder
5. Write a GUI program to create a window wizard having two text labels, two text fields and
two buttonsas Submit and Reset.
TEXT BOOKS:
1. Supercharged Python: Take your code to the next level, Overland 4th Edition, 2019.
2. Mark Lutz, O'reilly ,Learning Python. 5th Edition, 2015.

REFERENCE BOOKS:
1. Vamsi Kurama, Python Programming: A Modern Approach, Pearson, 2017.
2. Sheetal Taneja, Naveen Kumar, Python Programming A Modular Approach with
Graphics, Database, Mobile, and WebApplications, Pearson, 2017.
3. Michael Dawson, Cengage Learning ,Programming with Python, A Book, India
Edition.5th Edition 2013
4. W. Chun ,Core Python Programming, Pearson.2nd Edition ,2006.
5. Kenneth A. Lambert, Introduction to Python, Cengage 2nd Edition, 2017.

Web Link: 1) https://onlinecourses.nptel.ac.in/noc22_cs26/preview


2) https://www.python.org/about/gettingstarted/
ESTD: 2009
CMR TECHNICAL CAMPUS
UGC AUTONOMOUS
Accredited by NBA & NAAC with ‘A’ Grade
Approved by AICTE, New Delhi and JNTU, Hyderabad
Kandlakoya, Medchal Road, Hyderabad- 501 401, Telangana

DEPARTMENT OF CSE (AI & ML)

Institute Vision:
 To Impart quality education in serene atmosphere thus strive for excellence in
Technology and Research.
Institute Mission:
 To Create state of art facilities for effective Teaching- Learning Process.
 Pursue and Disseminate Knowledge based research to meet the needs of Industry &
Society.
 Infuse Professional, Ethical and Societal values among Learning Community.
Department Vision:
 To develop competent and socially responsible engineers in the domain of Artificial
Intelligence & Machine Learning for noteworthy contributions to the society.
Department Mission:
 To educate the students in fundamental principles of computing and develop the skills
needed to solve practical problems using contemporary computer-based technologies.
 To provide State-of-the-art computing laboratory facilities to promote industry-
institute interaction to enhance student’s practical knowledge.
 To Inculcate self-learning abilities, team spirit, and professional ethics among the
students to serve society.
Programme Educational Objectives (PEOs):
PEO-1: Graduates will have the ability to adapt, contribute and innovate new systems in the
key domains of Artificial Intelligence and Machine Learning.
PEO-2: Graduates will have the ability to pursue higher education in reputed institutions
with AI Specialization.
PEO-3: Graduates will be ethically and socially responsible solution providers and
entrepreneurs in the field of Computer Science and Engineering with AI&ML Specialization.
Programme Outcomes (POs):
PO1-Engineering Knowledge: Apply the knowledge of Mathematics, Science, Engineering
fundamentals, and an engineering specialization to the solution of complex engineering
problems.
PO2-Problem Analysis: Identify, formulate, research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of
Mathematics, Natural Sciences, and Engineering Sciences.
ESTD: 2009
CMR TECHNICAL CAMPUS
UGC AUTONOMOUS
Accredited by NBA & NAAC with ‘A’ Grade
Approved by AICTE, New Delhi and JNTU, Hyderabad
Kandlakoya, Medchal Road, Hyderabad- 501 401, Telangana

PO3-Design/Development of Solutions: Design solutions for complex engineering problems


and design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and environmental
considerations.
PO4-Conduct Investigations of Complex Problems: Use research-based knowledge and
research methods including design of experiments, analysis and interpretation of data, and
synthesis of the information to provide valid conclusions.
PO5-Modern Tool Usage: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modeling to complex engineering
activities with an understanding of the limitations.
PO6-The Engineer and Society: Apply reasoning informed by the contextual knowledge to
assess societal, health, safety, legal and cultural issues and the consequent responsibilities
relevant to the professional engineering practice.
PO7-Environment and Sustainability: Understand the impact of the professional
engineering solutions in societal and environmental contexts, and demonstrate the knowledge
of, and need for sustainable development
PO8-Ethics: Apply ethical principles and commit to professional ethics and responsibilities
and norms of the engineering practice
PO9-Individual and Team Work: Function effectively as an individual, and as a member or
leader in diverse teams, and in multidisciplinary settings.
PO10-Communication: Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as, being able to comprehend and
write effective reports and design documentation, make effective presentations, and give and
receive clear instructions.
PO11-Project Management and Finance: Demonstrate knowledge and understanding of
the engineering and management principles and apply these to one’s own work, as a member
and leader in a team, to manage projects and in multidisciplinary environments.
PO12-Life-long Learning: Recognize the need for, and have the preparation and ability to
engage in independent and life-long learning in the broadest context of technological change.
Programme Specific Outcomes(PSOs):
PSO1: Apply the fundamental Knowledge for problem analysis and conduct investigations in
Artificial Intelligence and Machine Learning for sustainable development
PSO2: Design and development of solutions by using modern software for the purpose of
execution of the projects in specialized areas.
PSO3: Inculcate effective communication and ethics for lifelong learning with social
awareness.
WEEK-1
1. i) Use a web browser to go to the Python website http://python.org. This page contains information
about Python and links to Python-related pages, and it gives you the ability to search the Python
documentation.

 The Python interpreter and the extensive standard library are freely available in source or binary form
for all major platforms from the Python web site, https://www.python.org/, and may be freely
distributed.
 The same site also contains distributions of and pointers to many free third party Python modules,
programs and tools, and additional documentation.

Python's documentation
The Python documentation pages are available at https://docs.python.org/3.12/. The most helpful sections are
listed here:
 The Python language reference at https://docs.python.org/3.12/reference/index.html

 The Python standard library documentation at https://docs.python.org/3.12/library/index.html


 This page contains information about Python and links to Python-related pages.
 Python Tutorials,
 Library References
 Python Setup and Usage
 Installing Python Modules etc.

ii). Start the Python interpreter and type help ( ) to start the online help utility.

Python help() Method

The Python help() function invokes the interactive built-in help system. If the argument is a string, then the
string is treated as the name of a module, function, class, keyword, or documentation topic, and a help page
is printed on the console. If the argument is any other kind of object, a help page on the object is displayed.

In this case, just open python interpreter and type help ( ).


Syntax:
help(object)
Parameters:
object: (Optional) The object whose documentation needs to be printed on the console.

To get help, one can enter help mode by typing help() ay python prompt(i.e. >>> prompt) we can see the help
utility appearing as shown in following

Now we can type in the name of a Python object to get helpful information about it:

When we type the name len at the help> prompt and hit Enter , we get help content related to that built-in
function.
We can type ‘topics’ to know about topics in python. Lets enter topics at help prompt.

Among the topics , suppose we want to know about functions, we should enter ‘FUNCTIONS’ in capital letters
since the FUNCTIONS topic is shown in capital letters in help window.
To leave the content and get back to the help> prompt, you can press Q . To leave the help utility, you can
type quit and hit Enter .

We can also use help() with the name of an object as an argument to get information about that object:

Python
>>> help(dir)

Help on built-in function dir in module builtins:

dir(...)
dir([object]) -> list of strings
...

Here dir(), we can use this function to inspect the methods and attributes that are available in a particular object:

Python
>>> dir(str)
['__add__', '__class__', ..., 'title', 'translate', 'upper', 'zfill']

>>> dir(tuple)
['__add__', '__class__', ..., 'count', 'index']
When we call dir() with the name of a Python object as an argument, the function attempts to return a list of valid
attributes for that specific object. This is a convenient way to get an idea of what a given object can do.
2. Start Python interpreter and use it as Calculator
3. I) Write a program to calculate compound interest when principal, rate and number of periods are
given
The formula to calculate compound interest annually is given by:
A = P(1 + R/100) t
Compound Interest = A – P
Where,
● A is amount
● P is the principal amount
● R is the rate and
● T is the time span

# Calculates compound interest


principal=int(input(“Enter the Principal amount:”))
rate=int(input(“Enter the Rate:”))
time=int(input(“Enter the time span:”))
Amount =principal *((1+rate /100)** time)
CI =Amount -principal
print("Compound interest is", CI)
3. II) Given coordinates (x1, y1), (x2, y2) find the distance between two points
Calculate the distance between two points.
The distance formula derived from Pythagorean theorem.

The formula for distance between two point (x1, y1) and (x2, y2) is √((x2 – x1)² + (y2 – y1)²).

Program to find distance between two points of coordinates

print(" To Find the distance between to (x1,y1),(x2,y2) coordinates")


x1=int(input("enter x1 value:"))
y1=int(input("enter y1 value:"))
x2=int(input("enter x2 value:"))
y2=int(input("enter y2 value:"))
pnts1=(x1,y1)
pnts2=(x2,y2)
print("\n you are given two coordinates are:",pnts1,'&',pnts2)
Distance=(((pnts1[0]-pnts2[0])**2)+((pnts1[1]-pnts2[1])**2))**0.5
print("The Distance Between two coordiantes are",Distance)
4. Read name, address, email and phone number of a person through keyboard and print the details.

# read name, contact, email and birthday from user and print them

name = input("Enter your name: ")

address = input("Enter your Address: ")

email = input("Enter your email: ")

phone_number = input("Enter your Phone Number: ")

print("Name: ", name)


print("Address: ", address)
print("Email: ", email)
print("Phone Number: ", phone_number)
WEEK-2:
1. Print the below triangle using for loop.

5
44
333
2222
11111

num=int(input("Please Enter the Number of Rows"))


for i in range(1,num+1):
for j in range(1,i+1):
print(num,end=' ')
num=num-1
print()
2. Write a program to check whether the given input is digit or lowercase character or
uppercasecharacter or a special character (use 'if-else-if' ladder)
Program-1:
ch=input("Please Enter any Character: \t")

if (ch >= 'A' and ch <= 'Z'):


print(ch,"is an UpperCase character");
elif (ch >= 'a' and ch <= 'z'):
print(ch,"is an LowerCase character");
elif(ch>='0' and ch<='9'):
print(ch,"is a digit")
else:
print(ch,"is not an alphabetic character");

Program-2:
ch=input("Please Enter any Character: \t")
if(ch>='0' and ch<='9'):
print(ch,"is a digit")

elif (ch.isUpper):
print(ch,"is an UpperCase character");

elif (ch.isLower):
print(ch,"is an LowerCase character");
else:
print(ch,"is not an alphabetic character");
3. Python Program to Print the Fibonacci sequence using while loop
4. Python program to print all prime numbers in a given interval (use break)

# First, we will take the input:


lower_value = int(input ("Please, Enter the Lowest Range Value: "))
upper_value = int(input ("Please, Enter the Upper Range Value: "))
print ("The Prime Numbers in the range are: ", lower_value,’and’, upper_value)
for number in range (lower_value, upper_value + 1):
# all prime numbers are greater than 1,if number is less than or equal to 1, it is not prime
if number> 1:
for i in range (2, number):
# Check for factors
if (number % i) == 0:
# not a prime number so break inner loop and look for next number
break
else:
print (number)
WEEK-3
1.
I) Write a program to convert a list and tuple into arrays
import numpy as np
#Declare List Elements
my_list = []
list_length = int(input("Enter No of List Elements:" ))
for i in range(list_length):
lst = int(input('Enter Element: '))
my_list.append(lst)
#Display List Elements
print("\n List Elements are: ",end=' ')
for i in my_list:
print(i,end=' ')
#Convert and Display Elements from List to Array
array1=np.asarray(my_list)
print("\n Convert After list to array is : ",array1)

#Declare Tuple Elements


my_tuple = []
tuple_length = int(input("Enter No of List Elements:" ))
for i in range(tuple_length):
tpl = int(input('Enter Element: '))
my_tuple.append(tpl)
#Display List Elements
print("\n Tuple Elements are: ",end=' ')
for i in my_tuple:
print(i,end=' ')
#Convert and Display Elements from List to Array
array2=np.asarray(my_tuple)
print("\n Convert After list to array is : ",array2)
1.

II)Write a program to find common values between two arrays.

from numpy import *


#Declare Array1 Elements
arr1 = array([],int)
length_arr1 = int(input("Enter the number of values you want: "))
for i in range(length_arr1):
values1 =int(input("Element: "))
arr1 = append(arr1, values1)
#Display Array1 Elements
print(arr1)
#Declare Array 2 elements
arr2 = array([],int)
length_arr2 = int(input("Enter the number of values you want: "))
for i in range(length_arr2):
values2 =int(input("Element: "))
arr2 = append(arr2, values2)
#Display Array2 Elements
print(arr2)
#Display Common values between two arrays
common=intersect1d(arr1, arr2)
print("\n Common values between two arrays",common)
2. Write a function called gcd that takes parameters a and b and returns their greatest common divisor

Program-1
# Python code to demonstrate naive
# method to compute gcd ( recursion )
def gcd(a, b):
if(b == 0):
return a
else:
return gcd(b, a % b)
# Driver program to test above function
m = int(input("Enter a Number: "))
n = int(input("Enter b Number: "))
print("The gcd of {0} and {1} is : ".format(m,n),end=' ')
print(gcd(m, n))

Program-2
# Recursive function to return gcd of a and b
def gcd(a, b):
# Everything divides 0
if (a == 0):
return b
if (b == 0):
return a
# base case
if (a == b):
return a
# a is greater
if (a > b):
return gcd(a-b, b)
return gcd(a, b-a)

# Driver program to test above function


m = int(input ("Please, Enter the First Value: "))
n = int(input ("Please, Enter the Second Value: "))
if(gcd(m, n)):
print('GCD of', m, 'and', n, 'is', gcd(m, n))
else:
print('not found')
3. Write a function called palindrome that takes a string argument and returns True if it is a palindrome
and False otherwise.
Remember that you can use the built-in function len to check the length of a string.

#Declare a Function with palindrome with argument str


def palindrome(str):
#use built-in function len to check the length of a string
for i in range(0, int(len(str)/2)):
if str[i] != str[len(str)-i-1]:
return False
return True

# main function
s = input("Enter a String: ")
#call the function to check the string is palindrome or not
ans =palindrome(s)
print(s," is Palindrome:",end='')
if (ans):
print("TRUE ")
else:
print("FALSE")
WEEK-4
1. Write a function called is_sorted that takes a list as a parameter and returns True if the list is sorted
in ascending order and False otherwise.

def is_sorted(list):
x=list[:]
x.sort()
if(list==x):
return True
else:
return False
n = int (input ("Enter number of elements in the List: "))
# Declare an empty list
list1 = []
# Iterate for n times take inputs
for i in range (n):
# Take input of ith element as x.
print(i+1,end=' ')
x = int(input(" Element"))
# Append 'x' to the list1.
list1.append(x)
print("Elements are : ",list1)
print(is_sorted(list1))
2. Write a function called has_duplicates that takes a list and returns True if there is any
element that appears more than once. It should not modify the original list.

def has_duplicate(list):
for i in range(len(list)):
for j in range(0, i):
if list[i] == list[j]:
return 'true'
return 'false'
n = int (input ("Enter number of elements: "))
# Declare an empty list
list1 = []
# Iterate for n times take inputs
for i in range (n):
# Take input of Ith element as x.
print(i+1,end=' ')
x = int(input(" Element"))
# Append 'x' to the list1.
list1.append(x)
print("Elements are : ",list1)
print(has_duplicate(list1))
2.I) Write a function called remove_duplicates that takes a list and returns a new list with only the
unique elements from the original. Hint: they don’t have to be in the same order.

def remove_duplicates(L):
LS = sorted(L)
res = []
prev = None
for el in LS:
if el != prev:
res.append(el)
prev = el
return res

n = int (input ("Enter number of elements: "))


# Declare an empty list
L = []
# Iterate for n times take inputs
for i in range (n):
# Take input of ith element as x.
print(i+1,end=' ')
x = int(input(" Element"))
# Append 'x' to the list1.
L.append(x)

print("Elements are : ",L)


print("\n ",remove_duplicates(L))
2.II)
The wordlist I provided, words.txt, doesn’t contain single letter words. So you might want to add“I”,
“a”, and the empty string.

"""Reads the words in words.txt and wordlist


I provided i.e I,a, empty string."""

with open('words.txt','w') as f:
letters=['I','a',""]
# have to add single letter words to the word list;
# also, the empty string is considered a word.
for l in letters:
f.write(l)
f.write('\n')
2. III) Write a python code to read dictionary values from the user. Construct a function to invert its
content. i.e., keys should be values and values should be keys
#Creating a dictionary to read values from the user
my_dict={}
print("How many elements ?", end=' ')
n=int(input())
for i in range(n):
print("Enter key:",end=' ')
k=input()
print("Enter its value: ",end=' ')
v=int(input())
my_dict.update({k:v})
print("The dictionary is: ",my_dict)

new_dict = dict([(value, key) for key, value in my_dict.items()])

# Printing original dictionary


print ("Original dictionary is : ")
print(my_dict)

print()

# Printing new dictionary after swapping keys and values


print ("Dictionary after swapping is : ")
print("keys: values")
for i in new_dict:
print(i, " : ", new_dict[i])
3. i) Add a comma between the characters. If the given word is 'Apple', it should become 'A,p,p,l,e'

x = "Apple"
y = ','.join(x)
print(y)

OR

x = "Apple"
y=''
for i in x:
y += i + ','*1
y = y.strip()
print(repr(y))

3. ii) Remove the given word in all the places in a string?

# Write a program that input a string and ask


# user to delete a given word from a string.

text = input('Enter a string: ')


words = text.split()

data = input('Enter a word to delete: ')


status = False

for word in words:


if word == data:
words.remove(word)
status = True

if status:
text = ' '.join(words)
print('String after deletion:',text)
else:
print('Word not present in string.')
3. iii) Write a function that takes a sentence as an input parameter and replaces the first letter of
every word with the corresponding upper case letter and the rest of the letters in the word by
corresponding letters in lower case without using a built-in function?
import string
import io
#Method to convert the string
def capitalize_word(s):
#create a stream of the string
s=io.StringIO(s)
result=" "
#Declare a character of space
#To identify that the next character is starting of a new word
for word in s.read().split():
word=word.lower()
word=word.capitalize()
result +=word+" "
#Return the string with trimming
return result.strip()
#Driver Code
if __name__=="__main__":
#Declare the string
s1="cMR technical campus , dept of AIML"
#call the method to capitalize each word
print(capitalize_word(s1))
4. Writes a recursive function that generates all binary strings of n-bit length
# Function to print the output
def printTheArray(arr, n):

for i in range(0, n):


print(arr[i], end = " ")

print()

# Function to generate all binary strings


def generateAllBinaryStrings(n, arr, i):

if i == n:
printTheArray(arr, n)
return

# First assign "0" at ith position


# and try for all other permutations
# for remaining positions
arr[i] = 0
generateAllBinaryStrings(n, arr, i + 1)

# And then assign "1" at ith position


# and try for all other permutations
# for remaining positions
arr[i] = 1
generateAllBinaryStrings(n, arr, i + 1)

# Driver Code
if __name__ == "__main__":

n=4
arr = [None] * n

# Print all binary strings


generateAllBinaryStrings(n, arr, 0)
WEEK-5
1. I) Write a python program that defines a matrix and prints

#python program that defines a matrix and prints


from numpy import *
#accept number of rows and columns into R, C
R = int(input("Enter the number of rows:"))
C = int(input("Enter the number of columns:"))
#accept matrix elements as list
# Initialize matrix
m_list = []
print("Enter the entries row wise:")

# 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()))
m_list.append(a)
x=reshape(matrix(m_list),(R,C))
print("The Matrix is :")
print(x)
1.II) Write a python program to perform addition of two square matrices

#To perform addition of two square matrices


import sys
from numpy import*
r1, c1 = [int(a) for a in input("First matrix rows, cols: ").split()]
r2, c2 = [int(a) for a in input("Second matrix rows, cols: ").split()]
if c1!=r2:
print('Multiplication is not possible')
sys.exit()
#accept First matrix elements as list
m_list1 = []
print("Enter the entries row wise:")
# For user input
for i in range(r1): # A for loop for row entries
for j in range(c1): # A for loop for column entries
m_list1.append(int(input()))
matrix1=reshape(matrix(m_list1),(r1,c1))
print("The First Matrix is :")
print(matrix1)
#accept Second matrix elements as list
m_list2 = []
print("Enter the entries row wise:")
# For user input
for i in range(r2): # A for loop for row entries
for j in range(c2): # A for loop for column entries
m_list2.append(int(input()))
matrix2=reshape(matrix(m_list2),(r2,c2))
print("The Second Matrix is :")
print(matrix2)
#Addition of two matrices
print('The Addition of Two matrix:')
add_matrix = matrix1 + matrix2
print(add_matrix)
1.III) Write a python program to perform multiplication of two square matrices

#To perform multiplication of two square matrices


import sys
from numpy import*
r1, c1 = [int(a) for a in input("First matrix rows, cols: ").split()]
r2, c2 = [int(a) for a in input("Second matrix rows, cols: ").split()]
if c1!=r2:
print('Multiplication is not possible')
sys.exit()
#accept First matrix elements as list
m_list1 = []
print("Enter the entries row wise:")
# For user input
for i in range(r1): # A for loop for row entries
for j in range(c1): # A for loop for column entries
m_list1.append(int(input()))
matrix1=reshape(matrix(m_list1),(r1,c1))
print("The First Matrix is :")
print(matrix1)
#accept Second matrix elements as list
m_list2 = []
print("Enter the entries row wise:")
# For user input
for i in range(r2): # A for loop for row entries
for j in range(c2): # A for loop for column entries
m_list2.append(int(input()))
matrix2=reshape(matrix(m_list2),(r2,c2))
print("The Second Matrix is :")
print(matrix2)
#Multiplication of two matrices
print('The Addition of Two matrix:')
mul_matrix = matrix1 * matrix2
print(mul_matrix)
2. How do you make a module? Give an example of construction of a module using different
geometrical shapes and operations on them as its functions.
Module:
In Python, Modules are simply files with the “.py” extension containing Python code that can be imported
inside another Python Program.

Geometry.py
# a module using different geometrical shapes and operations on them as its functions.
def geometrical_shapes(name):

# converting all characters into lower cases


name = name.lower()

# check for the conditions


if name == "rectangle":
l = int(input("Enter rectangle's length: "))
b = int(input("Enter rectangle's breadth: "))

# calculate area of rectangle


rect_area = l * b
print("The area of rectangle is. ",rect_area)

elif name == "square":


s = int(input("Enter square's side length: "))

# calculate area of square


sqt_area = s * s
print("The area of square is.",sqt_area)

elif name == "triangle":


h = int(input("Enter triangle's height length: "))
b = int(input("Enter triangle's breadth length: "))

# calculate area of triangle


tri_area = 0.5 * b * h
print("The area of triangle is ",tri_area)

elif name == "circle":


r = int(input("Enter circle's radius length: "))
pi = 3.14

# calculate area of circle


circ_area = pi * r * r
print(f"The area of circle is.",circ_area)

elif name == 'parallelogram':


b = int(input("Enter parallelogram's base length: "))
h = int(input("Enter parallelogram's height length: "))

# calculate area of parallelogram


para_area = b * h
print("The area of parallelogram is.",para_area)
else:
print("Sorry! This shape is not available")
main.py
from Geometry import *
# driver code
if __name__ == "__main__" :

print("Calculate Shape Area")


shape_name = input("Enter the name of shape whose area you want to find: ")

# function calling
geometrical_shapes(shape_name)
3. Use the structure of exception handling all general purpose exceptions.
# Use the structure of exception handling all general purpose exceptions.

from operator import mul, truediv

def calculate(operator, operand1, operand2):

return operator(operand1, operand2)

try:

first = float(input("What is your first number? "))

second = float(input("What is your second number? "))

operation = input("Enter either * or /: ")

if operation == "*":

answer = calculate(mul, first, second)

elif operation == "/":

answer = calculate(truediv, first, second)

else:

raise RuntimeError(f"'{operation}' is an unsupported operation")

except (RuntimeError, ValueError, ZeroDivisionError) as error:

print(f"A {type(error).__name__} has occurred")

match error:

case RuntimeError():

print(f"You have entered an invalid symbol: {error}")

case ValueError():

print(f"You have not entered a number: {error}")

case ZeroDivisionError():

print(f"You can't divide by zero: {error}")

else:

print(f"{first} {operation} {second} = {answer}")


Week-6:
1. a. Write a function called draw_rectangle that takes a Canvas and a Rectangle as
arguments and draws a representation of the Rectangle on the Canvas.

Note: To install swampy in command prompt

#pip install swampy


from swampy.World import *
class Canvas(object):
"""Represents a canvas.
attributes: width, height, background color"""
a_canvas = Canvas()
a_canvas.width = 500
a_canvas.height = 500
class Rectangle(object):
"""Represents a rectangle."""
box = Rectangle()
box.color = 'orange'
box.bbox = [[-100, -60],[100, 60]]
def draw_rectangle(canvas, rectangle):
drawn_canvas = world.ca(canvas.width, canvas.height)
drawn_canvas.rectangle(rectangle.bbox, fill=rectangle.color)

world = World()
draw_rectangle(a_canvas,box)
world.mainloop()
1. b. Add an attribute named color to your Rectangle objects and modify draw_rectangle
so that ituses the color attribute as the fill color.

from swampy.World import *


class Canvas(object):
"""Represents a canvas.
attributes: width, height, background color"""
a_canvas = Canvas()
a_canvas.width = 500
a_canvas.height = 500
class Rectangle(object):
"""Represents a rectangle."""
box = Rectangle()
box.color = 'orange'
box.bbox = [[-100, -60],[100, 60]]
def draw_rectangle(canvas, rectangle):
drawn_canvas = world.ca(canvas.width, canvas.height)
drawn_canvas.rectangle(rectangle.bbox, fill=rectangle.color)

world = World()
draw_rectangle(a_canvas,box)
world.mainloop()
1. c. Write a function called draw_point that takes a Canvas and a Point as arguments and
draws arepresentation of the Point on the Canvas.

from swampy.World import *


class Canvas(object):
"""Represents a canvas.
attributes: width, height, background color"""
a_canvas = Canvas()
a_canvas.width = 500
a_canvas.height = 500
class Point(object):
"represents a point in 2-D space"
p = Point()
p.x = 60
p.y = 15
def draw_point(canvas, point):
bbox = [[point.x, point.y], [point.x, point.y]]
drawn_canvas = world.ca(canvas.width, canvas.height)
drawn_canvas.rectangle(bbox, fill="black")

world = World()
draw_point(a_canvas,p)
world.mainloop()
1. d. Define a new class called Circle with appropriate attributes and instantiate a few Circle
objects.Write a function called draw_circle that draws circles on the canvas.

from swampy.World import *


class Canvas(object):
"""Represents a canvas.
attributes: width, height, background color"""
a_canvas = Canvas()
a_canvas.width = 500
a_canvas.height = 500

class Point(object):
"represents a point in 2-D space"
p = Point()
p.x = 60
p.y = 15

class Circle(object):
"""Represents a circle.
attributes: center point, radius"""
c = Circle()
c.radius = 50
c.center = Point()
c.center.x = 20
c.center.y = 20
def draw_circle(canvas, circle):
drawn_canvas = world.ca(canvas.width, canvas.height)
drawn_canvas.circle([circle.center.x, circle.center.y], circle.radius)

world = World()
draw_circle(a_canvas,c)
world.mainloop()
2. Write a Python program to demonstrate the usage of Method Resolution Order (MRO) in
multiplelevels of Inheritances.

#Method Resolution Order(MRO)


#A program to understand the order of execution of methods
#in several base classes according to MRO
#Multiple inheritance with several classes
class A(object):
def method(self):
print("A class method")
super().method()
class B(object):
def method(self):
print("B class method")
super().method()
class C(object):
def method(self):
print("C class method")
class X(A,B):
def method(self):
print("X class method")
super().method()
class Y(B,C):
def method(self):
print("Y class method")
super().method()
class P(X,Y,C):
def method(self):
print("P class method")
super().method()
pobj=P()
pobj.method()
3. Write a python code to read a phone number and email-id from the user and
validate it forcorrectness.
import re
#Define a function for validate mobile number
def valid_number(number):

# 1) Begins with 0 or 91
# 2) Then contains 6,7 or 8 or 9.
# 3) Then contains 9 digits
Pattern = re.compile("(0|91)?[6-9][0-9]{9}")
return Pattern.match(number)

#Define a function for validate email address


def validate_email(email):
# regular expression for an email address
pattern = re.compile(r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$")
# check if the pattern matches the email address
match = pattern.search(email)
return match

#main method
if __name__ == "__main__":

number = input("Enter your mobile number: ")


if (valid_number(number)):
print ("Valid Number")
else :
print ("Invalid Number")
email = input("Enter email address: ")
match = validate_email(email)
if match:
print("Valid email address.")
else:
print("Invalid email address.")
Week- 7
1. Write a Python code to merge two given file contents into a third file.
First file: file1.txt
CMR TECHNICAL CAMPAS
OUR VISION:
To Impart quality education in serene atmosphere thus strive for excellence in Technology and Research.

Second file: file2.txt


OUR MISSION:
To Create state of art facilities for effective Teaching- Learning Process.
Pursue and Disseminate Knowledge based research to meet the needs of Industry & Society.
Infuse Professional, Ethical and Societal values among Learning Community.

Merge.py
# Creating a list of filenames
filenames = ['file1.txt', 'file2.txt']

# Open file3 in write mode


with open('file3.txt', 'w') as outfile:

# Iterate through list


for names in filenames:

# Open each file in read mode


with open(names) as infile:

# read the data from file1 and file2 and write it in file3
outfile.write(infile.read())

# Add '\n' to enter data of file2


# from next line
outfile.write("\n")

mergefile = open("file3.txt")

# Reading from file


print(mergefile.read())

mergefile.close()
2. Write a Python code to open a given file and construct a function to check for given words
present init and display on found.

Note : create a text file (i.e.. sample.txt) in which we want to count the words in Python

Example:
file1.txt
CMR TECHNICAL CAMPAS
OUR VISION:
To Impart quality education in serene atmosphere thus strive for excellence in Technology and Research.

Search.py
#To Construct a function to Search a word in a file
def search_word(file_path, word):
with open(file_path, 'r') as file:
# read all content of a file
content = file.read()
# check if string present in a file
if word in content:
print('The word {0} exist in a file'.format(word))
else:
print('The word {0} does not exist in a file'.format(word))

#To Enter a word for check given words present in it or not


word=input("Enter a word for searching in file :")
search_word(r'file1.txt', word)
3. Write a Python code to Read text from a text file, find the word with most number of occurrences

Note : create a text file (i.e.. sample.txt) in which we want to count the words in Python

Example:
Sample.txt
Mango banana apple pear
Banana grapes strawberry
Apple pear mango banana
Kiwi apple mango strawberry

Count_word.py

fname = input("Enter file name: ")


word=input("Enter word to be searched:")
k = 0

with open(fname, 'r') as f:


for line in f:
words = line.split()
for i in words:
if(i==word):
k=k+1
print("Occurrences of the word {0} is :".format(word))
print(k)
4. Write a function that reads a file file1 and displays the number of words, number of
vowels, blankspaces, lower case letters and uppercase letters.
# program to displays the number of words, number of vowels,
# blankspaces,lower case letters and uppercase letters
def analyze_file(file_name):
try:
# Opening the file in read mode
with open(file_name, 'r') as file:
#Read the file Content
content=file.read()
#count the number of words
words=content.split()
word_count=len(words)
#count the number of vowels
vowels="aeiou"
vowel_count=sum(content.lower().count(vowel) for vowel in vowels)
#count the number of blank spaces
blank_space_count=content.count(' ')
# count the number of lowercase letters
lowercase_count = 0
uppercase_count = 0
for i in content:
if i.isupper() == True:
uppercase_count = uppercase_count + 1
elif i.islower() == True:
lowercase_count = lowercase_count + 1
else:
None
# Print the desired output on the console.
print(f"Number of words : {word_count}")
print(f"Number of vowels : {vowel_count}")
print(f"Number of Blankspaces: {blank_space_count}")
print(f"Number of Lowercase letters : {lowercase_count}")
print(f"Number of Uppercase letters : {uppercase_count}")
except FileNotFoundError:
print("File not found.")
# Calling the function counting which gives the desired output
analyze_file('file1.txt')
Week - 8:
1. Import numpy, Plotpy and Scipy and explore their functionalities.

NumPy – Introduction
NumPy is a Python package. It stands for 'Numerical Python'. It is a library con-sisting of
multidimensional array objects and a collection of routines for processing of array.
Numeric, the ancestor of NumPy, was developed by Jim Hugunin. Another package Numarray was also
developed, having some additional functionalities. In 2005, Travis Oliphant created NumPy package by
incorporating the features of Numarray into Numeric package. There are many contributors to this open
source project.

Operations using NumPy


Using NumPy, a developer can perform the following operations –
1. Mathematical and logical operations on arrays.
2. Fourier transforms and routines for shape manipulation.
3. Operations related to linear algebra. NumPy has in-built functions for linear algebra and random
number generation.
4. install NumPy, run the following command.
5. Python setup.py install
6. To test whether NumPy module is properly installed, try to import it from Python prompt.
7. import numpy
8. If it is not installed, the following error message will be displayed.
9. Traceback (most recent call last):
10. File "<pyshell#0>", line 1, in <module>
11. import numpy
12. ImportError: No module named 'numpy'
Alternatively, NumPy package is imported using the following syntax –
Example 1
import numpy as np
import numpy as np
a = np.array([1,2,3])
print(a)
The output is as follows
−[1, 2, 3]

Example 2
# more than one dimensions
import numpy as np
a = np.array([[1, 2], [3, 4]])
print(a)
The output is as follows –
[[1, 2]
[3, 4]]
Example 3
# minimum dimensions
import numpy as np
a = np.array([1, 2, 3,4,5], ndmin = 2)
print a
The output is as follows −
[[1, 2, 3, 4, 5]]
Example 4
# dtype parameter
import numpy as np
a = np.array([1, 2, 3], dtype = complex)
print a
The output is as follows −
[ 1.+0.j, 2.+0.j, 3.+0.j]

SciPy - Introduction
SciPy, a scientific library for Python is an open source, BSD-licensed library for mathematics, science
and engineering. The SciPy library depends on NumPy, which provides convenient and fast N-
dimensional array manipulation. The main reason for building the SciPy library is that, it should work
with NumPy arrays. It provides many user-friendly and efficient numerical practices such as routines for
numerical integration and optimization. This is an introductory tutorial, which covers the fundamentals
of SciPy and describes how to deal with its various modules.

Example 1
pip install plotly "notebook>=5.3" "ipywidgets>=7.2"
Inside Jupyter notebook:
import plotly.graph_objs as go
fig = go.FigureWidget()
# Display an empty figure
fig
# Add a scatter chart
fig.add_scatter(y=[2, 1, 4, 3])
# Add a bar chart
fig.add_bar(y=[1, 4, 3, 2])
# Add a title
fig.layout.title = 'Hello FigureWidget'
See the Python documentation for more examples.
Plotpy - Introduction
plotly.py is an interactive, open-source, and browser-based graphing library for Python :sparkles:
Built on top of plotly.js, plotly.py is a high-level, declarative charting library. plotly.js ships with over 30
chart types, including scientific charts, 3D graphs, statistical charts, SVG maps, financial charts, and
more.
plotly.py is MIT Licensed. Plotly graphs can be viewed in Jupyter notebooks, standalone HTML files, or
hosted online on plot.ly.

Example 1(Scatter plot)


N = 100
x = np.random.rand(N)
y = np.random.rand(N)
colors = np.random.rand(N)
sz = np.random.rand(N)*30
fig = go.Figure()
fig.add_scatter(x=x,
y=y,
mode='markers',
marker={'size': sz,
'color': colors,
'opacity': 0.6,
'colorscale': 'Viridis'
});
iplot(fig)

Example 2(Line Plot)


import plotly.plotly as py
import plotly.graph_objs as go
# Create random data with numpy
import numpy as np
N = 500
random_x = np.linspace(0, 1, N)
random_y = np.random.randn(N)
# Create a trace
trace = go.Scatter(
x = random_x,
y = random_y
)
data = [trace]
py.iplot(data, filename='basic-line')
Example 3(Bar plot)
import plotly.plotly as py
import plotly.graph_objs as go
data = [go.Bar(
x=['giraffes', 'orangutans', 'monkeys'],
y=[20, 14, 23]
)]
py.iplot(data, filename='basic-bar')
Example 4(Pie chart)
import plotly.plotly as py
import plotly.graph_objs as go
labels = ['Oxygen','Hydrogen','Carbon_Dioxide','Nitrogen']
values = [4500,2500,1053,500]
trace = go.Pie(labels=labels, values=values)
py.iplot([trace], filename='basic_pie_chart')
2. Install NumPy package with pip and explore it.

Introduction
To run the NumPy program, first, Numpy needs to be installed. Numpy is installed from Python's
official website using pip and conda by running different commands on different operating systems.
Many important packages are automatically installed within the Numpy library.

Steps for Installing NumPy


1. Download and Install Python.
 Python should be installed before installing NumPy.
 Download Python from Python's official website according to the operating system. After
installing Python, Numpy is installed using different commands in different operating systems.

Installing NumPy on Windows Operating System


Steps for installing NumPy on Windows:
1. Install NumPy using the following PIP command in the command prompt terminal:

pip install numpy


The installation will start automatically, and Numpy will be successfully installed with its latest version

Verify NumPy Installation by typing the command given below in cmd:

pip show Numpy

It will show the location and numpy version installed.


Import NumPy Package

1. Create python Environment in cmd by typing: Python

2. Type command import numpy as np


Upgrade NumPy by using the following command:

pip install –upgrade numpy

Shows message: Requirement already satisfied: numpy in [location (version)]

By performing all the above steps, Numpy will be successfully installed.


3. Write a program to implement Digital Logic Gates – AND, OR, NOT, EX-OR

Logic gates are elementary building blocks for any digital circuits. It takes one or two inputs and
produces output based on those inputs. Outputs may be high (1) or low (0). Logic gates are used for
circuits that perform calculations, data storage, or show off object-oriented programming especially the
power of inheritance.
Types of Logic Gates in Python
There are seven basic logic gates in Python. These are the following:
 AND Gate
 OR Gate
 NOT Gate
 NAND Gate
 NOR Gate
 XOR Gate

1. AND Gate in Python


The AND gate gives an output of 1 if both the two inputs are 1, it gives 0 otherwise.
# working of AND gate
def AND (a, b):
if a == 1 and b == 1:
return True
else:
return False
# Driver code
if __name__=='__main__':
print(AND(1, 1))

print("+---------------+----------------+")
print(" | AND Truth Table | Result |")
print(" A = False, B = False | A AND B =",AND(False,False)," | ")
print(" A = False, B = True | A AND B =",AND(False,True)," | ")
print(" A = True, B = False | A AND B =",AND(True,False)," | ")
print(" A = True, B = True | A AND B =",AND(True,True)," | ")
2. OR Gate in Python
The OR gate gives an output of 1 if either of the two inputs are 1, it gives 0 otherwise.
# working of OR gate
def OR(a, b):
if a == 1 or b ==1:
return True
else:
return False
# Driver code
if __name__=='__main__':
print(OR(0, 0))
print("+---------------+----------------+")
print(" | OR Truth Table | Result |")
print(" A = False, B = False | A OR B =",OR(False,False)," | ")
print(" A = False, B = True | A OR B =",OR(False,True)," | ")
print(" A = True, B = False | A OR B =",OR(True,False)," | ")
print(" A = True, B = True | A OR B =",OR(True,True)," | ")

3. NOT Gate in Python


It acts as an inverter. It takes only one input. If the input is given as 1, it will invert the result as 0 and
vice-versa.
# working of Not gate

def NOT(a):
return not a
# Driver code
if __name__=='__main__':
print(NOT(0))

print("+---------------+----------------+")
print(" | NOT Truth Table | Result |")
print(" A = False | A NOT =",NOT(False)," | ")
print(" A = True, | A NOT =",NOT(True)," | ")
4. XOR Gate in Python
The XOR gate gives an output of 1 if either of the inputs is different, it gives 0 if they are the same.
# working of Xor gate

def XOR (a, b):


if a != b:
return 1
else:
return 0

# Driver code
if __name__=='__main__':
print(XOR(5, 5))

print("+---------------+----------------+")
print(" | XOR Truth Table | Result |")
print(" A = False, B = False | A XOR B =",XOR(False,False)," | ")
print(" A = False, B = True | A XOR B =",XOR(False,True)," | ")
print(" A = True, B = False | A XOR B =",XOR(True,False)," | ")
print(" A = True, B = True | A XOR B =",XOR(True,True)," | ")
4. Write a program to implement Half Adder, Full Adder, and Parallel Adder

Half Adder
Given two inputs of Half Adder A, B. The task is to implement the Half Adder circuit and Print output i.e
sum and carry of two inputs

Logical Expression:
Sum = A XOR B
Carry = A AND B

Truth Table:

program to implement Half Adder


import numpy as np
def half_adder(A, B):
Sum = np.bitwise_xor(A, B)
Carry = np.bitwise_and(A, B)
return Sum, Carry
# Driver code
A=0
B=1
Sum, Carry = half_adder(A, B)
print("Sum:", Sum)
print("Carry:", Carry)
Full Adder :
A Full Adder is a logical circuit that performs an addition operation on three one-bit binary numbers.
The full adder produces a sum of the three inputs and carry value.

Logical Expression :
SUM = C-IN XOR ( A XOR B )
C-0UT= A B + B C-IN + A C-IN
Truth Table :

python program to implement full adder


# python program to implement full adder
# Function to print sum and C-Out
def half_adder(a, b):
# ^ is logical xor in python
sum = a ^ b
carry = a and b
return carry,sum

# A binary full adder


# The full adder can add 3 bits (can handle an incoming carry)
# Also returns a sum and carry
def full_adder(carry_in, a, b):
carry1,sum1 = half_adder(carry_in,a)
carry2,sum = half_adder(sum1,b)
carry = carry1 or carry2
# printing the values
print("Sum = ", sum)
print("C-Out = ", carry)

# Driver code
A=0
B=0
C=1
# passing three inputs of fulladder as arguments to get result function
full_adder(A, B, C)
Parallel Adder
A Parallel Adder is a digital circuit capable of finding the arithmetic sum of two binary numbers that
is greater than one bit in length by operating on corresponding pairs of bits in parallel.

def binary_adder(a,b):
an = len(a)
bn = len(b)

# Convert strings to list of bits -- very functional syntax here


al = list(int(x,2) for x in list(a))
bl = list(int(x,2) for x in list(b))

# Pad smaller list with 0's


dif = an - bn
# more digits in a than b
if dif > 0:
for i in range(dif):
bl.insert(0,0)
else:
for i in range(abs(dif)):
al.insert(0,0)

print(al)
print(bl)

result = []
carry = 0
# Iterate through list right to left, calling full_adder each time and
# inserting the sum each time
for i in range(len(al)-1,-1,-1):
carry,sum = full_adder(carry,al[i],bl[i])
result.insert(0,sum)
print result
result.insert(0,carry)

return ''.join(str(x) for x in result)


# Driver code
A=0
B=0
# passing two inputs of parallel adder as arguments to get result function
binary_adder(A,B)
5. Write a GUI program to create a window wizard having two text labels, two text fields and
two buttonsas Submit and Reset.
Our first GUI will be a window with a label and two buttons:
from tkinter import Tk, Label, Button
class MyFirstGUI:
def __init__(self, master):
self.master = master
master.title("A simple GUI")
self.label = Label(master, text="This is our first GUI!")
self.label.pack()
self.greet_button = Button(master, text="Greet", command=self.greet)
self.greet_button.pack()
self.close_button = Button(master, text="Close", command=master.quit)
self.close_button.pack()
def greet(self):
print("Greetings!")
root = Tk()
my_gui = MyFirstGUI(root)
root.mainloop()

Example for the Button Class


The following script defines two buttons: one to quit the application and another one for the action, i.e.
printing the text "Tkinter is easy to use!" on the terminal.
import tkinter as tk
def write_slogan():
print("Tkinter is easy to use!")
root = tk.Tk()
frame = tk.Frame(root)
frame.pack()
button = tk.Button(frame,
text="QUIT",
fg="red",
command=quit)
button.pack(side=tk.LEFT)
slogan = tk.Button(frame,
text="Hello",
command=write_slogan)
slogan.pack(side=tk.LEFT)
root.mainloop()
The result of the previous example looks like this:

You might also like