KEMBAR78
Python Manual | PDF | Python (Programming Language) | Regular Expression
0% found this document useful (0 votes)
30 views44 pages

Python Manual

The document outlines a Python Programming Laboratory course for B.Tech. students, detailing course objectives, outcomes, and a series of lab experiments over five weeks. Students will learn to install Python, utilize control structures, and handle data types such as lists and dictionaries, while completing practical exercises. The curriculum includes programming tasks like calculating compound interest, generating Fibonacci sequences, and performing matrix operations.

Uploaded by

Ummineni rajasri
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views44 pages

Python Manual

The document outlines a Python Programming Laboratory course for B.Tech. students, detailing course objectives, outcomes, and a series of lab experiments over five weeks. Students will learn to install Python, utilize control structures, and handle data types such as lists and dictionaries, while completing practical exercises. The curriculum includes programming tasks like calculating compound interest, generating Fibonacci sequences, and performing matrix operations.

Uploaded by

Ummineni rajasri
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 44

R22 B.Tech.

AI&DS JNTU

PYTHON PROGRAMMING LABORATORY

B.Tech. I Year II Sem. L T P C


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

Course Outcomes: After completion of the course, the student should be able to
● Develop the application specific codes using python.
● Understand Strings, Lists, Tuples and Dictionaries in Python
● Verify programs using modular approach, file I/O, Python standard library
● Implement Digital Systems 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
information about Python and links to Python-related pages, and it gives you the ability to search
the Python documentation.
installing Python on Windows takes a series of few easy steps.

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.
2.i Write a program to calculate compound interest when principal, rate and number
of periods are given.
principal = float(input("enter principal amount: "))
rate = float(input("enter rate of intrest: "))
time = float(input("enter the time the money is invested (number of years: )"))
number = float(input("number of times that interest is compounded per unit t: "))
rate = rate/100
amount = principal * pow( 1+(rate/number), number*time)
ci = amount - principal
print('Compound interest = %.2f' %ci)
print('Total amount = %.2f' %amount)
2.ii Given coordinates (x1, y1), (x2, y2) find the distance between two points

x1=int(input("enter x1 : "))
x2=int(input("enter x2 : "))
y1=int(input("enter y1 : "))
y2=int(input("enter y2 : "))
result= ((((x2 - x1 )**2) + ((y2-y1)**2) )**0.5)
print("distance between",(x1,x2),"and",(y1,y2),"is : ",result)
output:
enter x1 : 4
enter x2 : 6
enter y1 : 0
enter y2 : 6
distance between (4, 6) and (0, 6) is : 6.324555320336759
4. Read name, address, email and phone number of a person through keyboard and print
the details.
NAME=str(input("enter the name: "))
ADDR=str(input("enter the address: "))
EMAIL=str(input("enter the email id: "))
PHNO=str(input("enter the phone number: "))
print("hello",NAME,"entered address is:\n",ADDR,"email-id is:\n",EMAIL,"phone number:\n
",PHNO)
output:
enter the name: sravanthi
enter the address: alwal
enter the email id: sravanthi@smec.ac.in
enter the phone number: 9948365487
hello sravanthi entered address is:
alwal email-id is:
sravanthi@smec.ac.in phone number:
9948365487
Week - 2:
Print the below triangle using for loop.
5
44
333
2222
11111
n=int(input("enter number of rows:"))
for i in range(n,0,-1):
for j in range(n+1,i,-1):
print(i, end=' ')
print()
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)
ch = input("Enter a character: ")
if ch >= '0' and ch <= '9':
print("Digit")
elif ch.isupper ():
print("Uppercase character")
elif ch.islower ():
print("Lowercase character")
else:
print("Special character")
3) Program to Print the Fibonacci sequence using while loop
# Program to display the Fibonacci sequence up to n-th term

nterms = int(input("How many terms? "))

# first two terms


n1, n2 = 0, 1
count = 0

# check if the number of terms is valid


if nterms <= 0:
print("Please enter a positive integer")
# if there is only one term, return n1
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
# generate fibonacci sequence
else:
print("Fibonacci sequence:")
while count < nterms:
print(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1

output: How many terms? 5


Fibonacci sequence:
0
1
1
2
3
Python program to print all prime numbers in a given interval (use break)
lower = int(input("enter the lower range"))
upper = int(input("enter the upper range"))
print("Prime numbers between", lower, "and", upper, "are:")

for num in range(lower, upper + 1):


# all prime numbers are greater than 1
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
print(num,end=' ')
Week - 3:
1 i) Write a program to convert a list and tuple into arrays.
from array import array
l1=map(int,input("enter space separated elements into list:").split())
print(l1)
a1=array("i",l1)
print(a1)
for i in a1:
print(i)
t1=map(int,input("enter space separated elements into tuple:").split())
t1=tuple(t1)
print(t1)
a2=array("i",t1)
print(a2)
for i in a2:
print(i)

ii)
ii) Write a program to find common values between two arrays.
from array import*
a1=array("i",[])
n1=int(input("enter size of array1: "))
for i in range(n1):
x=int(input("enter the element into array1:"))
a1.append(x)
a2=array("i",[])
n2=int(input("enter size of array2: "))
for i in range(n2):
x=int(input("enter the element into array2:"))
a2.append(x)
print("elements in array1 are: ",a1)
print("elements in array2 are: ",a2)
a3=array("i",[])
for i in range(len(a1)):
for j in range(len(a2)):
if a1[i]==a2[j]:
a3.append(a1[i])
print("common elements in array1 and array2 are: ",a3)
2 Write a function called gcd that takes parameters a and b and returns their greatest
common divisor.

def gcd(x,y):
while y!=0:
(x,y)=(y,x%y)
return x
x=int(input("enter value of x:"))
y=int(input("enter value of y:"))
result=gcd(x,y)
print("gcd of ",x," and ",y," is: ",result)

output:
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.

def is_palindrome(str):
for i in range(0,int(len(str)/2)):
if(str[i] != str[len(str)-i-1]):
return False
return True
s=input("enter a string:")
ans=is_palindrome(s)
if (ans):
print(s, " is Palindrome")
else:
print(s, " not a palindrome")

output:

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(a):
for i in range(len(a)-1):
if a[i]>=a[i+1]:
return False
return True
a=[]
n=int(input("enter size of a list:"))
print("enter ",n,"elements into list: ")
for i in range(n):
x=int(input())
a.append(x)
print("elements in a list are: ",a)
result=is_sorted(a)
print(result)

output:

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_duplicates(list1):
for i in range(len(list1)):
for j in range(i+1,len(list1)):
if list1[i]==list1[j]:
return True
return False
list1=[]
n=int(input("enter size of list"))
print("enter ",n," elements into list: ")
for i in range(n):
x=int(input())
list1.append(x)
result=has_duplicates(list1)
print("has_duplicates:",result)
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 rem_duplicates(l):
s1=set(l)
return list(s1)
l=[]
n=int(input("enter size of list: "))
print("enter ",n," elements into list: ")
for i in range(n):
x=int(input())
l.append(x)
print("list of elements with duplicates:",l)
s1=rem_duplicates(l)
result=list(s1)
print("list without duplicates:",result)
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.

lines=["I"," ","a"]
with open("words.txt","a") as f:
for line in lines:
f.write(line)
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.
employee={}
n=int(input("enter number of employees:"))
for i in range(n):
name=input("enter employee name: ")
sal=int(input("enter salary: "))
employee[name]=sal
print(employee)
employee={value:key for key, value in employee.items()}
print(employee)

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)
ii Remove the given word in all the places in a string?
print("enter a string:")
text=input()
print("enter a word to delete")
word=input()
text=text.replace(word,"")
print(text)

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?
def convert(s):
ch = list(s)
for i in range(len(s)):
if (i == 0 and ch[i] != ' ' or
ch[i] != ' ' and
ch[i - 1] == ' '):
if (ch[i] >= 'a' and ch[i] <= 'z'):
ch[i] = chr(ord(ch[i]) - ord('a') +
ord('A'))
elif (ch[i] >= 'A' and ch[i] <= 'Z'):
ch[i] = chr(ord(ch[i]) + ord('a') -
ord('A'))
st = "".join(ch)
return st;
s = input("enter a sentence")
print(convert(s));

output:

4 Writes a recursive function that generates all binary strings of n-bit length

def printArray(arr, n):

for i in range(0, n):


print(arr[i], end = " ")
print()
def gbs(n, arr, i):
if i == n:
printArray(arr, n)
return
arr[i] = 0
gbs(n, arr, i + 1)
arr[i] = 1
gbs(n, arr, i + 1)
n = int(input("enter a number to generate binary strings: "))
arr = [None] * n
gbs(n, arr, 0)

Week - 5:
1 i) Write a python program that defines a matrix and prints
R = int(input("Enter the number of rows:"))
C = int(input("Enter the number of columns:"))
matrix = []
print("Enter the entries rowwise:")
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 = " ")
print()
output:

other code:
import numpy as np
R = int(input("Enter the number of rows:"))
C = int(input("Enter the number of columns:"))
print("Enter the entries in a single line (separated by space): ")

# User input of entries in a


# single line separated by space
entries = list(map(int, input().split()))

# For printing the matrix


matrix = np.array(entries).reshape(R, C)
print(matrix)

output:
Enter the number of rows:2
Enter the number of columns:2
Enter the entries in a single line separated by space: 1 2 3 1
[[1 2]
[3 1]]

ii Write a python program to perform addition of two square matrices


# take first matrix inputs
print("Enter the order of matrix 1:")
m, n = list(map(int, input().split()))
print("Enter the order of matrix2:")
p, q = list(map(int, input().split()))
if m==p and n==q:
m1 = []
for i in range(m):
print("Enter row", i, "values into matrix 1::")
row = list(map(int, input().split()))
m1.append(row)

# take second matrix inputs


m2 = []
for j in range(p):
print("Enter row", j, "value into matrix 2:")
row = list(map(int, input().split()))
m2.append(row)

# print both matrices


print("Matrix 1:", m1)
print("Matrix 2:", m2)

# multiply matrix
result = []
for i in range(m):
row = []
for j in range(n):
row.append(0)
result.append(row)
print("Matrix Multiplication:")
for i in range(m):
for j in range(n):
result[i][j] = m1[i][j] + m2[i][j]
for row in result:
print(row)
else:
print("matrix addition is not possible")

iii Write a python program to perform multiplication of two square matrices


# take first matrix inputs
print("Enter the order of matrix 1:")
m, n = list(map(int, input().split()))
print("Enter the order of matrix2:")
p, q = list(map(int, input().split()))
if n==p:
m1 = []
for i in range(m):
print("Enter row", i, "values into matrix 1::")
row = list(map(int, input().split()))
m1.append(row)

# take second matrix inputs


m2 = []
for j in range(p):
print("Enter row", j, "value into matrix 2:")
row = list(map(int, input().split()))
m2.append(row)

# print both matrices


print("Matrix 1:", m1)
print("Matrix 2:", m2)

# multiply matrix
result = []
for i in range(m):
row = []
for j in range(q):
row.append(0)
result.append(row)
print("Matrix Multiplication:")
for i in range(m):
for j in range(q):
for k in range(n):
result[i][j] += m1[i][k] * m2[k][j]
for row in result:
print(row)
else:
print("matrix multiplication is not possible")

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.

Shapes.py
def per_circle(radius):
perimeter = 2 * 3.14 * radius
print("Perimeter of Circle: ", perimeter)
def per_triangle(side1, side2, side3):
perimeter = side1 + side2 + side3
print("Perimeter of Triangle: ", perimeter)

def per_rectangle(height, width):


perimeter = 2 * (height + width)
print("Perimeter of Rectangle: ", perimeter)

def per_square(side):
perimeter = 4 * side
print("Perimeter of Square: ", perimeter)

#Declaring all the required functions with the calculations of area of different shapes
def a_circle(radius):
area = 3.14 * radius * radius
print("Area of Circle: ", area)

def a_triangle(base, height):


area = base * height / 2
print("Area of Triangle: ", area)

def a_rectangle(height, width):


area = height * width
print("Area of Rectangle: ", area)

def a_square(side):
area = side * side
print("Area of Square: ", area)

5_2.py
import shapes
l=20
h=40
shapes.per_rectangle(l,h)
3 Use the structure of exception handling all general purpose exceptions.
x=5
y = "hello"
try:
z=x+y
except TypeError:
print("Error: cannot add an int and a str")
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.
from swampy.TurtleWorld import *

class Rectangle(object):
"""Represents a rectangle."""
box = Rectangle()
box.bbox = [[-100, -60],[100, 60]]

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

def draw_rectangle(canvas, rectangle):


drawn_canvas = world.ca(canvas.width, canvas.height)
drawn_canvas.rectangle(rectangle.bbox)

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 it uses the color attribute as the fill color.
from swampy.TurtleWorld import *

class Rectangle(object):
"""Represents a rectangle."""

box = Rectangle()
box.color = 'blue'
box.bbox = [[-100, -60],[100, 60]]

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

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 a representation of the Point on the Canvas.
from swampy.TurtleWorld import *

class Point(object):
"""represents a point"""
p = Point()
p.x = 60
p.y = 15

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

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.TurtleWorld 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 multiple levels of Inheritances.
Method Resolution Order :
Method Resolution Order(MRO) it denotes the way a programming language resolves a method
or attribute. Python supports classes inheriting from other classes. The class being inherited is
called the Parent or Superclass, while the class that inherits is called the Child or Subclass. In
python, method resolution order defines the order in which the base classes are searched when
executing a method. First, the method or attribute is searched within a class and then it follows
the order we specified while inheriting. This order is also called Linearization of a class and set
of rules are called MRO(Method Resolution Order). While inheriting from another class, the
interpreter needs a way to resolve the methods that are being called via an instance. Thus we
need the method resolution order. For Example
# Python program showing
# how MRO works
class A:
def rk(self):
print(" In class A")
class B(A):
def rk(self):
print(" In class B")
r = B()
r.rk()
Output:
In class B

In the above example the methods that are invoked is from class B but not from class A, and this
is due to Method Resolution Order(MRO).
The order that follows in the above code is- class B – > class A
In multiple inheritances, the methods are executed based on the order specified while inheriting
the classes. For the languages that support single inheritance, method resolution order is not
interesting, but the languages that support multiple inheritance method resolution order plays a
very crucial role. Let’s look over another example to deeply understand the method resolution
order:

# Python program showing


# how MRO works

class A:
def rk(self):
print(" In class A")
class B(A):
def rk(self):
print(" In class B")
class C(A):
def rk(self):
print("In class C")

# classes ordering
class D(B, C):
pass

r = D()
r.rk()
Output:
In class B
In the above example we use multiple inheritances and it is also called Diamond
inheritance and it looks as follows:

Python follows a depth-first lookup order and hence ends up calling the method from class A. By
following the method resolution order, the lookup order as follows.
Class D -> Class B -> Class C -> Class A
Python follows depth-first order to resolve the methods and attributes. So in the above example,
it executes the method in class B.
3 Write a python code to read a phone number and email-id from the user and
validate it for correctness.
import re

# Make a regular expression


# for validating an Email
regex = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,7}\b'

# Define a function for


# for validating an Email
def check(email):

# pass the regular expression


# and the string into the fullmatch() method
if(re.fullmatch(regex, email)):
print("Valid Email")

else:
print("Invalid Email")
def isValid(s):

# 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(s)

# Driver Code
if __name__ == '__main__':
# Enter the email
email = input("enter email:")
s = input("enter Phone number:")
#calling run function
check(email)
if (isValid(s)):
print ("Valid Number")
else :
print ("Invalid Number")
Week- 7
1 Write a Python code to merge two given file contents into a third file.
data = data2 = ""
# Reading data from file1
with open('a.txt') as fp:
data = fp.read()
# Reading data from file2
with open('b.txt') as fp:
data2 = fp.read()
# Merging 2 files
# To add the data of file2
# from next line
data += "\n"
data += data2
with open ('file3.txt', 'w') as fp:
fp.write(data)

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.
with open('search.txt') as file:
contents = file.read()
search_word = input("enter a word you want to search in file: ")
if search_word in contents:
print ('word found')
else:
print ('word not found')
3 Write a Python code to Read text from a text file, find the word with most number of
occurrences
def read_data():
f = open("text.txt", 'r')
count = 0
s = f.read()
x = s.split()
for i in x:
if i == "apple":
count +=1
print(str(count)+" "+"times")
read_data()

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.
print("Enter the Name of File: ")
fileName = str(input())

fileHandle = open(fileName, "r")


countWord = 0
for content in fileHandle:
chk = 0
contentLen = len(content)
for i in range(contentLen):
if content[i]==' ':
if chk!=0:
countWord = countWord+1
chk = 0
else:
chk = chk+1
if chk!=0:
countWord = countWord+1

fileHandle = open(fileName, "r")


vtot = 0
vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
for char in fileHandle.read():
if char in vowels:
vtot = vtot+1
fileHandle.close()

fileHandle = open(fileName, "r")


btot = 0
for char in fileHandle.read():
if char==' ':
btot = btot+1
fileHandle.close()
fileHandle = open(fileName, "r")
ucount = 0
lcount=0
text = fileHandle.read()
for i in text:
if i.isupper():
ucount += 1
if i.islower():
lcount += 1
print("\nTotal Word(s): ")
print(countWord)

print("\nTotal Vowels are:")


print(vtot)

if btot>1:
print("\nThere are " + str(btot) + " Blank spaces available in the File")
elif btot==1:
print("\nThere is only 1 Blank space available in the File")
else:
print("\nThere is no any Blank space available in the File!")
print("No.of Uppercase letters in a file:",ucount)
print("No.of Lowercase letters in a file:",lcount)

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
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)," | ")

# Python3 program to illustrate


# 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)," | ")
# Python3 program to illustrate
# 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)," | ")
# Python3 program to illustrate
# 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 Write a program to implement Half Adder, Full Adder, and Parallel Adder

# Function to print sum and carry


def getResult(A, B):

# Calculating value of sum


Sum = A ^ B

# Calculating value of Carry


Carry = A & B

# printing the values


print("Sum ", Sum)
print("Carry", Carry)

# Driver code
A=0
B=1

# passing two inputs of halfadder as arguments to get result function


getResult(A, B)

5 Write a GUI program to create a window wizard having two text labels, two text fields
and two buttons as Submit and Reset.

from tkinter import *


from tkinter import messagebox
top = Tk()
top.geometry("600x550")
def fun():
messagebox.showinfo("Hello", "form submitted successfully")

def reset():
e1.delete(0,END)
e2.delete(0,END)

uname = Label(top, text = "Username")


uname.place(x=30,y=50)
e1 = Entry(top,width = 20)
e1.place(x=100,y=50)

password = Label(top, text = "Password",)


password.place(x=30,y=90)
e2 = Entry(top, width = 20,show="*")
e2.place(x=100,y=90)

Button(top, text = "Submit",command = fun,activebackground = "pink", activeforeground


= "blue").place(x = 30, y = 120)
Button(top, text="Reset", command=reset).place(x=90,y=120)

top.mainloop()

You might also like