R22 - IT - Python Programming Lab Manual
R22 - IT - Python Programming Lab Manual
for WOMEN
(Approved by AICTE, New Delhi and Affiliated to JNTUH)
Nizampet Cross Roads, JNTUH Kukatpally Hyderabad – 500085
LAB MANUAL
PYTHON PROGRAMMING
I List of Experiments ii
II V/M /POs/PSOs/PEOs iv
III Syllabus ix
i
List of Experiments
ii) Start the Python interpreter and type help() to start the online help
utility.
1 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 are given.
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.
1. Print the below triangle using for loop.
5
44
333
2222
11111
2 2. Write a program to check whether the given input is digit or lowercase
character or uppercase character 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
ii
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.
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.
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.
ii). The wordlist I provided, words.txt, doesn’t contain single
letter words. So you might want to add “I”, “a”, and the empty
4 string.
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.
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 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?
4. Writes a recursive function that generates all binary strings of n-bit length
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
5 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.
3. Use the structure of exception handling all general purpose exceptions
7 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, blank spaces, lower case letters and uppercase
letters.
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
8
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 buttons as Submit and Reset
iv
RISHI M.S INSTITUTE OF ENGINEERING & TECHNOLOGY FOR WOMEN
(Affiliated to JNTUH University, Approved by AICTE)
To be a center of excellence in producing women engineers and scientists who are professionally
competent social leaders to face multi-disciplinary global environment by imparting quality technical
education, values and ethics through innovation methods of teaching and learning.
To promote women technocrats capable enough to resolve the problems faced by the society using
the knowledge imparted.
To prepare self-reliant women engineering for technological growth of the nation and society by
laying strong theoretical foundation accompanied by wide practical training.
To equip the young women with creative thinking capabilities and empowering them towards
innovation.
v
RISHI M.S INSTITUTE OF ENGINEERING & TECHNOLOGY FOR WOMEN
(Affiliated to JNTUH University, Approved by AICTE)
Adopting creative techniques to nurture and strengthen the core skill of Computer Science.
Introduce students to the most recent technological advancements.
Impart quality education, improve the research, entrepreneurial, and employability skills of women
technocrats.
Instil professional ethics and a sense of social responsibility in students.
Strengthen the Industry-Academia interface, which will enable graduates to emerge as
academic leaders or inspiring entrepreneurs
vi
RISHI M.S INSTITUTE OF ENGINEERING & TECHNOLOGY FOR WOMEN
(Affiliated to JNTUH University, Approved by AICTE)
vii
RISHI M.S INSTITUTE OF ENGINEERING & TECHNOLOGY FOR WOMEN
(Affiliated to JNTUH University, Approved by AICTE)
PSO 1: Improve the student's ability to decipher the basic principles and methodology of computer
systems. Improve the students' ability to absorb facts and technical ideas in order to build and
develop software.
PSO 2: The capacity to create novel job routes as an entrepreneur using modern computer languages
and evolving technologies like SDLC, Python, Machine Learning, Social Networks, Cyber
Security, Mobile Apps etc.
viii
RISHI M.S INSTITUTE OF ENGINEERING & TECHNOLOGY FOR WOMEN
(Affiliated to JNTUH University, Approved by AICTE)
PEO-1: Engineering graduates with excellent fundamental and technical skills will have
successful careers in industry, meeting the needs of Indian and worldwide firms.
PEO-2: With determination, development, self-reliance, leadership, morality, and moral principles,
engineering graduates will become successful entrepreneurs who will leverage employability.
PEO-3: To support personal and organisational progress, engineering graduates will pursue higher
education and engage in lifelong learning.
ix
SYLLABUS
Python Programming Lab
B.TECH I Year II Sem
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.
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
are given.
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
uppercase character 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)
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 palindrome
and 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
sorted in ascending order and False otherwise.
x
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.
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.
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.
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.
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
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?
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 geometrical
shapes 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
and draws a representation of the Rectangle on the Canvas.
b. Add an attribute named color to your Rectangle objects and modify draw_rectangle so that
it uses 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
a representation 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
multiple levels of Inheritances.
3. Write a python code to read a phone number and email-id from the user and validate it
for correctness.
xi
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
in it 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,
blank spaces, 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 buttons as Submit and Reset.
TEXT BOOKS:
1. Supercharged Python: Take your code to the next level, Overland
2. Learning Python, Mark Lutz, O'reilly
REFERENCE BOOKS:
1. Python for Data Science, Dr. Mohd. Abdul Hameed, Wiley Publications - 1st Ed. 2021.
2. Python Programming: A Modern Approach, Vamsi Kurama, Pearson
3. Python Programming A Modular Approach with Graphics, Database, Mobile, and
Web Applications, Sheetal Taneja, Naveen Kumar, Pearson
4. Programming with Python, A User’s Book, Michael Dawson, Cengage Learning, India Edition
5. Think Python, Allen Downey, Green Tea Press
6. Core Python Programming, W. Chun, Pearson
7. Introduction to Python, Kenneth A. Lambert, Cengage
xii
Course Objectives: To learn
1. Understand the usage of data types, loops and conditional statements and functions.
2. Understand Lists, Dictionaries and Regular expressions in Python.
3. Handle Strings and Files in Python.
4. Learn the implantation of Python modules like Numpy, Plotpy, Turtle
Course Outcomes: After learning the contents of this course the student is able to
CO1. Examine Python syntax and semantics and be fluent in the use of Python flow control
and functions. Demonstrate proficiency in handling Strings and File Systems.
CO2. Create, run and manipulate Python Programs using core data structures like Lists,
Tuples,and Dictionaries.
CO3. Implement exemplary applications related to Numpy, Pandas and matplotlib in Python.
CO - PO MAPPING:
CO PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12
Python CO1 3 2 2 2 2 2
Programming
Lab CO2 3 2 3 2 3 3
CO3 3 3 3 3 3 3
CO - PSO MAPPING:
PSO-1 PSO-2
CO1 1 3
CO2 2 3
CO3 2 3
xiii
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.
ii) Start the Python interpreter and type help() to start the online help utility.
Stepss:
You can download latest version of python for any operating system and install them.
Python Documentation acts as a user manual and provides with all the required
1
information about python including tutorials.
2
Installing Python on Windows
1. Download the latest version installer for Windows from the official website
“http://python.org”
Check this
3
--
4
2. Start a Python interpreter and use it as a Calculator.
Simple arithmetic calculations can be completed at the Python Prompt, also called the Python
REPL. REPL stands for Read Evaluate Print Loop.
The Python REPL shows three arrow symbols >>> followed by a blinking cursor. Programmers
type commands at the >>> prompt then hit [ENTER] to see the results.
3. i) Write a program to calculate compound interest when principal, rate and number
of periods are given.
ii) Given coordinates (x1, y1), (x2, y2) find the distance between two points
Program :
5
Sample Input and Output 1:
enter principal amount : 10000
enter rate of interest : 8.5
enter period : 5
Compound interest is : 5036.566901781247
ii) Given coordinates (x1, y1), (x2, y2) find the distance between two points
Program :
import math
x1=int(input("enter x1 : "))
x2=int(input("enter x2 : "))
y1=int(input("enter y1 : "))
y2=int(input("enter y2 : "))
result = math.sqrt(((x2 - x1 )**2) + ((y2-y1)**2))
print("distance between",(x1,x2),"and",(y1,y2),"is : ",result)
# Note : instead of using the math module - square root can be derived using
exponentiation
# result = ((((x2 - x1 )**2) + ((y2-y1)**2) )**0.5)
6
4. Read name, address, email and phone number of a person through keyboard and
print the details.
Program:
Personal Details
Name: Trishika
Address: Sainikpuri, Secunderabad
Email: [email protected]
Mobile: 8777675747
7
Week 2
Program:
for i in range(rows,0,-1):
print("\n")
for j in range(rows-i+1):
print(i," ", end="")
5
44
33 3
22 2 2
1 11 1 1
8
77
66 6
55 5 5
44 4 4 4
33 3 3 3 3
22 2 2 2 2 2
1 11 1 1 1 1 1
2. Write a program to check whether the given input is digit or lowercase character or
uppercase character or a special character (use 'if-else-if' ladder)
Program:
Program:
9
Sample Input and Output 1:
How many terms? 10
Fibonacci sequence:
0 1 1 2 3 5 8 13 21 34
4. Python program to print all prime numbers in a given interval (use break)
Program:
10
Week 3
Program:
import numpy as np
my_list = [1, 2, 3, 4, 5, 6, 7, 8]
print("\n",type(my_list))
print(my_list)
<class 'tuple'>
([8, 4, 6], [1, 2,
3])
Tuple to array:
<class 'numpy.ndarray'>
[[8 4 6]
[1 2 3]]
Program:
import numpy as np
12
Sample Input and Output 1:
2. Write a function called gcd that takes parameters a and b and returns their
greatest common divisor.
Program:
"""
# Python code to demonstrate subtraction method to compute gcd ( recursion )
# 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)
"""
#function call
print("The gcd of ",a," and ",b," is : ", end="")
print(gcd(a, b))
Sample Input and Output 1:
enter a number : 60
13
enter another number : 25
14
The gcd of 60 and 25 is : 5
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.)
Program :
Method 1:
def Palindrome(s):
return s == s[::-1]
Method 2:
Method 3:
rev = ''.join(reversed(s))
if Palindrome(s):
print("True")
else:
print("False")
Note: Any one of the function definitions can be used to check for palindrome
16
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.
Program:
def is_sorted(a):
print("Given List is : ",a)
for i in range(len(a)-1):
#print(a[i], a[i+1])
if a[i] > a[i+1]:
return False
return True
if (is_sorted([31,42,53,74,95,96])):
print("List is in sorted")
else:
print("List is not sorted")
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.
Program:
def has_duplicates(source):
return len(set(source)) != len(source)
print(has_duplicates([1,2,3,4,4,5,6,7,8]))
17
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.
Program:
def Remove(duplicate):
final_list = []
for num in duplicate:
if num not in final_list:
final_list.append(num)
return final_list
# Driver Code
duplicate = [2, 4, 10, 20, 5, 2, 20, 4]
print(Remove(duplicate))
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.
Program:
with open("word.txt","w") as file:
file.write("I ")
file.write("a")
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.
Program:
n = int(input("Enter the no of entries you want to enter : "))
dict = {}
for i in range(n):
key = int(input("Enter the key : " ))
value = input("Enter the value : ")
dict[key]=value
18
print(dict)
newdict={}
for pair in dict.items():
newdict[pair[1]]=pair[0]
print(newdict)
3. i) Add a comma between the characters. If the given word is 'Apple', it should become
'A,p,p,l,e'
Program:
txt = '"a" "p" "p" "l" "e"'
commas_added = ', '.join(txt.split())
print(commas_added)
output:
"a", "p", "p", "l", "e"
(or)
import
re
# initializing string
test_str = input("Enter a word:")
# printing result
print("Result : " + str(res))
'''
test_str = input("Enter a word:")
res = [s.strip() for s in test_str.split(',')]
Enter a word:a p l e
19
Result : ['a', 'p', 'p', 'l', 'e']
20
ii) Remove the given word in all the places in a string?
Program:
print("Enter the String: ")
text = input()
print()
print(text)
welcome to RISHI
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?
Program:
txt=input("Enter a sentence:")
print(txt.title())
4. Writes a recursive function that generates all binary strings of n-bit length
Program:
def printTheArray(arr, n):
print()
if i == n:
printTheArray(arr, n)
return
21
arr[i] = 0
generateAllBinaryStrings(n, arr, i + 1)
arr[i] = 1
generateAllBinaryStrings(n, arr, i + 1)
# Driver Code
if name == " main ":
n=4
arr = [None] * n
0000
0001
0010
0011
0100
0101
0110
0111
1000
1001
1010
1011
1100
1101
1110
1111
22
Week - 5:
Program:
2st Matrix Y: [[4, 10, 5], [7, 21, 34], [11, 6, 3]]
23
ii) Write a python program to perform addition of two square
matrices Program:
import numpy as np
X = [[1,2,3],
[4 ,5,6],
[7 ,8,9]]
Y = [[9,8,7],
[6,5,4],
[3,2,1]]
print(result)
[[10 10 10]
[10 10 10]
[10 10 10]]
matrices Program:
# 3x3 matrix
X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
# 3x4 matrix
Y = [[5,8,1,2],
[6,7,3,0],
[4,5,9,1]]
# result is 3x4
result = [[0,0,0,0],
[0,0,0,0],
[0,0,0,0]]
24
Sample Input and Output:
Program:
try:
even_numbers = [2,4,6,8]
print(even_numbers[5])
except ZeroDivisionError:
print("Denominator cannot be 0.")
except IndexError:
print("Index Out of
Bound.")
25
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.
b. Add an attribute named color to your Rectangle objects and
modify draw_rectangle so that it uses 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 a representation 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
Program:
import tkinter as tk
root = tk.Tk()
.
2. Write a Python program to demonstrate the usage of Method Resolution Order (MRO)
in multiple levels of Inheritances.
Program:
class ClassA:
def m(self):
print("In ClassA")
class ClassB(ClassA):
def m(self):
print("In ClassB")
class ClassC(ClassA):
def m(self):
print("In ClassC")
obj = ClassD()
26
obj.m()
27
Sample Input and Output:
In
ClassD
In ClassB
In ClassC
In ClassA
2. Write a python code to read a phone number and email-id from the user
and validate it for correctness.
Program:
import re
regex = re.compile(r'([A-Za-z0-9]+[.-_])*[A-Za-z0-9]+@[A-Za-z0-9-]+(\.[A-Z|a-
z]{2,})+')
def isValid(email):
if re.fullmatch(regex, email):
print("Valid
email") else:
print("Invalid email")
isValid("[email protected]")
isValid("[email protected]")
isValid("[email protected]")
isValid("[email protected]")
For mobilenumber:
import re
pattern = re.compile(r"(\+\d{1,3})?\s?\(?\d{1,4}\)?[\s.-]?\d{3}[\s.-]?\d{4}")
test_phone_numbers = [
"+1 (555) 123-4567",
"555-123-4567",
"555 123 4567",
28
"+44 (0) 20 1234 5678",
"02012345678",
29
"invalid phone number"
]
30
Week- 7
1. Write a Python code to merge two given file contents into a third
file. Program:
2. Write a Python code to open a given file and construct a function to check for
given words present in it and display on found.
Program:
3. Write a Python code to Read text from a text file, find the word with most
number of occurrences
Program:
file = open("file1.txt","r")
frequent_word = ""
frequency = 0
words = []
31
# splits each line into
# words and removing spaces
# and punctuations from the input
line_word = line.lower().replace(',','').replace('.','').split(" ");
# Declaring count
= 1;
4. Write a function that reads a file file1 and displays the number of words, number
of vowels, blank spaces, lower case letters and uppercase letters.
Program:
f=open("file1.txt","r")
r=f.read()
u=l=v=c=b=0
for i in r:
if i.isalpha():
if i.isupper():
32
u=u+1
33
if i.islower():
l=l+1
if i.isspace():
b=b+1
if i.lower() in ["a","e","i","o","u"]:
v=v+1
else:
c=c+1
print("Number of Uppercase characters are:",u)
print("Number of Lowercase characters are:",l)
print("Number of blankspaces:",b)
print("Number of Vowels characters are:",v)
print("Number of Consonants characters are:",u)
Sample Output:
Number of Uppercase characters are: 10
Number of Lowercase characters are: 250
Number of blankspaces: 0
Number of Vowels characters are: 98
Number of Consonants characters are: 10
34
Week - 8:
Numpy:
import numpy as np
# Initial Array
arr = np.array([[-1, 2, 0, 4],
[4, -0.5, 6, 0],
[2.6, 0, 7, 8],
[3, -7, 4, 2.0]])
print("Initial Array: ")
print(arr)
# Printing elements at
# specific Indices
Index_arr = arr[[1, 1, 0, 3],
[3, 2, 1, 0]]
print ("\nElements at indices (1, 3), "
"(1, 2), (0, 1), (3, 0):\n", Index_arr)
Elements at indices (1, 3), (1, 2), (0, 1), (3, 0):
[0. 6. 2. 3.]
35
Pyplot
import numpy as np
import matplotlib.pyplot as plt
Python NumPy is a general-purpose array processing package which provides tools for
handling the n-dimensional arrays.
Syntax:
Pip install numpy
Program:
import numpy as np
a=np.array([10,20,30]) #creates a one dimensional array
print("one dimensional array:",a)
b=np.array([[10,20,30], [40,50,60]]) #creates a 2D array
print("Two dimensional array:",b)
c=np.zeros((3,4)) #creates array with all
zeros print("array with all zeros:",c)
d=np.ones((3,4)) #creates array with all ones.
print("array with all zeros:",d)
e=np.full((3,3),5) #creates an array with specified number
print("array with specific number:",e)
g=np.eye(3,dtype=int) #creates an identity matrix
print("Identity Matrx:",g)
36
print("Size of array:",b.size) #gives the total number of elements of the array
print("Data typpe of array elements:",b.dtype) #gives data type of the elements of the
array
print("Size of each array element in bytes:",b.itemsize) #It specifies the size in bytes of
each element of the array
3. Write a program to implement Digital Logic Gates – AND, OR, NOT, EX-
OR Program:
#Python3 program to illustrate 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)," | ")
37
print(" A = True, B = False | A AND B =",AND(True,False)," | ")
print(" A = True, B = True | A AND B =",AND(True,True)," | ")
# 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)," | ")
# 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)," | ")
def NOT(a):
return not a
# Driver code
38
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)," | ")
Adder Program:
# 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
39
# Driver code
A=0
B=1
Sum, Carry = half_adder(A, B)
print("Half Adder:")
print("Sum:", Sum)
print("Carry:", Carry)
5. Write a GUI program to create a window wizard having two text labels, two text
fields and two buttons as Submit and Reset
Program:
window.mainloop()
40