0% found this document useful (0 votes)
7 views41 pages

Python Programming Lab Programmes

The document outlines a series of Python experiments, including using the Python help utility, performing basic arithmetic operations, calculating compound interest, and reading user input. It also includes tasks such as printing patterns, checking character types, identifying prime numbers, and defining functions for palindrome checking and duplicate detection. Additionally, it covers converting data structures and finding common values between arrays.

Uploaded by

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

Python Programming Lab Programmes

The document outlines a series of Python experiments, including using the Python help utility, performing basic arithmetic operations, calculating compound interest, and reading user input. It also includes tasks such as printing patterns, checking character types, identifying prime numbers, and defining functions for palindrome checking and duplicate detection. Additionally, it covers converting data structures and finding common values between arrays.

Uploaded by

asnbharadwaj2007
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

List of Experiments:

1.​ Use a web browser to go to the Python website


[Link] 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.

help()
Welcome to Python 3.7's help utility!
If this is your first time using Python, you should definitely check out
the tutorial on the Internet at [Link]
Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules. To quit this help utility
and
return to the interpreter, just type "quit".
To get a list of available modules, keywords, symbols, or topics, type
"modules", "keywords", "symbols", or "topics". Each module also comes
with a one-line summary of what it does; to list the modules whose
name
or summary contain a given string such as "spam", type "modules
spam".
help> "modules"
Please wait a moment while I gather a list of all available modules...

Warning (from warnings module):


File
"C:\Users\shilpathoutireddy\AppData\Local\Programs\Python\Python
37\lib\site-packages\IPython\kernel\__init__.py", line 13
"You should import from ipykernel or jupyter_client instead.",
ShimWarning)
ShimWarning: The `[Link]` package has been deprecated since
IPython [Link] should import from ipykernel or jupyter_client instead.
Warning (from warnings module):
File
"C:\Users\shilpathoutireddy\AppData\Local\Programs\Python\Python
37\lib\[Link]", line 92
__import__([Link])
UserWarning: viewer requires Qt
2simplecompound collections modulefinder string
IPython colorama msilib stringprep
PIL colorizer msvcrt struct
__future__ colorsys multicall subprocess
__main__ commctrl multiprocessing sunau
_abc compileall nest_asyncio symbol
_ast concurrent netbios sympyprinting
_asyncio config netrc symtable
_bisect config_key networkx sys
_blake2 configdialog nntplib sysconfig
_bootlocale configparser nt tabnanny
_bz2 contextlib ntpath tabulate
_codecs contextvars ntsecuritycon tarfile
_codecs_cn copy nturl2path telnetlib
_codecs_hk copyreg numbers tempfile
_codecs_iso2022 crypt numpy tensorboard
_codecs_jp csv oauthlib tensorboard_data_server
_codecs_kr ctypes odbc tensorboard_plugin_wit
_codecs_tw curses opcode tensorflow
_collections cv2 operator tensorflow_estimator
_collections_abc cycler opt_einsum termcolor
_compat_pickle cythonmagic optparse test
_compression dataclasses os tests
_contextvars datetime outwin textview
_csv dateutil packaging textwrap
_ctypes dbi pandas this
_ctypes_test dbm parenmatch threading
_datetime dde parser threadpoolctl
_decimal debugger parso tifffile
_dummy_thread debugger_r pasta time
_elementtree debugobj pathbrowser timeit
_functools debugobj_r pathlib timer
_hashlib debugpy pdb tkinter
_heapq decimal percolator token
_imp decorator perfmon tokenize
_io delegator pickle tooltip
_json difflib pickleshare tornado
_locale dis pickletools trace
_lsprof distutils pip traceback
_lzma doctest pipes tracemalloc
_markupbase dummy_threading pkg_resources traitlets
_md5 dynoption pkgutil tree
_msi easy_install platform tty
_multibytecodec editor plistlib turtle
_multiprocessing email poplib turtledemo
_opcode encodings posixpath types
_operator ensurepip pprint typing
_osx_support entrypoints profile typing_extensions
_overlapped enum prompt_toolkit undo
_pickle errno pstats unicodedata
_py_abc faulthandler psutil unittest
_pydecimal filecmp pty urllib
_pyio fileinput py_compile urllib3
_queue filelist pyasn1 uu
_random flatbuffers pyasn1_modules uuid
_sha1 fnmatch pyclbr venv
_sha256 fontTools pydoc warnings
_sha3 format pydoc_data wave
_sha512 formatter pyexpat wcwidth
_signal fractions pygments weakref
_sitebuiltins ftplib pylab webbrowser
_socket functools pyparse werkzeug
_sqlite3 gast pyparsing wheel
_sre gc pyshell win2kras
_ssl genericpath pythoncom win32api
_stat getopt pytictoc win32clipboard
_string getpass pytz win32com
_strptime gettext pywin win32con
_struct glob pywin32_bootstrap win32console
_symtable google_auth_oauthlib pywin32_testutil win32cred
_testbuffer grep pywintypes win32crypt
_testcapi grpc pywt win32cryptcon
_testconsole gzip query win32event
_testimportmultiple h5py queue win32evtlog
_testmultiphase hashlib quopri win32evtlogutil
_thread heapq random win32file
_threading_local help rasutil win32gui
_tkinter help_about re win32gui_struct
_tracemalloc history redirector win32help
_warnings hmac regcheck win32inet
_weakref html regutil win32inetcon
_weakrefset http replace win32job
_win32sysloader hyperparser reprlib win32lz
_winapi idle requests win32net
_winxptheme idle_test requests_oauthlib win32netcon
abc idlelib rlcompleter win32pdh
absl idna rmagic win32pdhquery
adodbapi imageio rpc win32pdhutil
afxres imaplib rsa win32pipe
aifc imghdr run win32print
antigravity imp runpy win32process
argparse importlib runscript win32profile
array importlib_metadata sched win32ras
ast inspect scipy win32rcparser
astunparse io scrolledlist win32security
asynchat iomenu search win32service
asyncio ipaddress searchbase win32serviceutil
asyncore ipykernel searchengine win32timezone
atexit ipykernel_launcher secrets win32trace
audioop isapi select win32traceutil
autocomplete itertools selectors win32transaction
autocomplete_w jedi servicemanager win32ts
autoexpand joblib setuptools win32ui
autoreload json shelve win32uiole
backcall jupyter shlex win32verstamp
base64 jupyter_client shutil win32wnet
bdb jupyter_core sidebar window
binascii keras signal winerror
binhex keras_preprocessing site winioctlcon
bisect keyword six winnt
browser kiwisolver skimage winperf
builtins lib2to3 sklearn winreg
bz2 linecache smtpd winsound
cProfile locale smtplib winxpgui
cached_property logging sndhdr winxptheme
cachetools lzma socket wrapt
calendar macosx socketserver wsgiref
calltip macpath sqlite3 xdrlib
calltip_w mailbox squeezer xml
certifi mailcap sre_compile xmlrpc
cgi mainmenu sre_constants xxsubtype
cgitb markdown sre_parse zipapp
charset_normalizer markupsafe ssl zipfile
chunk marshal sspi zipimport
clang math sspicon zipp
cmath matplotlib stackviewer zlib
cmd matplotlib_inline start_pythonwin zmq
code mimetypes stat zoomheight
codecontext mmap statistics zzdummy
codecs mmapfile statusbar
codeop mmsystem storemagic
Enter any module name to get more help. Or, type "modules spam" to
search
for modules whose name or summary contain the string "spam".
help> "keywords"
Here is a list of the Python keywords. Enter any keyword to get more
help.
False class from or
None continue global pass
True def if raise
and del import return
as elif in try
assert else is while
async except lambda with
await finally nonlocal yield
break for not
help> "symbols"
Here is a list of the punctuation symbols which Python assigns special
meaning
to. Enter any symbol to get more help.
!= + <= __
" += <> `
""" , == b"
% - > b'
%= -= >= f"
& . >> f'
&= ... >>= j
' / @ r"
''' // J r'
( //= [ u"
) /= \ u'
* : ] |
** < ^ |=
**= << ^= ~
*= <<= _
help> "topics"
Here is a list of available topics. Enter any topic name to get more help.
ASSERTION DELETION LOOPING SHIFTING
ASSIGNMENT DICTIONARIES MAPPINGMETHODS
SLICINGS
ATTRIBUTEMETHODS DICTIONARYLITERALS MAPPINGS
SPECIALATTRIBUTES
ATTRIBUTES DYNAMICFEATURES METHODS
SPECIALIDENTIFIERS
AUGMENTEDASSIGNMENT ELLIPSIS MODULES
SPECIALMETHODS
BASICMETHODS EXCEPTIONS NAMESPACES
STRINGMETHODS
BINARY EXECUTION NONE STRINGS
BITWISE EXPRESSIONS NUMBERMETHODS
SUBSCRIPTS
BOOLEAN FLOAT NUMBERS TRACEBACKS
CALLABLEMETHODS FORMATTING OBJECTS
TRUTHVALUE
CALLS FRAMEOBJECTS OPERATORS
TUPLELITERALS
CLASSES FRAMES PACKAGES TUPLES
CODEOBJECTS FUNCTIONS POWER
TYPEOBJECTS
COMPARISON IDENTIFIERS PRECEDENCE TYPES
COMPLEX IMPORTING PRIVATENAMES UNARY
CONDITIONAL INTEGER RETURNING UNICODE
CONTEXTMANAGERS LISTLITERALS SCOPING
CONVERSIONS LISTS SEQUENCEMETHODS
DEBUGGING LITERALS SEQUENCES
-----------------------------------------------------------------------------------------
---------
2.​ Start a Python interpreter and use it as a Calculator.
a = 10
b=3
print("Addition:", a + b)
print("Subtraction:", a - b)
print("Multiplication:", a * b)
print("Division:", a / b)
print("Power:", a ** b)
-------------------------------------------------------------------------------------------------
---------
3.​ Write a program to calculate compound interest when principal,
rate and number of periods are given.
p = float(input("Enter principal amount: "))
r = float(input("Enter rate of interest: "))
t = float(input("Enter time (in years): "))
# Simple Interest
si = (p * r * t) / 100
# Compound Interest
amount = p * (1 + r / 100) ** t
ci = amount - p
print("\n--- Interest Calculation ---")
print("Simple Interest =", si)
print("Total Amount (SI) =", p + si)
print("Compound Interest =", ci)
print("Total Amount (CI) =", amount)
------------------------------------------------------------------------------------------------
----------
4.​ Read the name, address, email and phone number of a person
through the keyboard and print the details.
name = input("Enter name: ")
address = input("Enter address: ")
email = input("Enter email: ")
phone = input("Enter phone number: ")
print("\n--- Details ---")
print("Name:", name)
print("Address:", address)
print("Email:", email)
print("Phone:", phone)
------------------------------------------------------------------------------------------------
-------
●​ Print the below triangle using
for loop.
5
44
333
2222
11111
n =int(input("enter a number"))
for i in range(n,0,-1):
for j in range(n+1-i):
print(i,end=" ")
print()
---------------------------------------------------------------------------------------
---------
6.​ 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 value")
if [Link]():
print("given input id digit:")
elif [Link]():
print("given input is upper")
elif [Link]():
print("given input is lower")
else:
print("given input is special char")
--------------------------------------------------------------------------------
7.​ Python program to print all prime numbers in a given interval (use
break)
n=int(input("enter a number"))
if n<=1:
print("not prime")
else:
for i in range(2,n):
if n%i==0:
print("not prime")
break;
else:
print("prime")

----------------
start=int(input("enter start:"))
end=int(input("enter end:"))
for n in range(start, end+1):
if n>1:
for i in range(2,n):
if(n%i==0):
break
else:
print(n)
---------------------------------------------------------------------------------------
8.​ Write a program to convert a list and tuple into arrays.

9.​ Write a program to find common values between two arrays.


10.​ 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 palindrome(s):
s = [Link]() # convert to lowercase
length = len(s)
for i in range(length // 2):
if s[i] != s[length - i - 1]:
return False
return True

# Example usage
word = input("Enter a string: ")
if palindrome(word):
print("True - It is a palindrome")
else:
print("False - It is not a palindrome")
11.​ 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(lst):
for i in range(len(lst) - 1):
if lst[i] > lst[i + 1]:
return False
return True

# Manual values
numbers = [1, 2, 3, 4, 5]
if is_sorted(numbers):
print("True - The list is sorted in ascending order")
else:
print("False - The list is not sorted")
12.​ Write a function called has_dupIicates that takes a list and
returns True if there is any element that appears more than once.
It should not modify the original [Link] has_duplicates(lst):
for i in range(len(lst)):
for j in range(i + 1, len(lst)):
if lst[i] == lst[j]:
return True
return False

# Manual values
numbers = [1, 2, 3, 4, 2]
print(has_duplicates(numbers))
13.​ Write a function called remove_dupIicates that takes a list and
returns a new list with only the unique elements from the original.
Hint: they don't have to be in the same order.
def remove_duplicates(lst):
new_list = []
for item in lst:
if item not in new_list:
new_list.append(item)
return new_list

# Manual values
numbers = [1, 2, 3, 2, 4, 3, 5]
print(remove_duplicates(numbers))
14.​ The wordlist I provided, [Link], doesn't contain single letter
words. So you might want to add “I”, “a”, and the empty string.

['apple', 'banana', 'shilpa', 'I', 'a', '']

15.​ 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.
16.​ Add a comma between the characters. If the given word is
'Apple', it should become 'A,p,p,I,e'

17.​ Remove the given word in all the places in a string?

18.​ 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?
19.​ Writes a recursive function that generates all binary strings of
n-bit length

20.​ Write a python program that defines a matrix and prints


21.​ Write a python program to perform multiplication of two square
matrices
22.​ 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.
 A module is a Python file containing functions and variables
 It is created using .py file and imported using import
 It improves code reuse and structure

Feature Module Package


A collection of modules
Definition A single Python file (.py)
(folder)
Contains functions, Contains multiple modules
Structure
variables, classes + __init__.py
Large (directory with many
Size Small (single file)
files)
Used for specific Used for organizing large
Usage
functionality projects
numpy, django,
Example [Link], [Link]
matplotlib

# [Link]

import math

# Area of Circle
def area_circle(r):
return [Link] * r * r
# Area of Rectangle
def area_rectangle(l, b):
return l * b

# Area of Triangle
def area_triangle(b, h):
return 0.5 * b * h

# Perimeter of Circle
def perimeter_circle(r):
return 2 * [Link] * r

# Perimeter of Rectangle
def perimeter_rectangle(l, b):
return 2 * (l + b)
----------------------------------------

import shapes

print("Area of Circle:", shapes.area_circle(5))


print("Area of Rectangle:", shapes.area_rectangle(4, 3))
print("Area of Triangle:", shapes.area_triangle(6, 2))

print("Perimeter of Circle:", shapes.perimeter_circle(5))


print("Perimeter of Rectangle:", shapes.perimeter_rectangle(4, 3))

23.​ Use the structure of exception handling all general-purpose


exceptions.

What is an Exception?
An exception is an error that occurs during the execution of a program, which disrupts the
normal flow of the program.
a = 10​
b = 0​
print(a / b) # Causes error

👉 This gives ZeroDivisionError, which is an exception.


Common Types of Exceptions

●​ ZeroDivisionError → division by zero


●​ ValueError → wrong input type
●​ TypeError → wrong data type operation
●​ FileNotFoundError → file not found

Feature Error Exception


A serious problem in Runtime problem during
Definition
program execution
Occurrence Mostly at compile time Occurs during runtime
Handling Cannot be handled easily Can be handled using
try-except
Can be controlled and
Effect Stops program execution
program continues
Example Syntax error ZeroDivisionError

try:
a = int(input("Enter number: "))
b = int(input("Enter number: "))
print(a / b)
except ZeroDivisionError:
print("Cannot divide by zero")
except ValueError:
print("Invalid input")
else:
print("No error occurred")
finally:
print("Program ended")

>>>
========= RESTART: D:/shilpa college/Python
lab/programms/[Link] =========
Enter number: 5
Enter number: 0
Cannot divide by zero
Program ended
>>>
========= RESTART: D:/shilpa college/Python
lab/programms/[Link] =========
Enter number: r
Invalid input
Program ended
>>>

24.​ Write a function called draw_rectangIe that takes a Canvas and a


Rectangle as arguments and draws a representation of the
Rectangle on the Canvas.
import tkinter as tk
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
class Rectangle:
def __init__(self, width, height, corner):
[Link] = width
[Link] = height
[Link] = corner
def draw_rectangle(canvas, rect):
x1 = [Link].x
y1 = [Link].y
x2 = x1 + [Link]
y2 = y1 + [Link]
canvas.create_rectangle(x1, y1, x2, y2)
root = [Link]()
canvas = [Link](root, width=300, height=300)
[Link]()
p = Point(50, 50)
r = Rectangle(100, 60, p)
draw_rectangle(canvas, r)
[Link]()

25.​ Add an attribute named color to your Rectangle objects and


modify draw_rectangIe so that it uses the color attribute as the fill
color.
import tkinter as tk
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
class Rectangle:
def __init__(self, width, height, corner, color):
[Link] = width
[Link] = height
[Link] = corner
[Link] = color
def draw_rectangle(canvas, rect):
x1 = [Link].x
y1 = [Link].y
x2 = x1 + [Link]
y2 = y1 + [Link]
canvas.create_rectangle(x1, y1, x2, y2, fill=[Link])
root = [Link]()
canvas = [Link](root, width=300, height=300)
[Link]()
p = Point(50, 50)
r = Rectangle(100, 60, p, "blue")
draw_rectangle(canvas, r)
[Link]()

26.​ 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.
import tkinter as tk
class Point:
def __init__(self, x, y):
self.x = x
self.y = y

def draw_point(canvas, point):


r=3
canvas.create_oval(point.x - r, point.y - r,
point.x + r, point.y + r,
fill="red")
root = [Link]()
canvas = [Link](root, width=300, height=300)
[Link]()
p = Point(150, 150)
draw_point(canvas, p)
[Link]()

27.​ Define a new class called Circle with appropriate attributes and
instantiate a few Circle objects. Write a function called draw_circIe
that draws circles on the canvas.
import tkinter as tk
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
class Circle:
def __init__(self, center, radius):
[Link] = center
[Link] = radius
def draw_circle(canvas, circle):
x = [Link].x
y = [Link].y
r = [Link]
canvas.create_oval(x - r, y - r, x + r, y + r)
root = [Link]()
canvas = [Link](root, width=300, height=300)
[Link]()
p = Point(150, 150)
c = Circle(p, 50)
draw_circle(canvas, c)
[Link]()
28.​ Write a python code to read a phone number and email-id from
the user and validate it for correctness.
phone = input("Enter phone: ")​
email = input("Enter email: ")​

if len(phone) == 10 and [Link]():​
print("Valid Phone Number")​
else:​
print("Invalid Phone Number")​

if "@" in email and "." in email:​
print("Valid Email ID")​
else:​
print("Invalid Email ID")

===== RESTART: D:/shilpa college/Python


lab/programms/mail [Link] =====
Enter phone: 345267886
Enter email: shilpa@wds.
Invalid Phone Number
Valid Email ID
29.​ Write a Python code to merge two given file contents into a third
file.

What is a File?
A file is used to store data permanently on disk. In Python, we can create,
read, write, and update files.

File Operations in Python


Python mainly supports 3 operations:
1.​ Open a file
2.​ Read/Write file
3.​ Close the file
Opening a File
Syntax:
file_object = open("filename", "mode")
Modes of Opening File
Mode Description
"r" Read (default)
"w" Write (creates new / overwrites)
"a" Append (adds data at end)
"x" Create file (error if exists)
"b" Binary mode
"t" Text mode (default)

Closing a File
[Link]()

Writing to a File
f = open("[Link]", "w")​
[Link]("Hello World")​
[Link]()
Creates file and writes content.

Reading from a File


1. Read full content
f = open("[Link]", "r")​
print([Link]())​
[Link]()
2. Read line by line
f = open("[Link]", "r")​
print([Link]())​
[Link]()
3. Read all lines as list
f = open("[Link]", "r")​
print([Link]())​
[Link]()

Append to File
f = open("[Link]", "a")​
[Link]("\nNew line added")​
[Link]()

Using with Statement (Best Practice)


Automatically closes file ✅
with open("[Link]", "r") as f:​
data = [Link]()​
print(data)
Example Program (Write + Read)
# Writing to file​
with open("[Link]", "w") as f:​
[Link]("Python File Handling")​

# Reading from file​
with open("[Link]", "r") as f:​
print([Link]())

File Pointer Methods


Method Description
tell() Returns current position
seek() Moves pointer to position
Example:
f = open("[Link]", "r")​
print([Link]())​
[Link](0)​
print([Link]())​
[Link]()

# Open first file in read mode​


f1 = open("[Link]", "r")​

# Open second file in read mode​
f2 = open("[Link]", "r")​

# Open third file in write mode​
f3 = open("[Link]", "w")​

# Read contents and write into third file​
[Link]([Link]())​
[Link]([Link]())​

# Close all files​
[Link]()​
[Link]()​
[Link]()​

print("Files merged successfully!")

30.​ 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.
# Open the file​
f = open("[Link]", "r")​

# Read content​
content = [Link]()​

# Take input from user​
word = input("Enter word to search: ")​

# Check if word is present​
if word in content:​
print(f"'{word}' found in the file.")​
else:​
print(f"'{word}' NOT found in the file.")​

# Close the file​
[Link]()
31.​ Write a Python code to Read text from a text file, find the word
with most number of occurrences
f = open("[Link]", "r")​

text = [Link]().lower()​
words = [Link]()​

max_word = max(words, key=[Link])​

print("Most frequent word:", max_word)​
print("Occurrences:", [Link](max_word))​

[Link]().
Counter → directly counts frequency
OR max() with count() → finds most repeated word

32.​ Write a function that reads a file ii/ed and displays the number
of words, number of vowels, blank spaces, lower case letters and
uppercase letters.
def file_analysis(filename):​
f = open(filename, "r")​
text = [Link]()​

words = len([Link]())​
vowels = 0​
spaces = 0​
lower = 0​
upper = 0​

for ch in text:​
if ch in "aeiouAEIOU":​
vowels += 1​
if ch == " ":​
spaces += 1​
if [Link]():​
lower += 1​
if [Link]():​
upper += 1​

print("Number of words:", words)​
print("Number of vowels:", vowels)​
print("Number of blank spaces:", spaces)​
print("Number of lowercase letters:", lower)​
print("Number of uppercase letters:", upper)​

[Link]()​

# Function call​
file_analysis("[Link]")

33.​ Import numpy, Plotpy and Scipy and explore their


functionalities.

NumPy
●​ Used for numerical operations
Supports arrays and mathematical functions​
●​
👉 Example: mean(), sum(), square()

Matplotlib (Pyplot)
●​ Used for data visualization
Helps to draw graphs like line, bar, etc.​
●​
👉 Example: plot(), show()

SciPy
●​ Used for scientific and statistical computations
Built on NumPy​
●​
👉 Example: [Link]()

Output
●​ Displays array operations (mean, sum, etc.)
●​ Shows a line graph
●​ Prints statistical result (mode)

# Import libraries​
import numpy as np​
import [Link] as plt​
import scipy​

# ---------------- NUMPY ----------------​
# Create array​
arr = [Link]([1, 2, 3, 4, 5])​
print("NumPy Array:", arr)​

# Perform operations​
print("Mean:", [Link](arr))​
print("Sum:", [Link](arr))​
print("Square:", [Link](arr))​

# ---------------- MATPLOTLIB (Pyplot) ----------------​
# Plot graph​
x = [1, 2, 3, 4, 5]​
y = [10, 20, 25, 30, 40]​

[Link](x, y)​
[Link]("Simple Line Graph")​
[Link]("X values")​
[Link]("Y values")​
[Link]()​

# ---------------- SCIPY ----------------​
from scipy import stats​

# Statistical function​
data = [1, 2, 2, 3, 4]​
mode = [Link](data)​

print("Mode using SciPy:", mode)

34.​ Install NumPypackage with pip and explore it.


Installing NumPy using pip
Step 1: Open Command Prompt
●​ Press Windows + R
●​ Type cmd and press Enter

Step 2: Install NumPy


Type the following command:
pip install numpy
This will download and install the NumPy package
Step 3: Verify Installation
pip show numpy
Displays installed details (version, location, etc.)
import numpy as np​

# Create array​
arr = [Link]([1, 2, 3, 4, 5])​
print("Array:", arr)​

# Shape of array​
print("Shape:", [Link])​

# Data type​
print("Data type:", [Link])​

# Basic operations​
print("Sum:", [Link](arr))​
print("Mean:", [Link](arr))​
print("Max:", [Link](arr))​
print("Min:", [Link](arr))​

# Reshape array​
arr2 = [Link]([[1, 2, 3], [4, 5, 6]])​
print("2D Array:\n", arr2)​

# Indexing​
print("First element:", arr[0])​
print("Last element:", arr[-1])
35.​ Write a program to implement Digital Logic Gates — AND, OR,
NOT, EX-OR
# Input values (0 or 1)​
a = int(input("Enter first input (0 or 1): "))​
b = int(input("Enter second input (0 or 1): "))​

# AND Gate​
and_gate = a & b​

# OR Gate​
or_gate = a | b​

# NOT Gate (for both inputs)​
not_a = 1 - a​
not_b = 1 - b​

# EX-OR (XOR) Gate​
xor_gate = a ^ b​

# Display results​
print("AND Gate:", and_gate)​
print("OR Gate:", or_gate)​
print("NOT Gate (A):", not_a)​
print("NOT Gate (B):", not_b)​
print("EX-OR Gate:", xor_gate)
AND (&) → Output is 1 only if both inputs are 1
OR (|) → Output is 1 if at least one input is 1
NOT (1 - a) → Reverses the input (0→1, 1→0)
XOR (^) → Output is 1 if inputs are different

36.​ Write a GUI program to create a window wizard having two text
labels, two text fields and two buttons as Submit and Reset.
import tkinter as tk
# Create main window
root = [Link]()
[Link]("Window Wizard")
[Link]("300x200")
# Labels
label1 = [Link](root, text="Name")
[Link](row=0, column=0, padx=10, pady=10)
label2 = [Link](root, text="Email")
[Link](row=1, column=0, padx=10, pady=10)
# Text Fields
entry1 = [Link](root)
[Link](row=0, column=1)
entry2 = [Link](root)
[Link](row=1, column=1)
# Submit function
def submit():
name = [Link]()
email = [Link]()
print("Name:", name)
print("Email:", email)
# Reset function
def reset():
[Link](0, [Link])
[Link](0, [Link])
# Buttons
btn_submit = [Link](root, text="Submit", command=submit)
btn_submit.grid(row=2, column=0, pady=10)
btn_reset = [Link](root, text="Reset", command=reset)
btn_reset.grid(row=2, column=1, pady=10)
# Run the window
[Link]()

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.​ Introduction to Python Programming, Gowrishakar S, Veena A, CRC
Press
4.​ Programming with Python, A User's Book, Michael Dawson, Cengage
Learning, India Edition
5.​ Python for Data Science, Dr. Mohd Abdul Hameed, Wiley publications
6.​ Core Python Programming, Dr. R. Nageswara Rao, Dreamtech press
7.​ Introduction to Python, Gowrishankar S, Veena A., CRC Press
What is Object-Oriented Programming (OOP)?
Object-Oriented Programming (OOP) is a programming approach where
programs are designed using classes and objects.
👉 It models real-world things like students, cars, shapes, etc.
Key Idea
●​ Class → Blueprint (design)
●​ Object → Real instance (actual thing)

What is a Class?
A class is a blueprint or template used to create objects.
●​ It defines properties (attributes) and functions (methods)
●​ It does not occupy memory until objects are created
👉 Example:​
A Car class defines color, model, speed, etc.
Syntax of Class
class ClassName:
def __init__(self, variables):
[Link] = variables
What is an Object?
An object is an instance of a class.
●​ It represents a real-world entity
●​ It occupies memory
●​ It can access class attributes and methods
👉 Example:​
If Car is a class → car1 is an object
class Student:
def __init__(self, name, age):
[Link] = name
[Link] = age
def display(self):
print("Name:", [Link])
print("Age:", [Link])
# Creating objects
s1 = Student("Ram", 20)
s2 = Student("Sita", 21)
# Calling method
[Link]()
[Link]()
--------------------------------
Name: Ram
Age: 20
Name: Sita
Age: 21
----------------------------
__init__() Method
●​ Special method called constructor
●​ Automatically runs when object is created
self
●​ Refers to the current object
●​ Used to access variables and methods

Real-Time Examples
●​ Class → Student​
Object → Ram, Sita
●​ Class → Car​
Object → Honda, Toyota
●​ Class → Rectangle​
Object → specific rectangle with size
What is Canvas?
The Canvas class in Tkinter is used to draw graphics and shapes such as:
●​ Lines
●​ Rectangles
●​ Circles (ovals)
●​ Text
●​ Images
👉 It acts as a drawing area (board) inside a window.
Syntax
canvas = Canvas(parent, width=..., height=..., bg="color")
Parameters
●​ parent → window (usually root)
●​ width → width of canvas
●​ height → height of canvas
●​ bg → background color
import tkinter as tk
root = [Link]()
canvas = [Link](root, width=300, height=300, bg="white")
[Link]()
# Draw shapes
canvas.create_line(50, 50, 200, 50)
canvas.create_rectangle(50, 80, 200, 150)
canvas.create_oval(50, 160, 200, 250)
canvas.create_text(120, 270, text="Hello")
[Link]()
------------------------------------------
create_line(x1, y1, x2, y2)
●​ Draws a line between two points
create_rectangle(x1, y1, x2, y2)
●​ Draws a rectangle
●​ (x1, y1) → top-left
●​ (x2, y2) → bottom-right
create_oval(x1, y1, x2, y2)
●​ Draws circle/ellipse inside bounding box
create_text(x, y, text="...")
●​ Displays text on canvas
create_text(x, y, text="...")
●​ Displays text on canvas
create_polygon()
●​ Draws shapes with multiple sides

What is [Link]() in Tkinter?


[Link]() is used to place (display) the canvas widget inside the
window.
👉 Without calling pack(), the canvas will not be visible on the screen.
Why do we use pack()?
Tkinter needs a layout manager to arrange widgets.
pack() is one of the layout managers used to:
●​ Position widgets in the window
●​ Automatically adjust their size and placement

You might also like