Download as pdf or txt
Download as pdf or txt
You are on page 1of 45

List of Content

S.no Exercise Name Pg no DATE Remarks

1 Basics 2-3 21/10/22

2 Operations 4-5 28/10/22

3 Control Flow 6-9 05/11/22

4 Lists 10-12 11/11/22

5 Dictionary 13-14 18/11/22

6 Strings 15-16 25/11/22

7 Strings Continued 17-18 02/12/22

8 Files 19-22 09/12/22

9 Functions 23-27 16/12/22

10 Function Problem 28-31 06/01/23


Solving
11 Multi D- Lists 32-34 20/01/23

12 Modules 35-38 27/01/23

13 Digital Logical gates 39-45 03/02/23

1
Exercise 1

1. Running instructions in Interactive interpreter and a Python script:

 Shift + Enter  Run cell


 Ctrl +s  Save
 Ctrl +M+B  New cell
 Ctrl + M+D  Delete Cell
 Shift + /  Comment

2. Write a program to purposefully raise indentation Error and Correct it:

Error Code:

1. n=int(input("Enter Number:"))
2. if n%2==0:
3. print("Its even number")
4. else:
5. print("Its odd number")
6. Output:

File "", line 5 print("It is a negative number")


^ IndentationError: expected an indented block

Correct Code:
n=int(input("Enter Number:"))
if n%2==0:
print("Its even number")
else:
print("Its odd number")

2
Output:

Enter Number:3
Its odd number

Enter Number:105
Its odd number

Enter Number: 100


Its even number

3
Exercise 2

1. Write a program to compute GCD of Two numbers by taking input


from the user

Source Code:

def
gcd(a,b): if
a == 0:
return b
return gcd(b % a, a)
a=int(input("Enter first number:"))
b=int(input("Enter second
number:")) res1=gcd(a,b)
print(res1)

Output:

Enter first number:7


Enter second number:8
1

Enter first number:346


Enter second number:222
2

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

Source Code:

import sys
X=int(sys.arg[v])
Y=int(sys.argv[2])
Sum=x+y

Output:

C:\Python34\python sum.py 6 4
The addition is : 10
C:\Python34\python sum.py 64 47
The addition is : 111
C:\Python34\python sum.py 641 432
The addition is : 1073

5
Exercise 3

1. Write a Program for checking whether the given number is even


number or not.

Source Code:

n=int(input())
if(n%2==0):
print("It is even number")
else:
print("It is odd number")

Output:

44
It is even number
-544
It is even number

6
2. Write a program using for loop that loops over a sequence.

Source Code:

n=int(input("Enter the Number:"))


for i in range(n):
print(i,end=" ")

Output:

Enter the Number: 7


0123456
Enter the Number: 103
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
102
Enter the Number: 100
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99

7
3. Python Program to Print the Fibonacci sequence using while loop

Source Code:

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


count=0
n1=0
n2=1
while count < n:
print(n1)
temp = n1 + n2
n1 = n2
n2 = temp
count += 1

Output:

Enter number of terms:5


01123
Enter number of terms:25
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765
10946 17711 28657 46368

8
4. Python program to print all prime numbers in a given interval (use
break)
Source Code:

n,m=map(int,input("Enter the Range:").split())


for i in range(n,m): if i > 1: for j in range(2, i):
if (i % j) == 0:
break else:
print(i,end=" ")

Output:

Enter the Range:0 20


2 3 5 7 11 13 17 19
Enter the Range:542 775
547 557 563 569 571 577 587 593 599 601 607 613 617 619 631 641 643
647 653 659 661 673 677 683 691 701 709 719 727 733 739 743 751 757
761 769 773

9
Exercise 4

1. Find mean, median, mode for the given set of numbers in a list.

Source Code:

l= [2,44,8,9,4,33,4]
mean=sum(l)/len(l)
median=l[len(l)//2]
mode=max(set(l), key = l.count)
print(mean) print(median) print(mode)

Output:
55 342 43 55 8
Mean is 100.6
Median is 43
Mode is 55 55 342 43 55 8
Mean is 100.6
Median is 43
Mode is 55

10
2. Write a program to convert a list and tuple into arrays.

Source Code:

import numpy as np
li=[2,3,5,7,89,5]
tup=(4,88,1,6,90,2)
arr=np.array(li)
arr1=np.array(tup)
print(arr)
print(arr1)

Output:

[ 2 3 5 7 89 5] [ 4 88 1 6 90 2] [ 2 3 5 7 89 5] [ 4 88 1 6 90 2]

11
3. Write a program to find common values between two arrays.

Source Code:

lst1=[int(x) for x in
input().split()] lst2=[int(x) for x
in input().split()] common=[]
for i in lst1:
if i in lst2:
common.append(i) print(set(common))

Output:

123
234
{2, 3}

4 6 7 8 9 0 2 444 5 6 7 8 89
4 6 555 444 3 6667 8 99 89
{4, 6, 8, 89, 444}
1 2 3 4 5 6 7 8 9 0 11 12 13 14 15
99 98 97 96 95 94 93 92 91 90 89 88 87 86 85 84 83 82 81 set()
547 557 563 569 571 577 587 593 599 601 607 613 617 619 631 641 643
647 653 659 661 673 677 683 691 701 709 719 727 733 739 743 751 757
761 769 773
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765
10946 17711 28657 46368 set()
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 0 1 1 2
3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946
17711 28657 46368
{144, 89, 34, 55}
12
Exercise 5

1. Write a program to count the numbers of characters in the string


and store them in a dictionary data structure

Source Code:

dic={}
st=inpu
t()
st_li=lis
t(st) for
i in
st_li:
if i not in dic:
dic[i]=1
else:
dic[i]=dic
[i]+1
print(dic)

Output:

karthik
{'k': 2, 'a': 1, 'r': 1, 't': 1, 'h': 1, 'i': 1}

hi this is karthik
{'h': 3, 'i': 4, ' ': 3, 't': 2, 's': 2, 'k': 2, 'a': 1, 'r': 1}

13
2. Write a program combine lists into a dictionary.

Source Code:

li1=[(x) for x in input("Enter first list:").split()]


li2=[int(x) for x in input("Enter second
list:").split()] dic={}
for i in li1:
for j in li2:
dic[i]=j
li2.remove(j)
break
print(dic)

Output:

Enter first list:a b c


Enter second list:1 2 3
{'a': 1, 'b': 2, 'c': 3}
Enter first list:b c d e f g h i
Enter second list:2 3 4 5 6 7 8 9
{'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9}

14
Exercise 6

1. Write a program to check whether a string starts with specified


characters.

Source Code:

st=input("Enter the string:")


cha=input("Enter the
character:") if(st[0]==cha):
print("YES,!! string starts with a specified character")
else:
print("NO,!! It will not start")

Output:

Enter the string:Karthik


Enter the character:K
YES,!! string starts with a specified character

Enter the string:Hello This is Karthik


Enter the character:H
YES,!! string starts with a specified character

15
2. Write a program to check whether a string is palindrome or not

Source Code:

st=input("Enter the String:")


st=st.lower()
rev_st=st[::-1]
if(st==rev_st):
print("It is palindrome")
else:
print("It is not palindrome")

Output:

Enter the String:Rotator


It is palindrome

Enter the String:Mom


It is palindrome

Enter the String:Madam


It is palindrome

16
Exercise 7

1. Python program to split and join a string

Source Code:

string=input("Enter the
string: ") st_li=string.split("
") res_string=".".join(st_li)
print(res_string)

Output:

Enter the string: Hi this is Karthik


Hi.this.is.Karthik

Enter the string: My Name is Karthik


My.Name.is.Karthik

Enter the string: Python is an interpreted, high-level and general-


purpose programming language. Python's design philosophy
emphasizes

code readability with its notable use of significant whitespace.


Python.is.an.interpreted,.highlevel.and.generalpurpose.programming.la
nguage..Python's.design.philosophy.emphasizes.code.readability.with.it
s .notable.use.of.significant.whitespace.

17
2. Python Program to Sort Words in Alphabetic Order

Source Code:

string=input("Enter the string:")


str_li=string.split(" ")
sor_str=sorted(str_li)
print(sor_str)

Output:

Enter the string:hi a bde


['a', 'bde', 'hi']

Enter the string:Python was created in the late 1980s, and first released
in 1991, by Guido van Rossum as a successor to the ABC programming
language.
['1980s,', '1991,', 'ABC', 'Guido', 'Python', 'Rossum', 'a', 'and', 'as', 'by',
'created', 'first', 'in', 'in', 'language.', 'late', 'programming', 'released',
'successor', 'the', 'the', 'to', 'van', 'was']

18
Exercise 8

1. Write a program to print each line of a file in reverse order.

Source Code:

f=open("file.txt","r")
s=""
for i in f:
s=s+i[::-1]
print(“Reverse String is”,s)
f.close()

Output:

Reverse String is kihtraK si emaN


yM iH

Reverse
String is
]14[.licnuoc gnireetS 0202 eht rof noitanimon sih nwardhtiw neht ecnis
sah mussoR nav odiuG ]04[.tcejorp eht dael ot "licnuoC gnireetS"
rebmem-evif a ot mussoR naV dna gnilliW loraC ,wasraW yrraB
,nalhgoC kciN ,nonnaCtterB detcele srepoleved eroc nohtyP evitca
,9102 yraunaJ nI
]93[]83[]73[.licnuoc gnireets nosrep-evif a fo rebmem a sa pihsredael sih
serahs won eH ]63[.rekam-noisiced feihc s'tcejorp eht sa

19
2. Write a program to compute the number of characters, words and lines in a file.

Source Code:

f=open("file.txt","r")
s=""
for i in f:
s=s+i
print("Number of characters:",len(s)-s.count(' '))
print("Number of words:",s.count(' '))
print("Number of lines:",s.count('\n'))

Output:

Number of characters: 17
Number of words: 4
Number of lines: 0

Number of characters: 1599


Number of words: 282
Number of lines: 6

20
3. Write a program to count frequency of characters in a given file.

Source Code:

f=open("file.txt","r")
s=""
for i in f:
s=s+i
d={}
for i in s:
if i in d:
d[i]+=1
else:
d[i]=1
print(d)

Output:

{'h': 1, 'j': 2, 'g': 1, 'd': 2, 'y': 1, 't': 1}

{'P': 14, 'y': 33, 't': 122, 'h': 56, 'o': 119, 'n': 108, ' ': 282, 'w': 21, 'a': 104, 's':
81, 'c': 53, 'e': 163, 'i': 91, 'v': 13, 'd': 44, 'l': 58, '1': 8, '9': 6, '8': 6, '0': 17, '[':
19, '3': 16, ']': 19, 'b': 20, 'G': 2, 'u': 32, 'R': 5, 'm': 39, 'C': 7, 'r': 79, 'W': 5, 'k':
5, '&': 1, 'I': 5, 'f': 27, '(': 2, ')': 3, 'N': 3, 'A': 2, 'B': 4, 'p': 30, 'g': 22, ',': 13, 'S':
3, 'E': 1, 'T': 1, 'L': 2, '4': 12, 'x': 5, '.': 23, '7': 5, 'D': 3, '5': 4, 'V': 2, 'j': 6, '2': 18,
'J': 2, '"': 4, "'": 4, 'F': 1, '-': 11, '6': 5, 'H': 1, '\n': 6, 'O': 1, 'U': 1, 'M': 1}

{'P': 29, 'y': 70, 't': 264, 'h': 116, 'o': 236, 'n': 226, ' ': 524, 'i': 223, 's': 189, 'a':
246, 'm': 110, 'u': 77, 'l': 126, '-': 10, 'p': 87, 'r': 185, 'd': 109, 'g': 78, 'e': 281,
'.': 28, 'O': 1, 'b': 33, 'j': 4, 'c': 106, 'f': 54, ',': 27, '(': 6, '[': 18, '5': 12, '1': 2, ']':
18, ')': 6, '2': 3, 'M': 5, 'v': 17, 'x': 14, '3': 4, '4': 2, '\n': 23, '6': 9, 'I': 5, 'w': 23,
"'": 10, 'L': 2, ';': 1, '7': 1, 'T': 7, 'H': 1, 'k': 7, 'S': 3, '8': 1, 'z': 2, 'Z': 1, 'E': 2, '0':
2, ':': 1, '9': 2, 'B': 3, 'C': 7, 'R': 3, 'V': 1, 'A': 5, '"': 6, '—': 4, 'F': 2, 'W': 1, 'U': 1}

{'P': 32, 'y': 33, 't': 12, 'h': 56, 'o': 119, 'n': 108, ' ': 282, 'w': 21, 'a': 104, 's':
81, 'c': 53, 'e': 163, 'i': 91, 'v': 13, 'd': 44,, 'r': 185, 'd': 109, 'g': 78, 'e': 281, '.':
28, 'O': 1, 'b': 33, 'j': 4, 'c': 106, 'f': 54, ',': 27, '(': 6, '[': 18, '5': 12, '1': 2, ']': 18,
21
')': 6, '2': 3, 'M': 5, 'v': 17, 'x': 14, '3': 4, '4': 2, '\n': 23, '6': 9, 'I': 5, 'w': 23, "'":
10, 'L': 2, ';': 1, '7': 1, 'T': 7, 'H': 1, 'k': 7, 'S': 3, '8': 1, 'z': 2, 'Z': 1, 'E': 2, '0': 2,
':': 1, '9': 2, 'B': 3, 'C': 7, 'R': 3, 'V': 1, 'A': 5, '"': 6, '—': 4, 'F': 2, 'W': 1, 'U': 1}

22
Exercise 9

1. Simple Calculator program by making use of functions

Source Code:

def add(x,y):
print(x+y) def
sub(x,y):
print(x-y)
def mult(x,y):
print(x*y) def
div(x,y):
print(x/y)
print("1.Addition\n2.Subtraction\n3.Multiply\n4.Division")
n=int(input())
x=int(input("Enter First value:"))
y=int(input("Enter Second value:"))
if n==1:
add(x,y)
elif n==2:
sub(x,y)
elif n==3:
mult(x,y)
elif n==4:
div(x,y)
else:
print("No option")

23
Output:

1.Addition
2.Subtraction
3.Multiply
4.Division
1
Enter First value:3
Enter Second value:4
7

1.Addition
2.Subtraction
3.Multiply
4.Division
3
Enter First value:569
Enter Second value:222
126318

24
2. Find the factorial of a number using recursion

Source Code:

def factorial(n):
if(n==0):
return 1
elif(n==1):
return 1
else:
return n* factorial(n-1)
n=int (input ("Enter the Number:"))
result= factorial(n)
print(result)

Output:

Enter the Number:5


120
Enter the Number:157
117295687942641442819215807155131552511541831623044593627324
79955754482462269
663550547777601258732278967705798324665538723702018880460894
55812907729921755
894024363061543629619853937638474752237169791004877611734280
95446685622490578
985733324800000000000000000000000000000000000000

25
3. Write a function dups to find all duplicates in the list.

Source Code:

def duplicate(lis):
li_se=set(lis)
for i in li_se:
if(lis.count(i)>1):
res_li.append(i)
return res_li
li=[int(x) for x in input().split()]
res_li=[]
result=duplicate(li)

print(result)

Output: 1 5 5 3 1 1 8 9 5
[1, 5]
33 2 6 7 8 9 4 56 87 22 5 7 9 4
[4, 7, 9]
151375239
8 [2, 7, 8, 9]

26
4. Write a function unique to find all the unique elements of a list.

Source Code:

def unique(lis):
li_se=set(lis) for i
in li_se:
if(lis.count(i)==1
): res_li.append(i)
return res_li
li=[int(x) for x in input().split()]
res_li=[]
result=unique(li)

print(result)

Output:

151375239
8 [2, 7, 8, 9]
33 2 6 7 8 9 4 56 87 22 5 7 9 4
[33, 2, 5, 6, 8, 22, 87, 56]
5 88 2 3 77 1 11 2 3 77 5 99
[1, 99, 11, 88]
5 77 2 1 3 5 88
[1, 2, 3, 77, 88]

27
Exercise 10
1. Write a function cumulative_ product to compute cumulative
product of a list of numbers.

Source Code:

def cummulative_product(lis):
mul=1
for i in
lis:
mul=i
*mul
return
mul
li=[int(x) for x in
input().split()] result
=cummulative_product(li)
print(result)

Output:

10 4 5 8
1600
233 66 85 3 55 777
167580601650

28
2. Write a function reverse to print the given list in the reverse order.

Source Code:

def reverse(lis):
orgi_li=lis
for i in
range(len(orgi_li)):
rev_lis.append(lis.pop())
return rev_lis
li=[int(x) for x in input().split()]
rev_lis=[]
result =reverse(li)
print(result)

Output:

467821
[1, 2, 8, 7, 6, 4]

333 -1 -543 77 890 224


[224, 890, 77, -543, -1, 333]

29
3. Write function to compute GCD, LCM of two numbers

Source Code:

def gcd(a,b):
if a == 0:
return b
return gcd(b % a, a)
def lcm(res1):
return (a // res1)* b a=int(input("Enter
first number:")) b=int(input("Enter
second number:")) res1=gcd(a,b)
res2=lcm(res1)
print(res2,res1)

Output:

Enter first number:4


Enter second number:3
12 1

Enter first number:332


Enter second number:678
112548 2
Enter first number:43
Enter second number:990
42570 1

Enter first number:-521


Enter second number:62
32302 -1
30
Enter first number:-44
Enter second number:-890
-19580 -2

31
Exercise 11

1. Write a program that defines a matrix and prints

Source code :

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 j in range(C):
a.append(int(input()))
matrix.append(a)

for i in range(R):
for j in range(C):
print(matrix[i][j], end = " ")
print()
Output:

Enter the number of rows:2


Enter the number of columns:3
Enter the entries row wise:
1
2
3
4
5
6

123
456
32
2. Write a program to perform addition of two square matrices

Source code :

X = [[1,2,3],
[4 ,5,6],
[7 ,8,9]]

Y = [[9,8,7],
[6,5,4],
[3,2,1]]

result = [[X[i][j] + Y[i][j] for j in range


(len(X[0]))] for i in range(len(X))]

for r in result:
print(r)

Output :

[10, 10, 10]


[10, 10, 10]
[10, 10, 10]

33
3. Write a program to perform multiplication of two square matrices
Source code :

A = [[12, 7, 3],
[4, 5, 6],
[7, 8, 9]]

B = [[5, 8, 1, 2],
[6, 7, 3, 0],
[4, 5, 9, 1]]

result = [[sum(a * b for a, b in zip(A_row, B_col))


for B_col in zip(*B)]
for A_row in A]

for r in result:
print(r)

Output:

[114, 160, 60, 27]


[74, 97, 73, 14]
[119, 157, 112, 23]

34
Exercise 12

1. Install numpy package with pip and explore it :

NumPy (Numerical Python) is an open-source library for the Python


programming language. It is used for scientific computing and working with
arrays.

Prerequisites

Access to a terminal window/command line


A user account with sudo privileges
Python installed on your system

Step 1: Check Python Version

Before you can install NumPy, you need to know which Python version you
have. This programming language comes preinstalled on most operating
systems (except Windows; you will need to install Python on
Windows manually).

Most likely, you have Python 2 or Python 3 installed, or even both versions.
To check whether you have Python 2, run the command:

python –V

The output should give you a version number.

To see if you have Python 3 on your system, enter the following in the
terminal window:

python3 –V

In the example below, you can see both versions of Python are present.

35
Step 2: Install Pip

The easiest way to install NumPy is by using Pip. Pip a package manager for
installing and managing Python software packages.

Unlike Python, Pip does not come preinstalled on most operating systems.
Therefore, you need to set up the package manager that corresponds to the
version of Python you have. If you have both versions of Python, install both Pip
versions as well.

The commands below use the apt utility as we are installing on Ubuntu for the
purposes of this article.

Install Pip (for Python 2) by running:

sudo apt install python-pip

If you need Pip for Python 3, use the command:

sudo apt install python3-pip

Finally, verify you have successfully installed Pip by typing pip - V


and/or pip3 -V in the terminal window

36
Step 3: Install NumPy

With Pip set up, you can use its command line for installing NumPy.

Install NumPy with Python 2 by typing:

pip install numpy

Pip downloads the NumPy package and notifies you it has been successfully
installed.

To install NumPy with the package manager for Python 3, run:

pip3 install numpy

As this is a newer version of Python, the Numpy version also differs as you can see
in the image below.
Step 4: Verify NumPy Installation

Use the show command to verify whether NumPy is now part of you Python
packages:

pip show numpy

And for Pip3 type:

pip3 show numpy


37
The output should confirm you have NumPy, which version you are using, as
well as where the package is stored.

Step 5: Import the NumPy Package

After installing NumPy you can import the package and set an alias for it.

To do so, move to the python prompt by typing one of the following


commands:

Python

python3

Once you are in the python or python3 prompt you can import the new
package and add an alias for it (in the example below it is np):

import numpy as np

Upgrading NumPy

If you already have NumPy and want to upgrade to the latest version, for Pip2 use
the command:

pip install --upgrade numpy

If using Pip3, run the following command:

pip3 install --upgrade numpy

38
Exercise 13

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

Source Code :

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

39
Output:
True
+---------------+----------------
| AND Truth Table | Result |
A = False, B = False | A AND B = False
| A = False, B = True | A AND B = False
| A = True, B = False | A AND B = False
| A = True, B = True | A AND B = True
|

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

Output:
False
+---------------+----------------+
| OR Truth Table | Result |
A = False, B = False | A OR B = False |
A = False, B = True | A OR B = True |
A = True, B = False | A OR B = True |
A = True, B = True | A OR B = True
|

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

Output:
0
+---------------+----------------+
| XOR Truth Table | Result |
A = False, B = False | A XOR B = 0
| A = False, B = True | A XOR B = 1
| A = True, B = False | A XOR B = 1
| A = True, B = True | A XOR B = 0
|

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

Output:
1
+---------------+----------------+
| NOT Truth Table | Result |
A = False | A NOT = 1 |
A = True, | A NOT = 0 |

43
2. Write a program to implement Half adder, Full adder and Parallel adder

Sorce code:

# python program to implement Half Adder:

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)

Output:

Sum 1
Carry 0

44
Source Code :

# python program to implement full adder

# Function to print sum and C-

Out def getResult(A, B, C):

# Calculating value of sum


Sum = C ^ (A
^ B) C
# Calculating value of C-Out
C_Out = Bin&(not(A ^ B))| not(A)&B

# printing the values


print("Sum = ", Sum)
print("C-Out = ",
C_Out)

# Driver code
A=0
B=0
C=1
# passing three inputs of fulladder as arguments to get result function
getResult(A, B, C)

Output:

Sum = 1
C-Out = 0

45

You might also like