Civil Python Lab Manual
Civil Python Lab Manual
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. Write a program to calculate compound interest when principal, rate and numbers of
periods are given.
i) 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
2 2 22
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 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.
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.
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.
3. 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.
4. The wordlist I provided, words.txt, doesn’t contain single letter words. So you might want
to add “I”, “a”, and the empty string.
5. 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.
6. Add a comma between the characters. If the given word is 'Apple', it should become
'A,p,p,l,e'
7. Remove the given word in all the places in a string?
8. 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?
9. Writes a recursive function that generates all binary strings of n-bit length
Week - 5:
1. Write a python program
i) that defines a matrix and prints
ii) to perform addition of two square matrices
iii) 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. Do the following:
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.
e) 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.
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. 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 Programming: A Modern Approach, Vamsi Kurama, Pearson.
2. Python Programming - A Modular Approach with Graphics, Database, Mobile, and Web
Applications, Sheetal Taneja, Naveen Kumar, Pearson.
3. Programming with Python, A User’s Book, Michael Dawson, Cengage Learning, India
Edition.
4. Think Python, Allen Downey, Green Tea Press.
5. Core Python Programming, W. Chun, Pearson.
6. Introduction to Python, Kenneth A. Lambert, Cengage.
PYTHON LAB MANUAL
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.
Example:
Go to: https://docs.python.org/3/tutorial/
ii) Start the Python interpreter and type help() to start the online help utility.
bash
CopyEdit
python
cpp
CopyEdit
Python 3.13.5 (default, ...)
Type "help", "copyright", "credits" or "license" for more
information.
>>>
python
CopyEdit
help()
e. You will enter the Python help utility. It looks like this:
csharp
CopyEdit
Welcome to Python 3.13's help utility!
If this is your first time using Python, you should definitely check
out the tutorial on the Internet at
https://docs.python.org/3/tutorial/
help>
nginx
CopyEdit
python
c. Once you see the prompt >>>, you can start typing math expressions just like on a
calculator:
Example
python
CopyEdit
>>> 2 + 3
5
>>> 10 - 4
6
>>> 6 * 7
42
>>> 20 / 4
5.0
>>> 2 ** 3 # Exponentiation
8
python
CopyEdit
>>> (2 + 3) * 4
20
python
CopyEdit
exit()
3. Write a program to calculate compound interest when principal, rate and numbers
of periods are given.
# Python3 program to find compound
# interest for given values.
def compound_interest(principal, rate, time):
# Calculates compound interest
Amount = principal * (pow((1 + rate / 100), time))
CI = Amount - principal
print("Compound interest is", CI)
# Driver Code
compound_interest(10000, 10.25, 5)
i) Given coordinates (x1, y1), (x2, y2) find the distance between two points
# Python3 program to calculate
# distance between two points
import math
# Function to calculate distance
def distance(x1 , y1 , x2 , y2):
# Calculating distance
return math.sqrt(math.pow(x2 - x1, 2) +
math.pow(y2 - y1, 2) * 1.0)
# Drivers Code
print("%.6f"%distance(3, 4, 4, 3))
Read name, address, email and phone number of a person through keyboard and print the
details
# carrier: to know the name of
# service provider of that phone number
from phone numbers import carrier
service_provider = phone numbers.parse("Number with country code")
# Indian phone number example: +91**********
# Nepali phone number example: +977**********
# this will print the service provider name
print(carrier.name_for_number(service_provider, 'en'))
Print the below triangle using for loop.
# Python 3.x code to demonstrate star pattern
# Function to demonstrate printing pattern
def pypart(n):
# outer loop to handle number of rows
# n in this case
for i in range(0, n):
# inner loop to handle number of columns
# values changing acc. to outer loop
for j in range(0, i+1):
# printing stars
print("* ",end="")
# ending line after each row
print("\r")
# Driver Code
n=5
pypart(n)
4. Read name, address, email and phone number of a person through keyboard and
print the details.
# Read user input
name = input("Enter your name: ")
address = input("Enter your address: ")
email = input("Enter your email: ")
phone = input("Enter your phone number: ")
# Print the details
print("\n--- Person Details ---")
print("Name :", name)
print("Address :", address)
print("Email :", email)
print("Phone No. :", phone)
Output:
Enter your name: Priya Sharma
Enter your address: 123, MG Road, Mumbai
Enter your email: [email protected]
Enter your phone number: 9876543210
--- Person Details ---
Name : Priya Sharma
Address : 123, MG Road, Mumbai
Email : [email protected]
Phone No. : 9876543210
Week - 2:
1. Print the below triangle using for loop.
5
44
333
2 2 22
11111
Output:
5
4 4
3 3 3
2 2 2 2
1 1 1 1 1
newstring = ''
count1 = 0
count2 = 0
count3 = 0
for a in string:
# converting to uppercase.
if (a.isupper()) == True:
count1 += 1
newstring += (a.lower())
# converting to lowercase.
count2 += 1
newstring += (a.upper())
count3 += 1
newstring += a
print(newstring)
Output:
In original String :
Uppercase - 4
Lowercase - 41
Spaces - 7
After changing cases:
gEEKSFORgEEKS IS A COMPUTER sCIENCE PORTAL FOR gEEKS
Output:
Output
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
Week - 3:
1. i) Write a program to convert a list and tuple into arrays.
import numpy as np
# list
list1 = [1, 2, 3]
print(type(list1))
print(list1)
print()
# conversion
array1 = np.array(list1)
print(type(array1))
print(array1)
print()
tuple1 = ((1, 2, 3))
print(type(tuple1))
print(tuple1)
print()
# conversion
array2 = np.array(tuple1)
print(type(array2))
print(array2)
print()
# list, array and tuple
array3 = np.array([tuple1, list1, array2])
print(type(array3))
print(array3)
Output:
<class 'list'>
[1, 2, 3]
<class 'numpy.ndarray'>
[1 2 3]
<class 'tuple'>
(1, 2, 3)
<class 'numpy.ndarray'>
[1 2 3]
<class 'numpy.ndarray'>
[[1 2 3]
[1 2 3]
[1 2 3]]
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.
# function to check string is
# palindrome or not
def isPalindrome(str):
# Run loop from 0 to len/2
for i in range(0, int(len(str)/2)):
if str[i] != str[len(str)-i-1]:
return False
return True
# main function
s = "malayalam"
ans = isPalindrome(s)
if (ans):
print("Yes")
else:
print("No")
Output
Yes
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.
# Python3 code to demonstrate
# to check if list is sorted
# using all()
# initializing list
test_list = [9, 4, 5, 8, 10]
# printing original list
print ("Original list : " + str(test_list))
# using all() to
# check sorted list
flag = 0
if(all(test_list[i] <= test_list[i + 1] for i in range(len(test_list)-1))):
flag = 1
# printing result
if (flag) :
else :
print ("Yes, List is sorted.")
print ("No, List is not sorted.")
Output :
Original list : [9, 4, 5, 8, 10]
No, 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.
def has_dup(v):
c=0
for i in range(len(v)):
for j in range(len(v)-1):
print(f'index:{i} item:{v[i]} with index:{j+1} item:{v[j+1]}')
if v[i] == v[j+1]:
c = c+1
print(c)
if c > 1:
return True
if c <= 1:
return False
v = ['car', 'bar', 'are']
has_dup(v)
3. 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.
# Python program to read
# file word by word
# opening the text file
with open('GFG.txt','r') as file:
# reading each line
for line in file:
# reading each word
for word in line.split():
# displaying the words
print(word)
# Open the file in write mode
f2 = open("output2.txt", "w")
# Open the input file again and get
# the content as list to a variable data
with open("file.txt", "r") as myfile:
data = myfile.readlines()
# We will just reverse the
# array using following code
data_2 = data[::-1]
# Now we will write the fully reverse
# list in the output2 file using
# following command
f2.writelines(data_2)
f2.close()
# Initializing String
test_str = "GeeksForGeeks"
# Removing char at pos 3
# using replace
new_str = test_str.replace('e', '')
# Printing string after removal
# removes all occurrences of 'e'
print ("The string after removal of i'th character( doesn't work) : " + new_str)
# Removing 1st occurrence of s, i.e 5th pos.
# if we wish to remove it.
new_str = test_str.replace('s', '', 1)
# Printing string after removal
# removes first occurrences of s
print ("The string after removal of i'th character(works) : " + new_str)
4. The wordlist I provided, words.txt, doesn’t contain single letter words. So you might
want to add “I”, “a”, and the empty string
# Python3 implementation of the
# above approach
# Function to print the output
def printTheArray(arr, n):
for i in range(0, n):
print(arr[i], end = " ")
print()
of n-bit length
if i == n:
1. Writes a recursive function that generates all binary strings of n-bit length
# 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)
# This code is contributed
# by Rituraj Jain
Output:
0000
0001
0010
0011
0100
0101
0110
0111
1000
1001
1010
1011
1100
1101
1110
1111
5. 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.
def invert_dict(d):
# Invert the dictionary
inverted = {}
for key, value in d.items():
if value in inverted:
# If value already exists as a key, convert it to a list to handle duplicates
if isinstance(inverted[value], list):
inverted[value].append(key)
else:
inverted[value] = [inverted[value], key]
else:
inverted[value] = key
return inverted
# Read dictionary from user
n = int(input("Enter the number of items in the dictionary: "))
user_dict = {}
for _ in range(n):
k = input("Enter key: ")
v = input("Enter value: ")
user_dict[k] = v
# Print original dictionary
print("\nOriginal Dictionary:", user_dict)
# Invert and print
inverted = invert_dict(user_dict)
print("Inverted Dictionary:", inverted)
Output:
Enter the number of items in the dictionary: 3
Enter key: a
Enter value: 1
Enter key: b
Enter value: 2
Enter key: c
Enter value: 1
Original Dictionary: {'a': '1', 'b': '2', 'c': '1'}
Inverted Dictionary: {'1': ['a', 'c'], '2': 'b'}
6. Add a comma between the characters. If the given word is 'Apple', it should become
'A,p,p,l,e'
# Read word from user
word = input("Enter a word: ")
# Add comma between characters
result = ','.join(word)
# Print the result
print("Output:", result)
Output:
Enter a word: Apple
Output: A,p,p,l,e
8. 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 capitalize_words(sentence):
result = ""
i=0
length = len(sentence)
Output:
Enter a sentence: hELLo WOrLD fROM pYTHON
Formatted sentence: Hello World From Python
9. Writes a recursive function that generates all binary strings of n-bit length
# Example usage:
n=3
generate_binary_strings(n)
Explanation:
n is the number of bits you want in the binary strings.
prefix is used to build each string step by step.
Base case: when n == 0, the current prefix is a complete binary string, so we print it.
Recursive case: append "0" and "1" to the prefix, and reduce n by 1.
Output for n = 3:
Copy
Edit
000
001
010
011
100
101
110
111
Week - 5:
1. Write a python program
i) that defines a matrix and prints
# A basic code for matrix input from user
R = int(input("Enter the number of rows:"))
C = int(input("Enter the number of columns:"))
# Initialize matrix
matrix = []
print("Enter the entries rowwise:")
# For user input
for i in range(R): # A for loop for row entries
a =[]
for j in range(C): # A for loop for column entries
a.append(int(input()))
matrix.append(a)
# For printing the matrix
for i in range(R):
for j in range(C):
print(matrix[i][j], end = " ")
print()
Output:
Enter the number of rows:2
Enter the number of columns:3
Enter the entries rowwise:
1
2
3
4
5
6
123
456
ii) to perform addition of two square matrices
# Define two square matrices
A=[
[1, 2],
[3, 4]
]
B=[
[5, 6],
[7, 8]
]
# Initialize result matrix with zeros
n = len(A)
result = [[0 for _ in range(n)] for _ in range(n)]
# Perform matrix addition
for i in range(n):
for j in range(n):
result[i][j] = A[i][j] + B[i][j]
# Display the result
print("Sum of the matrices:")
for row in result:
print(row)
Output:
Sum of the matrices:
[6, 8]
[10, 12]
A module in Python is simply a .py file that contains functions, variables, or classes. You
can import and use them in other Python programs.
import math
def area_circle(radius):
return math.pi * radius ** 2
def perimeter_circle(radius):
return 2 * math.pi * radius
Python provides a structured way to handle errors (called exceptions) using the try, except,
else, and finally blocks.
try:
print("Result:", result)
except ZeroDivisionError:
except ValueError:
except Exception as e:
else:
finally:
How it works:
Output
d) Define a new class called Circle with appropriate attributes and instantiate a few
Circle objects.
import math
class Circle:
def __init__(self, radius):
self.radius = radius
def area(self):
return math.pi * self.radius ** 2
def circumference(self):
return 2 * math.pi * self.radius
# Instantiate a few Circle objects
circle1 = Circle(5)
circle2 = Circle(10)
circle3 = Circle(2.5)
# Print details
print("Circle 1 - Radius:", circle1.radius, "Area:", circle1.area(), "Circumference:",
circle1.circumference())
print("Circle 2 - Radius:", circle2.radius, "Area:", circle2.area(), "Circumference:",
circle2.circumference())
print("Circle 3 - Radius:", circle3.radius, "Area:", circle3.area(), "Circumference:",
circle3.circumference())
Explanation:
3. Write a python code to read a phone number and email-id from the user and validate
it for correctness.
# Python program to extract emails From
# the String By Regular Expression.
# Importing module required for regular
# expressions
import re
# Example string
s = """Hello from [email protected]
to [email protected] about the meeting @2PM"""
# \S matches any non-whitespace character
# @ for as in the Email
# + for Repeats a character one or more times
lst = re.findall('\S+@\S+', s)
# Printing of List
print(lst)
Week- 7:
1. Write a Python code to merge two given file contents into a third file.
# Python program to
# demonstrate merging
# of two files
data = data2 = ""
# Reading data from file1
with open('file1.txt') as fp:
data = fp.read()
# Reading data from file2
with open('file2.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. \
#include <bits/stdc++.h>
ALPHABET_SIZE = 26;
class trieNode:
self.isEnd = 0
def getNode():
temp = trieNode()
return temp;
# Function to insert new words in trie
def insert(root, key):
trail = None
trail = root;
# Iterate for the length of a word
for i in range(len(key)):
temp = None
# If the next key does not contains the character
if (trail.t[ord(key[i]) - ord('a')] == None):
temp = getNode();
trail.t[ord(key[i]) - ord('a')] = temp;
trail = trail.t[ord(key[i]) - ord('a')];
# isEnd is increment so not only
# the word but its count is also stored
(trail.isEnd) += 1
# Search function to find a word of a sentence
def search_mod(root, word):
trail = root;
# Iterate for the complete length of the word
for i in range(len(word)):
# If the character is not present then word
# is also not present
if (trail.t[ord(word[i]) - ord('a')] == None):
return False;
# If present move to next character in Trie
trail = trail.t[ord(word[i]) - ord('a')];
# If word found then decrement count of the word
if ((trail.isEnd) > 0 and trail != None):
# if the word is found decrement isEnd showing one
# occurrence of this word is already taken so
(trail.isEnd) -= 1
return True;
else:
return False;
# Function to check if string can be
# formed from the sentence
def checkPossibility(sentence, m, root):
flag = 1;
# Iterate for all words in the string
for i in range(m):
if (search_mod(root, sentence[i]) == False):
# if a word is not found in a string then the
# sentence cannot be made from this dictionary of words
print('NO', end='')
return;
# If possible
print('YES')
# Function to insert all the words of dict in the Trie
def insertToTrie(dictionary, n, root):
for i in range(n):
insert(root, dictionary[i]);
# Driver Code
if name ==' main ':
root = getNode();
# Dictionary of words
dictionary = [ "find", "a", "geeks",
"all", "for", "on",
"geeks", "answers", "inter" ]
N = len(dictionary)
# Calling Function to insert words of dictionary to tree
insertToTrie(dictionary, N, root);
Write a Python code to Read text from a text file, find the word
with most number of occurrences
# String to be checked
sentence = [ "find", "all", "answers", "on",
"geeks", "for", "geeks" ]
M = len(sentence)
# Function call to check possibility
checkPossibility(sentence, M, root);
# This code is contributed by pratham76
Output:
YES
3. Write a Python code to Read text from a text file, find the word with most number
of occurrences
def find_most_frequent_word(filename):
try:
with open(filename, 'r') as file:
text = file.read()
# Remove punctuation and convert to lowercase
for char in "-.,\n":
text = text.replace(char, " ")
text = text.lower()
words = text.split()
word_count = {}
# Count occurrences of each word
for word in words:
word_count[word] = word_count.get(word, 0) + 1
# Find the word with the most occurrences
most_frequent = max(word_count, key=word_count.get)
count = word_count[most_frequent]
print(f"The most frequent word is: '{most_frequent}' (occurs {count} times)")
except FileNotFoundError:
print("File not found. Please check the file name or path.")
# Example usage
filename = "sample.txt" # Replace with your file path
find_most_frequent_word(filename)
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.
# Importing required libraries
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
# -------- NumPy Functionalities --------
print("----- NumPy Functionalities -----")
array = np.array([1, 2, 3, 4, 5])
print("Array:", array)
mean = np.mean(array)
print("Mean of array:", mean)
matrix = np.array([[1, 2], [3, 4]])
print("Matrix:\n", matrix)
print("Transpose:\n", matrix.T)
# -------- Matplotlib (Plotpy) Functionalities --------
print("\n----- Matplotlib (Plotpy) Functionalities -----")
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.plot(x, y, label="sin(x)")
plt.title("Sine Wave")
plt.xlabel("x-axis")
plt.ylabel("y-axis")
plt.legend()
plt.grid(True)
plt.show()
# -------- SciPy Functionalities --------
print("\n----- SciPy Functionalities -----")
data = [1, 2, 2, 3, 4, 4, 4, 5]
mode = stats.mode(data)
print("Mode of data:", mode.mode[0], "with frequency:", mode.count[0])
Explanation of Functionalities:
NumPy: Handles arrays, linear algebra, and statistical operations.
Matplotlib (Plotpy): Used for plotting graphs like line, bar, scatter, etc.
SciPy: Builds on NumPy; includes stats, optimization, integration, etc.
Output Summary:
Printed array, mean, matrix transpose (NumPy)
Displayed a sine graph (Matplotlib)
Calculated mode using statistics (SciPy)
2. Install NumPy package with pip and explore it.
# using the iris dataset
df = px.data.iris()
# plotting the bubble chart
fig = px.scatter(df, x="species", y="petal_width",
size="petal_length", color="species")
# showing the plot
fig.show()
Output:
Installation
Plotly does not come built-in with Python. To install it type the below command in the
terminal.
pip install plotly
This may take some time as it will install the dependencies as well.
Package Structure of Plotly
There are three main modules in Plotly. They are:
• plotly.plotly
• plotly.graph.objects
• plotly.tools
plotly.plotly acts as the interface between the local machine and Plotly. It contains functions
that require a response from Plotly’s server.
plotly.graph_objects module contains the objects (Figure, layout, data, and the definition
of
the plots like scatter plot, line chart) that are responsible for creating the plots. The Figure
can
be represented either as dict or instances of plotly.graph_objects.Figure and these are
serialized as JSON before it gets passed to plotly.js. Consider the below example for better
understanding.
Note: plotly.express module can create the entire Figure at once. It uses the graph_objects
internally and returns the graph_objects.Figure instance.
Example:
How to Install Numpy on Windows?
• Last Updated : 09 Sep, 2021
1 Read
2 Discuss
Python NumPy is a general-purpose array processing package that provides tools for
handling n-dimensional arrays. It provides various computing tools such as comprehensive
mathematical functions, linear algebra routines. NumPy provides both the flexibility of
Python and the speed of well-optimized compiled C code. Its easy-to-use syntax makes it
highly accessible and productive for programmers from any background.
Pre-requisites:
The only thing that you need for installing Numpy on Windows are:
• Python
• PIP or Conda (depending upon user preference)
Make sure you follow the best practices for installation using conda as:
• Use an environment for installation rather than in the base environment using the below
command:
conda create -n my-env
conda activate my-env
Note: If your preferred method of installation is conda-forge, use the below command:
conda config --env --add channels conda-forge
For PIP Users:
Users who prefer to use pip can use the below command to install NumPy:
pip install numpy
You will get a similar message once the installation is complete:
Now that we have installed Numpy successfully in our system, let’s take a look at few simple
examples.
3. Write a program to implement Digital Logic Gates – AND, OR, NOT, EX-OR
# Python3 program to illustrate
# working of Not gate
def XNOR(a,b):
if(a == b):
return 1
else:
return 0
# Driver code
if __name__=='__main ':
print(XNOR(1,1))
print("+ + +")
print(" | XNOR Truth Table | Result |")
print(" A = False, B = False | A XNOR B =",XNOR(False,False)," | ")
print(" A = False, B = True | A XNOR B =",XNOR(False,True)," | ")
print(" A = True, B = False | A XNOR B =",XNOR(True,False)," | ")
print(" A = True, B = True | A XNOR B =",XNOR(True,True)," | ")
Output:
1
+ + +
| XNOR Truth Table | Result |
A = False, B = False | A XNOR B = 1 |
A = False, B = True | A XNOR B = 0 |
A = True, B = False | A XNOR B = 0 |
A = True, B = True | A XNOR B = 1 |
# Python3 program to illustrate
# working of NOR gate
# Driver code
if __name__=='__main ':
print(NOR(0, 0))
print("+ + +")
print(" | NOR Truth Table | Result |")
print(" A = False, B = False | A NOR B =",NOR(False,False)," | ")
print(" A = False, B = True | A NOR B =",NOR(False,True)," | ")
print(" A = True, B = False | A NOR B =",NOR(True,False)," | ")
print(" A = True, B = True | A NOR B =",NOR(True,True)," | ")
Output:
1
+ + +
| NOR Truth Table | Result |
A = False, B = False | A NOR B = 1 |
A = False, B = True | A NOR B = 0 |
A = True, B = False | A NOR B = 0 |
A = True, B = True | A NOR B = 0 |
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)
Output:
Sum 1
Carry 0
5. Write a GUI program to create a window wizard having two text labels, two text
fields and two buttons as Submit and Reset.
# Import Module
from tkinter import *
# create root window
root = Tk()
# root window title and dimension
root.title("Welcome to GeekForGeeks")
# Set geometry (widthxheight)
root.geometry('350x200')
# all widgets will be here
# Execute Tkinter
root.mainloop()