FUNDAMENTALS OF
PYTHON
PROGRAMMING
FOR BEGINNERS
UNIT-5
PYTHON PACKAGES
Mr. Rahul Kumar Gupta Dr. Arun Kumar. G
Assistant Professor Professor & HOD
Department of Electronics & Communication Engg.
JSS Academy of Technical Education , Noida, UP.
Python Packages
UNIT
5
Python packages
UNIT-5: Python Packages: Simple programs using the built-in functions of packages
matplotlib, numpy, pandas etc. GUI Programming: Tkinter introduction, Tkinter and
Python Programming, Tk Widgets, Tkinter examples. Python programming with IDE.
5.1 INTRODUCTIONS TO PYTHON PACKAGES:
A Python package is a directory (folder) that contains related Python files called
modules along with a special file called along with a special __init__.py file.
• A module is a single .py file containing Python code (functions, classes, variables).
• A package is a directory containing multiple modules and a special file called
__init__.py (can be empty) that tells Python it’s a package.
BENEFITS OF PYTHON PACKAGES
1. Organized Code Structure
• Groups related modules together, making projects easier to navigate and
maintain.
2. Reusability
• Write code once and reuse it across multiple projects without duplication.
3. Modularity
• Breaks large programs into smaller, manageable components.
4. Ease of Sharing
• Distribute packages via PyPI or other repositories so others can install and use
them easily.
5. Namespace Management
• Prevents naming conflicts by isolating modules in separate namespaces.
6. Extensibility
• Easily integrate third-party packages to expand Python’s capabilities.
7. Collaboration Friendly
• Allows multiple developers to work on different modules within the same package
without interference.
Fundamentals of Python Programming for Beginners 236
Python Packages
5.2 CLASSIFICATION OF PYTHON PACKAGES
Python packages are grouped into categories based on what they are used for. This helps
developers choose the right tool for their task.
Figure 5.1: Major Python Package Classifications
Table: Classification of Python Packages
Package
Category Explanation Purpose
Examples
Built-in with Python, no Handle basic tasks like math
math, datetime,
Standard installation needed; handles operations, date/time, file
os, sys, random,
Library math, date/time, file handling, handling, and system
json
system tasks, and data formats. interaction.
numpy, scipy, Perform numerical
Scientific & Used for calculations, data
matplotlib, computations, analyze datasets,
Numerical analysis, and visualization.
pandas, sympy and visualize results.
scikit-learn, Create machine learning
Machine Used to build models for
tensorflow, models, deep learning
Learning & predictions, deep learning, and
keras, xgboost, networks, and natural language
AI natural language processing.
nltk processing systems.
flask, django, Develop web applications,
Web requests, Used to create websites, APIs, connect to web services, and
Development beautifulsoup4, and scrape web data. scrape data from websites.
fastapi
Used to create desktop Build apps with buttons, menus,
GUI tkinter, PyQt,
applications with graphical forms, and interactive elements.
Development Kivy, wxPython
interfaces.
Data sqlite3, Handle databases, read/write
Used to store, read, and manage
Handling & sqlalchemy, Excel and CSV files.
data in files or databases.
Database openpyxl, csv
unittest, pytest, Ensure code works correctly
Testing & Used to test code and
selenium, and automate repetitive
Automation automate repetitive tasks.
robotframework processes.
Fundamentals of Python Programming for Beginners 237
Python Packages
5.3 BUILT-IN FUNCTIONS OF PYTHON PACKAGES
In Python, each package (or module) comes with its own built-in functions, these are
functions provided by that package to perform specific tasks without requiring you to
write the logic from scratch.
The below table summarizing some commonly used packages and their important built-
in functions with simple explanations:
Table: Commonly used packages and their important built-in functions
Package Common Built-in Functions Simple Explanation
The basic built-in functions in Python provide quick
Basic ways to display output, check types, get object details,
(print(), len(), type(), id(), dir(),
Built-in and access documentation.
help())
Functions They simplify coding by offering ready-to-use tools
for debugging, exploring, and managing data.
sqrt(x), pow(x, y), factorial(x), Perform mathematical calculations like square root,
math
ceil(x), floor(x) powers, factorial, rounding up/down.
random(), randint(a, b), Generate random numbers, choose random items,
random
choice(seq), shuffle(seq) shuffle data.
[Link](), [Link](), Work with dates and times, get current date/time,
datetime
timedelta(days=n) calculate time differences.
getcwd(), listdir(path), Interact with the operating system folders, files,
os
mkdir(name), remove(file) paths.
Manage Python runtime, exit program, check memory
sys exit(), getsizeof(obj), version
size, get Python version.
mean(data), median(data),
statistics Perform statistical calculations easily.
mode(data), stdev(data)
dump(obj, file), load(file), Work with JSON data—read, write, and convert
json
dumps(obj), loads(str) between JSON and Python objects.
search(pattern, string),
Use regular expressions to search, match, and extract
re match(pattern, string),
patterns in text.
findall(pattern, string)
Counter(seq), defaultdict(type), Special data structures for counting, default values,
collections
namedtuple(name, fields) and structured tuples.
5.4 MATPLOTLIB – BUILT-IN FUNCTIONS
• Matplotlib’s pyplot module is used to create graphs and charts in Python.
• Always import the module first: import [Link] as plt
• Use [Link]() at the end to render the plot.
Table: Summary of built-in Functions of [Link]
Function Syntax Example Explanation
plot() [Link](x, y) Draws a line graph between x and y values.
bar() [Link](x, height) Creates a vertical bar chart.
barh() [Link](y, width) Creates a horizontal bar chart.
scatter() [Link](x, y) Plots individual data points as a scatter plot.
hist() [Link](data, bins=...) Displays a histogram showing frequency distribution.
pie() [Link](sizes, labels=...) Creates a pie chart to show proportions.
xlabel() [Link]("X-axis Label") Adds a label to the X-axis.
ylabel() [Link]("Y-axis Label") Adds a label to the Y-axis.
title() [Link]("Plot Title") Adds a title to the plot.
legend() [Link]() Displays a legend for labeled plot elements.
grid() [Link](True) Adds grid lines to the plot for better readability.
xlim() [Link](min, max) Sets limits for the X-axis.
ylim() [Link](min, max) Sets limits for the Y-axis.
Fundamentals of Python Programming for Beginners 238
Python Packages
BUILT-IN FUNCTIONS OF [Link]: plot()
SYNTAX
[Link](x, y)
Explanation:
• plot() draws a line graph connecting the points defined by the x and y arrays.
• It’s ideal for visualizing trends, relationships, or changes over a continuous range.
• Optional arguments include:
✓ label: for legend
✓ color: line color
✓ marker: symbol at each data point (e.g., 'o', 'x', etc.)
✓ linestyle: line style ('-', '--', ':', etc.)
Example Program: Simple Line Plot
import [Link] as plt
import numpy as np
x = [Link](0, 10, 100)
y = [Link](x)
[Link](x, y, label='sin(x)', color='blue')
[Link]('Simple Line Plot')
[Link]('X-axis (units)')
[Link]('Y-axis (units)')
[Link]()
[Link](True)
[Link]()
OUTPUT:
Explanation:
• [Link](0, 10, 100) generates 100 evenly spaced values from 0 to 10.
• [Link](x) computes the sine of each value.
• The plot shows a smooth sine wave.
• Labels, title, legend, and grid enhance readability.
Fundamentals of Python Programming for Beginners 239
Python Packages
Example Program: Simple Line Plot
import [Link] as plt
import numpy as np
x = [Link](0, 10, 100)
y1 = [Link](x)
y2 = [Link](x)
[Link](x, y1, label='sin(x)', color='green', marker='o')
[Link](x, y2, label='cos(x)', color='red', marker='x')
[Link]('Multiple Line Plot with Styles')
[Link]('X-axis (units)')
[Link]('Y-axis (units)')
[Link]()
[Link](True)
[Link]()
OUTPUT:
Explanation:
• Two functions (sin(x) and cos(x)) are plotted on the same graph.
• Different colors and markers distinguish the lines.
• Useful for comparing multiple datasets visually.
Example Program: Simple Line Plot
import numpy as np
import [Link] as plt
from [Link] import sawtooth
# Generate time values
t = [Link](0, 2 * [Link], 500)
# Generate triangular waveform
triangular_wave = sawtooth(t, width=0.5)
# Plotting
[Link](t, triangular_wave, label='Triangular Wave', color='blue')
[Link]('Triangular Waveform')
[Link]('Time (radians)')
[Link]('Amplitude')
[Link]()
[Link](True)
[Link]()
Fundamentals of Python Programming for Beginners 240
Python Packages
OUTPUT:
Explanation:
• sawtooth(t, width=0.5) generates a symmetric triangular wave.
• width=0.5 makes the waveform peak in the middle of each cycle.
• The plot shows a repeating linear rise and fall pattern.
• Useful in signal processing and waveform analysis.
BUILT-IN FUNCTIONS OF [Link]: bar()
SYNTAX
[Link](x, height)
Explanation:
• bar() creates a vertical bar chart.
• x: categories or positions on the X-axis.
• height: values or heights of the bars.
• Optional arguments:
✓ color: bar color
✓ width: width of each bar
✓ label: for legend
✓ align: alignment of bars ('center' or 'edge')
Example Program: Basic Bar Chart
import [Link] as plt
subjects = ['Math', 'Physics', 'Chemistry']
marks = [85, 90, 78]
[Link](subjects, marks, color='darkblue')
[Link]('Subjects')
[Link]('Marks')
[Link]('Student Performance')
[Link](True, axis='y')
[Link]()
Fundamentals of Python Programming for Beginners 241
Python Packages
OUTPUT:
Explanation:
• Each subject is represented by a vertical bar.
• grid(True, axis='y') adds horizontal grid lines for better readability.
Example Program: Bar Chart with Custom Width and Labels
import [Link] as plt
companies = ['Company A', 'Company B', 'Company C']
revenue = [120, 150, 90]
[Link](companies, revenue, color='green', width=0.5, label='Annual Revenue')
[Link]('Companies')
[Link]('Revenue (in crores)')
[Link]('Company Revenue Comparisxon')
[Link]()
[Link](True)
[Link]()
OUTPUT:
Explanation:
• Bars are narrower (width=0.5) and colored green.
• legend() displays the label for the bars.
• Useful for comparing financial or categorical data.
Fundamentals of Python Programming for Beginners 242
Python Packages
BUILT-IN FUNCTIONS OF [Link]: barh()
• barh() in Matplotlib is used to create horizontal bar charts.
SYNTAX
[Link](y, width)
Explanation:
• y: Specifies the y-coordinates of the bars (i.e., the positions on the vertical axis
where bars are placed). This can be a list of values or categories.
• width: Specifies the lengths (widths) of the horizontal bars, representing the data
values.
Example Program: Simple Line Plot
import [Link] as plt
categories = ['A', 'B', 'C']
values = [10, 20, 15]
[Link](categories, values, color='darkblue')
[Link]('Values')
[Link]('Categories') # Added for clarity, since categories are on the y-axis
[Link]('Horizontal Bar Chart')
[Link]()
OUTPUT:
Explanation:
Code Purpose Output/Effect
Brings in the plotting library
import [Link] as plt Makes plotting functions available
with alias
categories = ['A', 'B', 'C'] Creates list of category labels Stores ['A', 'B', 'C'] in memory
values = [10, 20, 15] Creates list of numerical data Stores [10, 20, 15] in memory
[Link](categories, values,
Generates horizontal bars Creates 3 dark blue horizontal bars
color='darkblue')
[Link]('Values') Adds label to x-axis Displays "Values" below chart
[Link]('Categories') Adds label to y-axis Displays "Categories" on left side
[Link]('Horizontal Bar Chart') Adds title to chart Displays title at top of chart
[Link]() Renders and shows the chart Opens chart window/displays chart
Data Mapping:
Category Value Bar Length
A 10 Short
Fundamentals of Python Programming for Beginners 243
Python Packages
B 20 Long
C 15 Medium
BUILT-IN FUNCTIONS OF [Link]: scatter()
The [Link] function in Matplotlib is used to create a scatter plot of
individual data points on a 2D plane. Below is the detailed syntax, including all key
parameters, as provided by the Matplotlib library.
SYNTAX
[Link](
x,
y,
s=None,
c=None,
marker=None,
cmap=None,
norm=None,
vmin=None,
vmax=None,
alpha=None,
linewidths=None,
edgecolors=None,
plotnonfinite=False,
*,
data=None,
**kwargs
)
Explanation:
Parameter Description
x Sequence of x-values
y Sequence of y-values
s Size of points (scalar or array)
c Color(s) of points (single color, array, or colormap)
marker Marker style ('o', 'x', '^', etc.)
cmap Colormap for mapping numeric c values
norm Normalization for colormap scaling
vmin, vmax Color scale limits for colormap
alpha Transparency level (0.0–1.0)
linewidths Marker edge width
edgecolors Color of marker edges
plotnonfinite Whether to plot points with NaN/Inf values
data Optional data source (dict, DataFrame, etc.)
kwargs Additional customization options
Fundamentals of Python Programming for Beginners 244
Python Packages
Example Program: Simple Line Plot
import [Link] as plt import [Link] as plt
x = [1, 2, 3, 4, 5] # Sample data
y = [2, 4, 6, 8, 10] x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
[Link](x, y)
[Link]("Basic Scatter Plot") # Create scatter plot
[Link]("X values") [Link](x, y, c='blue', s=100, marker='o',
[Link]("Y values") alpha=0.8)
[Link]() [Link]("Basic Scatter Plot")
[Link]("X Axis")
[Link]("Y Axis")
[Link](True)
[Link]()
OUTPUT: OUTPUT:
Explanation: Explanation:
• Data: The x and y lists define the • Data: The x and y lists define the
coordinates of the points. coordinates of the points, forming pairs
• Parameters: that indicate a linear relationship (y = 2x).
c='blue': Sets all markers to blue. • Parameters:
s=100: Sets a uniform marker size. c: Not specified, defaults to blue markers
marker='o': Uses circular markers. based on Matplotlib’s default style.
alpha=0.8: Makes markers slightly s: Not specified, uses default marker size
transparent. (typically 20 points^2).
• Customization: The [Link](), marker: Not specified, defaults to circular
[Link](), [Link](), and markers ('o').
[Link](True) enhance the plot's clarity. alpha: Not specified, defaults to fully
opaque (1.0).
• Customization: The [Link](), [Link](),
and [Link]() add a title and axis labels to
improve readability. No grid or legend is
included, as [Link]() or label parameters
weren’t used.
Fundamentals of Python Programming for Beginners 245
Python Packages
Example Program: Scatter Plot with Varying Marker Sizes and Colors
import [Link] as plt import [Link] as plt
x = [5, 7, 8, 7, 6, 9, 5] # Sample data
y = [99, 86, 87, 88, 100, 86, 103] x = [1, 2, 3, 4, 5]
y = [3, 5, 2, 8, 7]
[Link](x, y, c="red", s=150, alpha=0.6, sizes = [50, 100, 150, 200, 250]
edgecolors="black") colors = [1, 2, 3, 4, 5]
[Link]("Customized Scatter Plot")
[Link]("X values") # Create scatter plot
[Link]("Y values") [Link](x, y, s=sizes, c=colors, cmap='viridis',
[Link]() alpha=0.6, edgecolors='black')
[Link]("Scatter Plot with Varying Sizes and
Colors")
[Link]("X Axis")
[Link]("Y Axis")
[Link](label='Color Scale')
[Link](True)
[Link]()
OUTPUT: OUTPUT:
Explanation: Explanation:
• Red dots, semi-transparent Data:
(alpha=0.6), with black edges. The x and y lists define the coordinates of the
• Dot size is larger (s=150). points, representing a non-linear dataset. The
• Here, visual customization is added sizes list specifies varying marker sizes, and the
using c for color, s for size, alpha for colors list provides values mapped to colors via a
transparency, and edgecolors for colormap.
border color. Parameters:
• s=sizes: Sets different marker sizes (50 to
250 points^2) for each point to highlight
variation.
• c=colors: Maps each point’s color to a value
in the colors list using the 'viridis' colormap.
• cmap='viridis': Uses the 'viridis' colormap
to translate numeric color values into a
gradient.
Fundamentals of Python Programming for Beginners 246
Python Packages
• alpha=0.6: Makes markers semi-transparent
to improve visibility if points overlap.
• edgecolors='black': Adds black edges to
markers for better contrast.
Customization: The [Link](), [Link](), and
[Link]() add a title and axis labels for clarity.
The [Link](True) adds a grid, and
[Link](label='Color Scale') includes a
colorbar to show the color mapping.
BUILT-IN FUNCTIONS OF [Link]: hist()
The hist() function in [Link] is used to compute and plot histograms, which
are graphical representations of the distribution of numerical data. It divides the
data into equally spaced intervals called bins and counts how many data points fall into
each bin, displaying the frequency as bars.
SYNTAX
[Link](
x,
bins=None,
range=None,
density=False,
weights=None,
cumulative=False,
bottom=None,
histtype='bar',
align='mid',
orientation='vertical',
rwidth=None,
log=False,
color=None,
label=None,
stacked=False,
data=None,
**kwargs
)
Explanation:
• x: Input data (array-like or sequence of arrays) to plot.
• bins: Number of bins (int), bin edges (sequence), or binning method (str, e.g., 'auto').
Default: 10 bins.
• range: Tuple (lower, upper) to set the data range for binning. Default: Uses data
min/max.
• density: If True, normalizes histogram to a probability density (area sums to 1).
Default: False.
• weights: Array of weights for each data point, same shape as x. Default: None (equal
weights).
Fundamentals of Python Programming for Beginners 247
Python Packages
• cumulative: If True, plots cumulative histogram; if -1, reverse cumulative. Default:
False.
• bottom: Starting height for bars (scalar or array). Useful for stacking. Default: 0.
• histtype: Histogram style ('bar', 'barstacked', 'step', 'stepfilled'). Default: 'bar'.
• align: Bar alignment ('left', 'mid', 'right'). Default: 'mid'.
• orientation: Bar direction ('vertical' or 'horizontal'). Default: 'vertical'.
• rwidth: Relative bar width (float < 1 for gaps). Default: Bars touch.
• log: If True, uses logarithmic scale for y-axis. Default: False.
• color: Bar color(s) (single color or list). Default: Uses default color cycle.
• label: Legend label for the histogram. Default: None.
• stacked: If True, stacks multiple datasets (with histtype='barstacked'). Default:
False.
• data: Optional dictionary/DataFrame to reference x by key/column. Default: None.
• kwargs: Additional styling options (e.g., alpha, edgecolor, linewidth).
Return Value
• A tuple:
✓ n: Bin counts.
✓ bins: Bin edges.
✓ patches: List of Patch objects (the drawn bars).
Example Program: Basic Histogram Plot
import [Link] as plt
# Sample data
data = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5]
# Plot histogram
[Link](data, bins=5, color='orange', edgecolor='black')
# Add labels and title
[Link]("Values")
[Link]("Frequency")
[Link]("Basic Histogram")
[Link]()
Fundamentals of Python Programming for Beginners 248
Python Packages
OUTPUT:
Example Program: Histogram Plot
import [Link] as plt import [Link] as plt
import numpy as np import numpy as np
# Generate 1000 random numbers from data = [Link](1000)
a standard normal distribution [Link](x=data, bins=20, color='blue', alpha=0.7,
(mean=0, std=1) label='Data')
[Link]('Value')
data = [Link](1000) [Link]('Frequency')
[Link]()
# Plot histogram [Link]()
[Link](
x=data, # Input data
bins=20, # Divide data into 20
intervals (bins)
color='blue', # Bar color
alpha=0.7, #Transparency
(0=transparent, 1=opaque)
label='Data' # Label for legend
)
# Labels & legend
[Link]('Value') # X-axis label
[Link]('Frequency') # Y-axis label
[Link]() # Show legend ("Data")
[Link]() # Display the plot
Fundamentals of Python Programming for Beginners 249
Python Packages
OUTPUT: OUTPUT:
Example Program: Basic Histogram with Random Data
import [Link] as plt
import numpy as np
# Generate sample data (1000 random numbers from a normal distribution)
data = [Link](1000)
# Create histogram
[Link](
x=data, # Input data
bins=15, # Number of bins
color='skyblue', # Bar color
edgecolor='black', # Bar edge color
alpha=0.8, # Transparency
label='Normal Dist.' # Legend label
)
# Add labels and title
[Link]('Value')
[Link]('Frequency')
[Link]('Basic Histogram of Random Data')
[Link]()
# Display the plot
[Link]()
Fundamentals of Python Programming for Beginners 250
Python Packages
OUTPUT:
Explanation:
• Data: 1000 random numbers from a normal distribution ([Link]).
• Parameters Used:
✓ x=data: The input data.
✓ bins=15: Uses 15 bins for the histogram.
✓ color='skyblue': Sets bar color.
✓ edgecolor='black': Adds black outlines for clarity.
✓ alpha=0.8: Slight transparency for visual effect.
✓ label='Normal Dist.': Adds a legend label.
• Output: A histogram showing the frequency of values in 15 bins, with labeled axes
and a legend.
Example Program: Normalized Histogram with Multiple Datasets
import [Link] as plt
import numpy as np
# Generate sample data
data1 = [Link](1000) # Normal distribution
data2 = [Link](-3, 3, 1000) # Uniform distribution
# Create histogram
[Link](
x=[data1, data2], # Multiple datasets
bins=20, # Number of bins
density=True, # Normalize to probability density
histtype='bar', # Bar-style histogram
color=['teal', 'orange'], # Colors for each dataset
label=['Normal', 'Uniform'], # Legend labels
orientation='horizontal', # Horizontal bars
alpha=0.7, # Transparency
rwidth=0.9 # Bar width with small gaps
)
Fundamentals of Python Programming for Beginners 251
Python Packages
# Add labels and title
[Link]('Density')
[Link]('Value')
[Link]('Normalized Histogram of Normal and Uniform Data')
[Link]()
# Display the plot
[Link]()
OUTPUT:
Explanation:
• Data: Two datasets (data1: normal distribution, data2: uniform distribution between
-3 and 3).
• Parameters Used:
✓ x=[data1, data2]: Plots two datasets in the same histogram.
✓ bins=20: Uses 20 bins.
✓ density=True: Normalizes the histogram to a probability density.
✓ histtype='bar': Uses bar-style histogram.
✓ color=['teal', 'orange']: Different colors for each dataset.
✓ label=['Normal', 'Uniform']: Labels for the legend.
✓ orientation='horizontal': Flips the histogram to horizontal bars.
✓ alpha=0.7: Adds transparency.
✓ rwidth=0.9: Creates small gaps between bars.
Output: A horizontal histogram comparing the normalized distributions of two datasets,
with a legend distinguishing them.
BUILT-IN FUNCTIONS OF [Link]: pie()
The pie() function in [Link] is used to create pie charts, which are circular
statistical graphics divided into slices to illustrate numerical proportions.
Fundamentals of Python Programming for Beginners 252
Python Packages
SYNTAX
[Link](
x,
explode=None,
labels=None,
colors=None,
autopct=None,
shadow=False,
startangle=0,
radius=1,
counterclock=True,
wedgeprops=None,
textprops=None,
center=(0, 0),
frame=False,
rotatelabels=False,
**kwargs
)
Explanation:
Parameter Description
x Array-like values representing the wedge sizes.
explode List of offsets to "explode" slices outward (e.g., [0.1, 0, 0]).
labels Labels for each slice.
colors List of colors for the slices.
autopct Format string or function to display values (e.g., '%1.1f%%').
shadow If True, adds a shadow beneath the pie.
startangle Angle (in degrees) to start the first slice.
radius Radius of the pie chart (default is 1).
counterclock If True, slices are drawn counterclockwise.
wedgeprops Dictionary of properties for the wedges (e.g., {'edgecolor': 'black'}).
textprops Dictionary of properties for the text labels (e.g., {'fontsize': 12}).
center Tuple specifying the center of the pie chart.
frame If True, draws a frame around the pie.
rotatelabels If True, rotates labels to match slice angles.
**kwargs Additional keyword arguments passed to [Link].
Example Program: Basic Pie Chart
import [Link] as plt
# Data values (percentages of the whole)
sizes = [25, 35, 40]
# Labels for each slice
labels = ['Apples', 'Bananas', 'Cherries']
# Plot pie chart
[Link](sizes, labels=labels)
# Add a title
[Link]('Fruit Distribution')
Fundamentals of Python Programming for Beginners 253
Python Packages
# Display the chart
[Link]()
OUTPUT:
Example Program: Exploded Pie Chart
import [Link] as plt
# Data values
sizes = [30, 50, 20]
# Labels for each slice
labels = ['Cats', 'Dogs', 'Birds']
# Explode: highlight the first slice (Cats) by 0.1 offset
explode = [0.1, 0, 0]
# Plot pie chart
[Link](sizes, labels=labels, explode=explode)
# Add title
[Link]('Pet Preferences')
# Display chart
[Link]()
Fundamentals of Python Programming for Beginners 254
Python Packages
OUTPUT:
Example Program: Pie Chart with Custom Styling and Rotated Labels
import [Link] as plt
# Data
sizes = [30, 50, 20]
labels = ['Cats', 'Dogs', 'Birds']
explode = [0.1, 0, 0] # Highlight Cats
# Create pie chart with customizations
[Link](
x=sizes, # Wedge sizes
labels=labels, # Wedge labels
explode=explode, # Explode Cats slice
colors=['cyan', 'yellow', 'pink'], # Custom colors
autopct='%.0f%%', # Show whole number percentages
startangle=45, # Start at 45 degrees
wedgeprops={'edgecolor': 'black', 'linewidth': 1.5}, # Black edges
textprops={'fontsize': 12}, # Larger label font
rotatelabels=True, # Rotate labels to align with wedges
radius=1.2 # Larger pie chart
)
# Add title
[Link]('Pet Preferences with Custom Styling')
# Ensure circular shape
[Link]('equal')
# Display the plot
[Link]()
Fundamentals of Python Programming for Beginners 255
Python Packages
OUTPUT:
Explanation:
Additions:
• colors=['cyan', 'yellow', 'pink']: Bright colors for each slice.
• autopct='%.0f%%': Shows percentages without decimals (e.g., 30%).
• startangle=45: Starts the chart at a 45-degree angle.
• wedgeprops={'edgecolor': 'black', 'linewidth': 1.5}: Adds black outlines to wedges.
• textprops={'fontsize': 12}: Increases label font size.
• rotatelabels=True: Rotates labels to align with each slice’s angle.
• radius=1.2: Makes the pie chart slightly larger.
• [Link]('equal'): Ensures circular shape.
Output: A larger pie chart with the “Cats” slice exploded, black-edged wedges, rotated
labels, whole-number percentages, and vibrant colors.
BUILT-IN FUNCTIONS OF [Link]: xlabel()
The xlabel() function in Matplotlib is used to set the label (name) of the x-axis in a plot.
This improves clarity by describing what values on the x-axis represent.
SYNTAX
[Link](
xlabel,
fontdict=None,
labelpad=None,
loc=None,
**kwargs
)
Explanation:
• xlabel: str. The x-axis label text (required).
• fontdict: dict, optional. Custom font properties, such as size, weight, color, etc.
• labelpad: float, optional. Padding (space) between label and axis.
• loc: {'left', 'center', 'right'}, optional. Alignment of label (default is 'center').
• kwargs: Additional text properties like color, fontsize, etc.
Fundamentals of Python Programming for Beginners 256
Python Packages
Example Program: Simple X-axis Label
import [Link] as plt
x = [1, 2, 3, 4]
y = [10, 20, 25, 30]
[Link](x, y)
[Link]("X-axis")
[Link]("Y-axis")
[Link]("Simple Line Plot")
[Link]()
OUTPUT:
Explanation:
Import: Imports [Link] for plotting.
Data:
• x = [1, 2, 3, 4]: X-coordinates for the plot.
• y = [10, 20, 25, 30]: Y-coordinates for the plot.
✓ [Link](x, y): Creates a line plot connecting the points (1, 10), (2, 20), (3, 25),
and (4, 30).
✓ [Link]("X-axis"): Sets the x-axis label to “X-axis” with default styling.
✓ [Link]("Y-axis"): Sets the y-axis label to “Y-axis”.
✓ [Link]("Simple Line Plot"): Sets the plot title.
✓ [Link](): Displays the plot.
Output: A line plot with a linear trend, labeled x-axis (“X-axis”), y-axis (“Y-axis”), and title
(“Simple Line Plot”), using Matplotlib’s default styling.
Example Program: Custom Font and Color
import [Link] as plt
x = [1, 2, 3, 4, 5]
y = [5, 15, 25, 35, 45]
[Link](x, y, marker='o')
[Link]("Time (seconds)", fontdict={'fontsize':14, 'color':'blue'})
[Link]("Distance (m)")
[Link]("Motion Graph")
[Link]()
Fundamentals of Python Programming for Beginners 257
Python Packages
OUTPUT:
Explanation:
Import: Imports [Link] for plotting.
Data:
• x = [1, 2, 3, 4, 5]: X-coordinates (time in seconds).
• y = [5, 15, 25, 35, 45]: Y-coordinates (distance in meters).
✓ [Link](x, y, marker='o'): Creates a line plot with circular markers at each
point (1, 5), (2, 15), (3, 25), (4, 35), (5, 45).
✓ [Link]("Time (seconds)", fontdict={'fontsize':14, 'color':'blue'}):
• Sets the x-axis label to “Time (seconds)”.
• fontdict={'fontsize':14, 'color':'blue'}: Uses a font size of 14 and blue color.
✓ [Link]("Distance (m)"): Sets the y-axis label to “Distance (m)”.
✓ [Link]("Motion Graph"): Sets the plot title.
✓ [Link](): Displays the plot.
Output: A line plot with circular markers showing a linear relationship between time and
distance, with a blue x-axis label (“Time (seconds)”), y-axis label (“Distance (m)”), and
title (“Motion Graph”).
Example Program: Label with Padding and Rotation
import [Link] as plt
x = [1, 2, 3, 4]
y = [2, 4, 6, 8]
[Link](x, y)
[Link]("Categories", fontsize=12, color='green', labelpad=15, rotation=0)
[Link]("Values")
[Link]("Bar Chart Example")
[Link]()
Fundamentals of Python Programming for Beginners 258
Python Packages
OUTPUT:
Explanation:
Import: Imports [Link] for plotting.
Data:
• x = [1, 2, 3, 4]: X-coordinates for the bars (categories).
• y = [2, 4, 6, 8]: Heights of the bars (values).
✓ [Link](x, y): Creates a bar chart with bars at x-positions 1, 2, 3, 4, with heights
2, 4, 6, 8.
✓ [Link]("Categories", fontsize=12, color='green', labelpad=15,
rotation=0):
• Sets the x-axis label to “Categories”.
• fontsize=12: Sets font size to 12.
• color='green': Uses green text.
• labelpad=15: Adds 15 points of spacing from the x-axis.
• rotation=0: Ensures no rotation (default).
✓ [Link]("Values"): Sets the y-axis label to “Values”.
✓ [Link]("Bar Chart Example"): Sets the plot title.
✓ [Link](): Displays the bar chart.
Output: A bar chart with four bars of increasing height, a green x-axis label (“Categories”)
with size 12 and 15-point padding, a y-axis label (“Values”), and a title (“Bar Chart
Example”).
BUILT-IN FUNCTIONS OF [Link]: xlabel(), ylabel(), title()
SYNTAX: xlabel()
Sets the label (title) for the x-axis.
[Link](xlabel, fontdict=None, labelpad=None, **kwargs)
Explanation:
• xlabel → Text for the x-axis.
• fontdict → Font styling (fontsize, weight, color).
• labelpad → Distance between label and axis.
SYNTAX: ylabel()
Sets the label (title) for the y-axis.
[Link](ylabel, fontdict=None, labelpad=None, **kwargs)
Explanation:
Works the same way as xlabel(), but for the y-axis.
Fundamentals of Python Programming for Beginners 259
Python Packages
SYNTAX: title()
Sets the main title for the plot.
[Link](label, fontdict=None, loc=None, pad=None, **kwargs)
Explanation:
• label → Title text.
• loc → Position ('center' (default), 'left', 'right').
• pad → Spacing between title and plot.
Example Program: Line Plot with Labels and Title
import [Link] as plt
x = [1, 2, 3, 4]
y = [2, 4, 6, 8]
[Link](x, y, marker='o')
[Link]("X-Axis")
[Link]("Y-Axis")
[Link]("Simple Line Plot")
[Link]()
OUTPUT:
Explanation:
Import: Imports [Link] for plotting.
Data:
• x = [1, 2, 3, 4]: X-coordinates.
• y = [2, 4, 6, 8]: Y-coordinates.
✓ [Link](x, y, marker='o'): Creates a line plot connecting points (1, 2), (2, 4),
(3, 6), and (4, 8) with circular markers.
✓ [Link]("X-Axis"): Sets the x-axis label to “X-Axis” with default styling.
✓ [Link]("Y-Axis"): Sets the y-axis label to “Y-Axis” with default styling.
✓ [Link]("Simple Line Plot"): Sets the plot title to “Simple Line Plot” with
default styling.
✓ [Link](): Displays the plot.
Output: A line plot with circular markers showing a linear trend, labeled x-axis (“X-Axis”),
y-axis (“Y-Axis”), and title (“Simple Line Plot”), using Matplotlib’s default styling.
Fundamentals of Python Programming for Beginners 260
Python Packages
Example Program: Custom Font and Color
import [Link] as plt
x = [10, 20, 30, 40]
y = [3, 7, 9, 12]
[Link](x, y, marker='s', color='red')
[Link]("Time (s)", fontdict={'fontsize':12, 'color':'blue'})
[Link]("Distance (m)", fontdict={'fontsize':12, 'color':'green'})
[Link]("Time vs Distance", fontdict={'fontsize':14, 'weight':'bold'}, loc='center')
[Link]()
OUTPUT:
Explanation:
Import: Imports [Link] for plotting.
Data:
• x = [10, 20, 30, 40]: X-coordinates (time in seconds).
• y = [3, 7, 9, 12]: Y-coordinates (distance in meters).
• [Link](x, y, marker='s', color='red'): Creates a red line plot with square
markers at points (10, 3), (20, 7), (30, 9), and (40, 12).
• [Link]("Time (s)", fontdict={'fontsize':12, 'color':'blue'}):
✓ Sets the x-axis label to “Time (s)”.
✓ fontdict={'fontsize':12, 'color':'blue'}: Size 12, blue color.
• [Link]("Distance (m)", fontdict={'fontsize':12, 'color':'green'}):
✓ Sets the y-axis label to “Distance (m)”.
✓ fontdict={'fontsize':12, 'color':'green'}: Size 12, green color.
• [Link]("Time vs Distance", fontdict={'fontsize':14, 'weight':'bold'},
loc='center'):
✓ Sets the title to “Time vs Distance”.
✓ fontdict={'fontsize':14, 'weight':'bold'}: Size 14, bold.
✓ loc='center': Centers the title (default).
• [Link](): Displays the plot.
Output: A red line plot with square markers showing a trend between time and distance,
with a blue x-axis label (“Time (s)”), green y-axis label (“Distance (m)”), and bold,
centered title (“Time vs Distance”).
Fundamentals of Python Programming for Beginners 261
Python Packages
Example Program: Bar Chart with Padding
import [Link] as plt
x = ['A', 'B', 'C', 'D']
y = [5, 7, 3, 8]
[Link](x, y, color='orange')
[Link]("Categories", labelpad=15)
[Link]("Values", labelpad=15)
[Link]("Bar Chart Example", pad=20)
[Link]()
OUTPUT:
Explanation:
Import: Imports [Link] for plotting.
Data:
• x = ['A', 'B', 'C', 'D']: Categorical x-coordinates (labels for categories).
• y = [5, 7, 3, 8]: Heights of the bars (values).
• [Link](x, y, color='orange'): Creates a bar chart with orange bars at categories
A, B, C, D, with heights 5, 7, 3, 8.
• [Link]("Categories", labelpad=15):
✓ Sets the x-axis label to “Categories”.
✓ labelpad=15: Adds 15 points of spacing from the x-axis.
• [Link]("Values", labelpad=15):
✓ Sets the y-axis label to “Values”.
✓ labelpad=15: Adds 15 points of spacing from the y-axis.
• [Link]("Bar Chart Example", pad=20):
✓ Sets the title to “Bar Chart Example”.
✓ pad=20: Adds 20 points of spacing above the plot.
• [Link](): Displays the bar chart.
Output: A bar chart with four orange bars, labeled x-axis (“Categories”) and y-axis
(“Values”) with 15-point padding, and a title (“Bar Chart Example”) with 20-point
padding, using Matplotlib’s default styling.
Fundamentals of Python Programming for Beginners 262
Python Packages
Example Program: Simple X-axis Label
import [Link] as plt
x = [1, 2, 3, 4]
y = [10, 20, 25, 30]
[Link](x, y)
[Link]("X-axis")
[Link]("Y-axis")
[Link]("Simple Line Plot")
[Link]()
OUTPUT:
Explanation:
Import: Imports [Link] for plotting.
Data:
• x = [1, 2, 3, 4]: X-coordinates for the plot.
• y = [10, 20, 25, 30]: Y-coordinates for the plot.
✓ [Link](x, y): Creates a line plot connecting the points (1, 10), (2, 20), (3, 25),
and (4, 30).
✓ [Link]("X-axis"): Sets the x-axis label to “X-axis” with default styling.
✓ [Link]("Y-axis"): Sets the y-axis label to “Y-axis”.
✓ [Link]("Simple Line Plot"): Sets the plot title.
✓ [Link](): Displays the plot.
Output: A line plot with a linear trend, labeled x-axis (“X-axis”), y-axis (“Y-axis”), and title
(“Simple Line Plot”), using Matplotlib’s default styling.
SYNTAX: legend()
• The legend() function in Matplotlib is used to display a legend box that identifies
the elements (lines, bars, etc.) in your plot.
• A legend identifies the plotted elements, clarifies their meaning, and makes
complex graphs readable.
[Link](
loc='best',
labels=None,
fontsize=None,
title=None,
shadow=False,
frameon=True,
ncol=1,
bbox_to_anchor=None,
Fundamentals of Python Programming for Beginners 263
Python Packages
**kwargs
)
Explanation:
loc → Position of legend ('best', 'upper left', 'upper right', 'lower left', 'lower right',
'center', etc.). Default = 'best'.
labels → Custom labels for the legend.
fontsize → Size of legend text.
title → Title for the legend box.
shadow → If True, draws shadow under legend.
frameon → If False, removes the box frame.
ncol → Number of columns in legend.
bbox_to_anchor → Places legend outside the plot ((x, y) coordinates).
Example Program: Simple Line Plot with Legend
import [Link] as plt
x = [1, 2, 3, 4]
y1 = [1, 4, 9, 16]
y2 = [1, 2, 3, 4]
[Link](x, y1, label="Squares")
[Link](x, y2, label="Line")
[Link]("X-axis")
[Link]("Y-axis")
[Link]("Legend Example 1")
[Link]() # default position
[Link]()
OUTPUT:
Explanation:
Import: Imports [Link] for plotting.
Data:
• x = [1, 2, 3, 4]: X-coordinates.
• y1 = [1, 4, 9, 16]: Y-coordinates for the first dataset (squares of x).
• y2 = [1, 2, 3, 4]: Y-coordinates for the second dataset (linear).
• [Link](x, y1, label="Squares"): Plots a line for y1 with label “Squares”.
• [Link](x, y2, label="Line"): Plots a line for y2 with label “Line”.
Fundamentals of Python Programming for Beginners 264
Python Packages
• [Link]("X-axis"): Sets the x-axis label to “X-axis” with default styling.
• [Link]("Y-axis"): Sets the y-axis label to “Y-axis” with default styling.
• [Link]("Legend Example 1"): Sets the title to “Legend Example 1” with default
styling.
• [Link](): Adds a legend using default settings (loc='best', frameon=True,
shadow=False, ncol=1), displaying “Squares” and “Line” based on plot labels.
• [Link](): Displays the plot.
Output: A line plot with two lines (one for squares, one linear), labeled x-axis (“X-axis”),
y-axis (“Y-axis”), title (“Legend Example 1”), and a legend automatically placed to
minimize overlap, showing “Squares” and “Line”.
Example Program: Legend with Custom Location & Title
import [Link] as plt
x = [1, 2, 3, 4, 5]
y1 = [2, 4, 6, 8, 10]
y2 = [1, 3, 5, 7, 9]
[Link](x, y1, label="Even Numbers", color='blue')
[Link](x, y2, label="Odd Numbers", color='green')
[Link]("Legend Example 2")
[Link](loc='upper left', title="Number Types", fontsize=10)
[Link]()
OUTPUT:
Explanation:
Import: Imports [Link] for plotting.
Data:
• x = [1, 2, 3, 4, 5]: X-coordinates.
• y1 = [2, 4, 6, 8, 10]: Y-coordinates for the first dataset (even numbers).
• y2 = [1, 3, 5, 7, 9]: Y-coordinates for the second dataset (odd numbers).
• [Link](x, y1, label="Even Numbers", color='blue'): Plots a blue line for y1 with
label “Even Numbers”.
• [Link](x, y2, label="Odd Numbers", color='green'): Plots a green line for y2
with label “Odd Numbers”.
Fundamentals of Python Programming for Beginners 265
Python Packages
• [Link]("Legend Example 2"): Sets the title to “Legend Example 2” with default
styling.
• [Link](loc='upper left', title="Number Types", fontsize=10):
✓ Adds a legend in the upper left corner.
✓ title="Number Types": Sets the legend title.
✓ fontsize=10: Sets legend text size to 10.
✓ Uses default settings for other parameters (frameon=True, shadow=False,
ncol=1).
• [Link](): Displays the plot.
Output: A line plot with two lines (blue for even numbers, green for odd numbers), a title
(“Legend Example 2”), and a legend in the upper left with title “Number Types” and labels
“Even sNumbers” and “Odd Numbers”. No axis labels are included.
SYNTAX: grid()
The grid() function in Matplotlib is used to add grid lines to your plot for better readability
of values.
[Link](
b=None,
which='major',
axis='both',
color=None,
linestyle=None,
linewidth=None,
**kwargs
)
Explanation:
• b → Boolean (True / False) to turn grid on or off.
• which → 'major' (default), 'minor', or 'both' → controls which ticks have grid lines.
• axis → 'both' (default), 'x', or 'y' → controls where the grid appears.
• color → Color of grid lines (e.g., 'grey', 'red').
• linestyle → Style of grid ('-' solid, '--' dashed, ':' dotted, '-.' dash-dot).
• linewidth → Thickness of grid lines.
• kwargs → Extra customization.
Example Program: Simple Line Plot with Legend
import [Link] as plt
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
[Link](x, y, marker='o')
[Link]("Example with Grid")
# Enable grid lines
[Link](True, which='both', axis='both', color='gray', linestyle='--', linewidth=0.7)
[Link]()
Fundamentals of Python Programming for Beginners 266
Python Packages
OUTPUT:
Explanation:
Import: Imports [Link] for plotting.
Data:
x = [1, 2, 3, 4, 5]: X-coordinates.
y = [2, 4, 6, 8, 10]: Y-coordinates (linear relationship, y = 2x).
• [Link](x, y, marker='o'): Creates a line plot with circular markers at points (1,
2), (2, 4), (3, 6), (4, 8), (5, 10).
• [Link]("Example with Grid"): Sets the title to “Example with Grid” with default
styling.
• [Link](True, which='both', axis='both', color='gray', linestyle='--',
linewidth=0.7): Enables grid lines (True).
which='both': Includes both major and minor grid lines.
axis='both': Applies grid lines to both x- and y-axes.
color='gray': Sets grid lines to gray.
linestyle='--': Uses dashed lines.
linewidth=0.7: Sets line thickness to 0.7 points.
• [Link](): Displays the plot.
Output: A line plot with circular markers, a title (“Example with Grid”), and a grid of
dashed gray lines (major and minor) on both axes. No axis labels or legend are included.
Example Program: Line Plot with Styled Major Grid and Legend
import [Link] as plt
# Data
x = [1, 2, 3, 4, 5]
y = [5, 7, 6, 8, 7]
# Create line plot with label
[Link](x, y, marker='o', color='red', label='Data Trend')
# Set labels and title
[Link]('Index', fontdict={'fontsize': 12, 'color': 'navy'}, labelpad=10)
[Link]('Values', fontdict={'fontsize': 12, 'color': 'darkgreen'}, labelpad=10)
[Link]('Line Plot with Major Grid', fontdict={'fontsize': 14, 'fontweight': 'bold',
'color': 'purple'}, pad=15)
Fundamentals of Python Programming for Beginners 267
Python Packages
# Enable grid with customizations
[Link](True, which='major', axis='both', color='blue', linestyle='--', linewidth=0.8,
alpha=0.6)
# Add legend
[Link](loc='upper left', fontsize=10, title='Data')
# Display plot
[Link]()
OUTPUT:
Explanation:
• Plot: A red line plot with circular markers.
• xlabel: “Index”, size 12, navy, 10-point padding.
• ylabel: “Values”, size 12, dark green, 10-point padding.
• title: “Line Plot with Major Grid”, bold, size 14, purple, 15-point padding.
• grid: Major grid lines on both axes, blue, dashed, 0.8-point width, 60% opacity.
• legend: Upper left, size 10, with title “Data”.
Output: A line plot with a blue dashed major grid, styled axis labels, a bold title, and a
legend.
Example Program: Scatter Plot with Major and Minor Grid
import [Link] as plt
# Data
x = [1, 2, 3, 4, 5]
y = [5, 7, 6, 8, 7]
y2 = [4, 6, 5, 7, 6] # Second dataset for comparison
# Create scatter plots with labels
[Link](x, y, color='red', s=100, marker='o', label='Primary Data')
[Link](x, y2, color='green', s=80, marker='^', label='Secondary Data')
# Set labels and title
[Link]('X Values', fontdict={'fontsize': 12, 'color': 'black'}, labelpad=10)
[Link]('Y Values', fontdict={'fontsize': 12, 'color': 'black'}, labelpad=10)
Fundamentals of Python Programming for Beginners 268
Python Packages
[Link]('Scatter Plot with Grid', fontdict={'fontsize': 14, 'color': 'darkblue'},
pad=15)
# Enable minor ticks
plt.minorticks_on()
# Enable grid with customizations
[Link](True, which='both', axis='both', color='gray', linestyle=':', linewidth=0.5,
alpha=0.7)
# Add legend
[Link](loc='best', fontsize=10, title='Datasets', ncol=2, framealpha=0.8)
# Display plot
[Link]()
OUTPUT:
Explanation:
• Plot: Two scatter plots (red circles for y, green triangles for y2).
• xlabel: “X Values”, size 12, black, 10-point padding.
• ylabel: “Y Values”, size 12, black, 10-point padding.
• title: “Scatter Plot with Grid”, size 14, dark blue, 15-point padding.
• grid: Major and minor grid lines (which='both'), gray, dotted, 0.5-point width, 70%
opacity. Minor ticks enabled with plt.minorticks_on().
• legend: Automatically placed (loc='best'), size 10, title “Datasets”, two columns,
semi-transparent frame.
• Output: A scatter plot with major and minor gray dotted grids, axis labels, and a
two-column legend.
SYNTAX: xlim() and ylim()
These functions are used to set or get the limits of the x-axis and y-axis in a plot.
[Link]([xmin, xmax])
[Link]([ymin, ymax])
or
[Link](xmin, xmax)
[Link](ymin, ymax)
Note: Both forms are valid.
Fundamentals of Python Programming for Beginners 269
Python Packages
Explanation:
xlim(): Sets the limits of the x-axis.
• xmin: Minimum value to display on the x-axis.
• xmax: Maximum value to display on the x-axis.
ylim(): Sets the limits of the y-axis.
• ymin: Minimum value to display on the y-axis.
• ymax: Maximum value to display on the y-axis.
Example Program: Simple Line Plot with Legend
import [Link] as plt
x = [1, 2, 3, 4, 5]
y = [10, 20, 25, 30, 40]
[Link](x, y)
[Link](2, 4)
[Link](15, 35)
[Link]("Zoomed View")
[Link]()
OUTPUT:
Explanation:
Import: Imports [Link] for plotting.
Data:
• x = [1, 2, 3, 4, 5]: X-coordinates.
• y = [10, 20, 25, 30, 40]: Y-coordinates.
• [Link](x, y): Creates a line plot connecting points (1, 10), (2, 20), (3, 25), (4, 30),
(5, 40) with default styling (blue line, no markers).
• [Link](2, 4): Sets the x-axis range from 2 to 4, zooming in on a subset of the data.
• [Link](15, 35): Sets the y-axis range from 15 to 35, focusing on the
corresponding y-values.
• [Link]("Zoomed View"): Sets the title to “Zoomed View” with default styling.
• [Link](): Displays the plot.
Output: A line plot showing only the portion of the data between x=2 and x=4 (points (2,
20), (3, 25), (4, 30)), with y-values between 15 and 35. No axis labels, legend, or grid are
included.
Fundamentals of Python Programming for Beginners 270
Python Packages
Example Program: Zooming into Part of the Graph
import [Link] as plt
x = [0, 1, 2, 3, 4, 5, 6]
y = [0, 1, 4, 9, 16, 25, 36]
[Link](x, y, marker='o', color='green')
[Link]("Zoomed-in View")
[Link](2, 5)
[Link](0, 30)
[Link]()
OUTPUT:
Explanation:
Import: Imports [Link] for plotting.
Data:
• x = [0, 1, 2, 3, 4, 5, 6]: X-coordinates.
• y = [0, 1, 4, 9, 16, 25, 36]: Y-coordinates (quadratic relationship, y = x²).
[Link](x, y, marker='o', color='green'): Creates a green line plot with circular markers
at points (0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25), (6, 36).
[Link]("Zoomed-in View"): Sets the title to “Zoomed-in View” with default styling.
[Link](2, 5): Sets the x-axis range from 2 to 5, zooming in to show points (2, 4), (3, 9),
(4, 16), (5, 25).
[Link](0, 30): Sets the y-axis range from 0 to 30, focusing on y-values up to 30.
[Link](): Displays the plot.
Output: A green line plot with circular markers, showing only the portion of the data
between x=2 and x=5 (points (2, 4), (3, 9), (4, 16), (5, 25)), with y-values between 0 and
30. No axis labels, legend, or grid are included.
5.5 NumPy Built-in functions
NumPy is a fundamental Python library for numerical operations (computations),
offering a wide range of built-in functions for array creation, manipulation, mathematical
operations, and statistical analysis.
Fundamentals of Python Programming for Beginners 271
Python Packages
The different NumPy type built-in functions are:
• Array Creation
• Array Inspection
• Math Functions
• Elementwise Operations
• Linear Algebra
• Random
• Reshape & Manipulation
• Sorting & Searching
5.5.1 Array Creation built-in functions of packages NumPy
Array creation functions in NumPy are built-in methods that allow users to initialize arrays of
various shapes, sizes, and values. These functions are foundational for numerical computing,
enabling efficient storage, manipulation, and processing of data in structured formats.
They support:
• Manual input (e.g., from lists or tuples)
• Automated generation (e.g., ranges, random values, identity matrices)
• Custom initialization (e.g., zeros, ones, specific values)
Table: Summary of Array Creation built-in functions of packages NumPy
Method Syntax Example Explanation
Converts a list or tuple
array() [Link](object, dtype=None) [Link]([1, 2, 3]) → [1 2 3]
into a NumPy array.
Creates an array filled
[Link]((2, 3)) → [[0. 0.
zeros() [Link](shape, dtype=float) with zeros. Shape is
0.],[0. 0. 0.]]
(rows, columns).
[Link]((3, 2)) → [[1. 1.],[1. Creates an array filled
ones() [Link](shape, dtype=float)
1.],[1. 1.]] with ones.
Creates an array
[Link]((2, 2)) → [[6.9e-
without initializing
empty() [Link](shape, dtype=float) 310 6.9e-310],[0.0 0.0]]
entries (may contain
(values may vary)
garbage values).
[Link]((2, 2), 7) → [[7 7],[7 Creates an array filled
full() [Link](shape, fill_value)
7]] with a specified value.
Creates array with
[Link](0, 10, 2) → [0 2 4
arange() [Link](start, stop, step) evenly spaced values
6 8]
within a range.
Creates array with
[Link](0, 1, 5) → [0.
linspace() [Link](start, stop, num) evenly spaced values
0.25 0.5 0.75 1.]
between two points.
[Link](3) → [[1. 0. 0.],[0. 1. Creates a 2D identity
eye() [Link](N, M=None, k=0)
0.],[0. 0. 1.]] matrix.
Creates array with
[Link](2, 2) →
random values from a
[Link]() [Link](d0, d1, ..., dn) [[0.12 0.73],[0.55 0.91]]
uniform distribution
(values vary)
over [0, 1).
[Link](1, 10, Creates array with
[Link]() [Link](low, high, size) size=(2, 3)) → [[3 7 2],[9 1 random integers in a
5]] (values vary) specified range.
Example Program: Array Creation in NumPy
import numpy as np
# 1. array()
print("1. array()")
arr = [Link]([1, 2, 3])
print(arr) # → [1 2 3]
print()
Fundamentals of Python Programming for Beginners 272
Python Packages
# 2. zeros()
print("2. zeros()")
z = [Link]((2, 3))
print(z) # → [[0. 0. 0.], [0. 0. 0.]]
print()
# 3. ones()
print("3. ones()")
o = [Link]((3, 2))
print(o) # → [[1. 1.], [1. 1.], [1. 1.]]
print()
# 4. empty()
print("4. empty()")
e = [Link]((2, 2))
print(e) # values may vary (garbage values)
print()
# 5. full()
print("5. full()")
f = [Link]((2, 2), 7)
print(f) # → [[7 7], [7 7]]
print()
# 6. arange()
print("6. arange()")
a = [Link](0, 10, 2)
print(a) # → [0 2 4 6 8]
print()
# 7. linspace()
print("7. linspace()")
l = [Link](0, 1, 5)
print(l) # → [0. 0.25 0.5 0.75 1. ]
print()
# 8. eye()
print("8. eye()")
I = [Link](3)
print(I) # → [[1. 0. 0.], [0. 1. 0.], [0. 0. 1.]]
print()
# 9. [Link]()
print("9. [Link]()")
r = [Link](2, 2)
print(r) # values vary (uniform [0,1))
print()
# 10. [Link]()
print("10. [Link]()")
ri = [Link](1, 10, size=(2, 3))
print(ri) # values vary between 1 and 9
OUTPUT: (values of random functions will vary)
1. array()
[1 2 3]
Fundamentals of Python Programming for Beginners 273
Python Packages
2. zeros()
[[0. 0. 0.]
[0. 0. 0.]]
3. ones()
[[1. 1.]
[1. 1.]
[1. 1.]]
4. empty()
[[6.94333818e-310 6.94333818e-310]
[0.00000000e+000 0.00000000e+000]]
(values will differ each time)
5. full()
[[7 7]
[7 7]]
6. arange()
[0 2 4 6 8]
7. linspace()
[0. 0.25 0.5 0.75 1. ]
8. eye()
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
9. [Link]()
[[0.312 0.789]
[0.452 0.987]]
(values will differ each time)
10. [Link]()
[[8 3 5]
[2 7 9]]
(values will differ each time)
Example Program: Array Creation in NumPy
import numpy as np
# 1. array()
arr = [Link]([1, 2, 3])
print("array():", arr)
# 2. zeros()
z = [Link]((2, 3))
print("\nzeros():\n", z)
# 3. ones()
o = [Link]((3, 2))
print("\nones():\n", o)
# 4. empty()
e = [Link]((2, 2))
Fundamentals of Python Programming for Beginners 274
Python Packages
print("\nempty():\n", e)
# 5. full()
f = [Link]((2, 2), 7)
print("\nfull():\n", f)
# 6. arange()
a = [Link](0, 10, 2)
print("\narange():", a)
# 7. linspace()
l = [Link](0, 1, 5)
print("\nlinspace():", l)
# 8. eye()
I = [Link](3)
print("\neye():\n", I)
# 9. [Link]()
r = [Link](2, 2)
print("\[Link]():\n", r)
# 10. [Link]()
ri = [Link](1, 10, size=(2, 3))
print("\[Link]():\n", ri)
Output: (values of random functions will vary)
array(): [1 2 3]
zeros():
[[0. 0. 0.]
[0. 0. 0.]]
ones():
[[1. 1.]
[1. 1.]
[1. 1.]]
empty():
[[0.00000000e+000 0.00000000e+000]
[4.65661320e-310 6.93211133e-310]] # (garbage values may change)
full():
[[7 7]
[7 7]]
arange(): [0 2 4 6 8]
linspace(): [0. 0.25 0.5 0.75 1. ]
eye():
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
[Link]():
[[0.45 0.67]
Fundamentals of Python Programming for Beginners 275
Python Packages
[0.21 0.89]]
[Link]():
[[3 7 2]
[9 1 5]]
5.5.2 Array Inspection built-in functions of packages NumPy
Array inspection functions help you look inside a NumPy array to understand its structure, size,
shape, and data type. Think of them as tools to “ask questions” about the array like how big it is,
what kind of data it holds, and how it's organized.
Table: Summary of Array Inspection built-in functions of packages NumPy
Method Syntax Example Output Explanation
a= Shows the dimensions
[Link] [Link] [Link]([[1,2],[3,4],[5,6]]); (3, 2) of the array (e.g., 3
[Link] rows, 2 columns).
Returns the number of
[Link] [Link] [Link] 2 dimensions (e.g., 2 for a
2D array).
Counts the total
number of elements
[Link] [Link] [Link] 6
(e.g., 3 rows × 2
columns = 6).
dtype('int32') Shows the data type of
[Link] [Link] [Link] (system- elements (e.g., int32 for
dependent) integers).
Size in bytes of each
[Link] [Link] [Link] 4 (for int32) element (e.g., 4 bytes
for int32).
Total memory used
[Link] [Link] [Link] 24 (e.g., 6 elements × 4
bytes = 24 bytes).
Transposes the array
[[1, 3, 5],
array.T a.T a.T (swaps rows and
[2, 4, 6]]
columns).
(Detailed Shows full details like
[Link](obj) [Link](a) [Link](a) metadata shape, dtype, strides,
printed) and memory layout.
Checks if elements are
[Link](a) [Link](a) [Link]([1, [Link]]) [False, True]
NaN (Not a Number).
Checks if elements are
[Link](a) [Link](a) [Link]([1, [Link]]) [False, True]
infinite (e.g., inf or -inf).
Note:
• The examples assume import numpy as np and a = [Link]([[1, 2], [3, 4], [5, 6]])
unless specified otherwise.
• Outputs for dtype, itemsize, and nbytes may vary depending on the system (e.g.,
int32 vs. int64).
• [Link](a) prints a detailed report to the console, not a return value, so the output
isn’t a simple array.
Example Program: Integer 2D Array
import numpy as np
# Example 1: 2D integer array
a = [Link]([[1, 2], [3, 4], [5, 6]])
Fundamentals of Python Programming for Beginners 276
Python Packages
print("Array:\n", a)
print("Shape:", [Link]) # (3, 2)
print("Dimensions:", [Link]) #2
print("Size:", [Link]) #6
print("Data Type:", [Link]) # int32 (may vary)
print("Item Size:", [Link]) # 4 (bytes per element)
print("Total Bytes:", [Link]) # 24 (6 elements × 4 bytes)
print("Transpose:\n", a.T) # Transposed array
print("\nCheck for NaN:", [Link](a)) # All False
print("Check for Inf:", [Link](a)) # All False
print("\nArray Info:")
[Link](a)
OUTPUT:
Array:
[[1 2]
[3 4]
[5 6]]
Shape: (3, 2)
Dimensions: 2
Size: 6
Data Type: int32
Item Size: 4
Total Bytes: 24
Transpose:
[[1 3 5]
[2 4 6]]
Check for NaN:
[[False False]
[False False]
[False False]]
Check for Inf:
[[False False]
[False False]
[False False]]
Array Info:
class: ndarray
shape: (3, 2)
strides: (8, 4)
itemsize: 4
aligned: True
contiguous: True
dtype: int32
Example Program: Covers All Array Inspection Functions
import numpy as np
# Create a 1D and 2D array
arr1 = [Link]([10, 20, 30, 40, 50])
arr2 = [Link]([[1.5, 2.5], [3.5, 4.5], [5.5, 6.5]])
print("Array 1:\n", arr1)
Fundamentals of Python Programming for Beginners 277
Python Packages
print("Array 2:\n", arr2)
# Inspection on arr1
print("\n--- Inspection of arr1 ---")
print("Number of dimensions:", [Link])
print("Shape:", [Link])
print("Size:", [Link])
print("Data type:", [Link])
print("Item size:", [Link])
print("Total bytes used:", [Link])
print("Transpose:\n", arr1.T)
# Inspection on arr2
print("\n--- Inspection of arr2 ---")
print("Number of dimensions:", [Link])
print("Shape:", [Link])
print("Size:", [Link])
print("Data type:", [Link])
print("Item size:", [Link])
print("Total bytes used:", [Link])
print("Transpose:\n", arr2.T)
OUTPUT:
Array 1:
[10 20 30 40 50]
Array 2:
[[1.5 2.5]
[3.5 4.5]
[5.5 6.5]]
--- Inspection of arr1 ---
Number of dimensions: 1
Shape: (5,)
Size: 5
Data type: int32
Item size: 4
Total bytes used: 20
Transpose:
[10 20 30 40 50]
--- Inspection of arr2 ---
Number of dimensions: 2
Shape: (3, 2)
Size: 6
Data type: float64
Item size: 8
Total bytes used: 48
Transpose:
[[1.5 3.5 5.5]
[2.5 4.5 6.5]]
Fundamentals of Python Programming for Beginners 278
Python Packages
Example Program: Array with NaN and Inf
import numpy as np
# Create array with NaN and Inf values
b = [Link]([1.0, [Link], [Link], -[Link]])
print("Array b:", b)
print("Shape:", [Link]) # (4,)
print("Dimensions:", [Link]) # 1
print("Size:", [Link]) #4
print("Data Type:", [Link]) # float64
print("Item Size:", [Link]) # 8 (for float64)
print("Total Bytes:", [Link]) # 32 (4 elements × 8 bytes)
print("Transpose:", b.T) # same as b (1D array has no change)
print("\nCheck for NaN:", [Link](b)) # [False True False False]
print("Check for Inf:", [Link](b)) # [False False True True]
print("\nArray Info:")
[Link](b)
OUTPUT:
Array b: [ 1. nan inf -inf]
Shape: (4,)
Dimensions: 1
Size: 4
Data Type: float64
Item Size: 8
Total Bytes: 32
Transpose: [ 1. nan inf -inf]
Check for NaN: [False True False False]
Check for Inf: [False False True True]
Array Info:
class: ndarray
shape: (4,)
strides: (8,)
itemsize: 8
aligned: True
contiguous: True
dtype: float64
Example Program:
import numpy as np
# Create a sample 2D array
a = [Link]([[1, 2], [3, 4], [5, 6]])
# 1. [Link]: Shows the dimensions (rows, columns)
print("Shape:", [Link])
# 2. [Link]: Number of dimensions
print("Number of dimensions:", [Link])
Fundamentals of Python Programming for Beginners 279
Python Packages
# 3. [Link]: Total number of elements
print("Size:", [Link])
# 4. [Link]: Data type of elements
print("Data type:", [Link])
# 5. [Link]: Size of each element in bytes
print("Item size (bytes):", [Link])
# 6. [Link]: Total memory used in bytes
print("Total bytes:", [Link])
# 7. array.T: Transpose (swap rows and columns)
print("Transpose:\n", a.T)
# 8. [Link](obj): Detailed metadata about the array
print("Array info:")
[Link](a)
# 9. [Link](a): Check for NaN values
# Create a new array with a NaN value for this example
b = [Link]([1, [Link], 3])
print("Is NaN:", [Link](b))
# 10. [Link](a): Check for infinite values
# Create a new array with an infinite value for this example
c = [Link]([1, [Link], 3])
print("Is infinite:", [Link](c))
OUTPUT:
Shape: (3, 2)
Number of dimensions: 2
Size: 6
Data type: int64
Item size (bytes): 8
Total bytes: 48
Transpose:
[[1 3 5]
[2 4 6]]
Array info:
class: ndarray
shape: (3, 2)
strides: (16, 8)
itemsize: 8
aligned: True
contiguous: True
fortran: False
data pointer: 0x1730de0
byteorder: little
byteswap: False
type: int64
Is NaN: [False True False]
Is infinite: [False True False]
Fundamentals of Python Programming for Beginners 280
Python Packages
5.5.3 Math Functions of NumPy
Math functions in NumPy are built-in tools that let you perform mathematical
operations directly on arrays quickly and efficiently. Instead of looping through each
element like in regular Python, NumPy applies the operation to the entire array at once.
Table: Summary of Math Functions built-in functions of packages NumPy
Type Syntax Example Output Explanation
Adds elements
[Link](x, y) [Link]([1,2,3], [4,5,6]) [5 7 9]
of two arrays
Subtracts
[Link](x, [Link]([10,20,30],
[ 9 18 27] second array
y) [1,2,3])
from first
[Link](x, Multiplies
[Link]([2,3,4], [5,6,7]) [10 18 28]
Arithmetic y) element-wise
Functions Divides
[Link](x, y) [Link]([10,20,30], [2,5,10]) [ 5. 4. 3.]
element-wise
Raises
[Link](x, y) [Link]([2,3,4], 2) [ 4 9 16] elements to a
power
Remainder
[Link](x, y) [Link]([10,20,30], 7) [3 6 2]
after division
Computes sine
[Link](x) [Link](np.deg2rad([0,30,90])) [0. 0.5 1.]
values
Computes
[Link](x) [Link](np.deg2rad([0,60,90])) [1. 0.5 0.]
cosine values
Computes
[Link](x) [Link](np.deg2rad([0,45])) [0. 1.]
tangent values
Trigonometric Inverse sine
[Link](x) [Link]([0,1]) [0. 1.5708]
Functions (radians)
Converts
np.deg2rad(x) np.deg2rad([180]) [3.1416] degrees →
radians
Converts
np.rad2deg(x) np.rad2deg([[Link]]) [180.] radians →
degrees
Computes
[2.71828183
[Link](x) [Link]([1,2]) exponential
7.3890561 ]
(e^x)
Exponential &
Natural log
Log Functions [Link](x) [Link]([1, np.e, np.e**2]) [0. 1. 2.]
(base e)
np.log10(x) np.log10([1,10,100]) [0. 1. 2.] Log base 10
np.log2(x) np.log2([1,2,4,8]) [0. 1. 2. 3.] Log base 2
Rounds to
[Link](x, n) [Link]([1.234, 2.567], 2) [1.23 2.57]
given decimals
Rounds down
Rounding
[Link](x) [Link]([1.2, 2.9, -3.7]) [ 1. 2. -4.] to nearest
Functions
integer
Rounds up to
[Link](x) [Link]([1.2, 2.9, -3.7]) [ 2. 3. -3.]
nearest integer
NOTE:
Arithmetic : add, subtract, multiply, divide, power, mod
Trigonometric : sin, cos, tan, arcsin, rad2deg, deg2rad
Exponential & Log : exp, log, log10, log2
Rounding : around, floor, ceil
Fundamentals of Python Programming for Beginners 281
Python Packages
Example Program: Arithmetic and Trigonometric Functions
import numpy as np
# Arithmetic operations
a1 = [Link]([1, 2, 3])
a2 = [Link]([4, 5, 6])
print("Addition:", [Link](a1, a2)) # [5 7 9]
print("Subtraction:", [Link]([10, 20, 30], [1, 2, 3])) # [9 18 27]
print("Multiplication:", [Link]([2, 3, 4], [5, 6, 7])) # [10 18 28]
print("Division:", [Link]([10, 20, 30], [2, 5, 10])) # [5. 4. 3.]
print("Power:", [Link]([2, 3, 4], 2)) # [4 9 16]
print("Modulus:", [Link]([10, 20, 30], 7)) # [3 6 2]
# Trigonometric operations
angles_deg = [Link]([0, 30, 90])
angles_rad = np.deg2rad(angles_deg)
print("Sine:", [Link](angles_rad)) # [0. 0.5 1.]
print("Cosine:", [Link](np.deg2rad([0, 60, 90]))) # [1. 0.5 0.]
print("Tangent:", [Link](np.deg2rad([0, 45]))) # [0. 1.]
print("Arcsin:", [Link]([0, 1])) # [0. 1.5708]
print("Degrees to Radians:", np.deg2rad([180])) # [3.1416]
print("Radians to Degrees:", np.rad2deg([[Link]])) # [180.]
OUTPUT:
Addition: [5 7 9]
Subtraction: [ 9 18 27]
Multiplication: [10 18 28]
Division: [5. 4. 3.]
Power: [ 4 9 16]
Modulus: [3 6 2]
Sine: [0. 0.5 1. ]
Cosine: [1. 0.5 0. ]
Tangent: [0. 1.]
Arcsin: [0. 1.5708]
Degrees to Radians: [3.1416]
Radians to Degrees: [180.]
Example Program: Exponential, Logarithmic, and Rounding Functions
import numpy as np
# Exponential and logarithmic functions
print("Exponential:", [Link]([1, 2])) # [2.71828183 7.3890561]
print("Natural Log:", [Link]([1, np.e, np.e**2])) # [0. 1. 2.]
print("Log base 10:", np.log10([1, 10, 100])) # [0. 1. 2.]
print("Log base 2:", np.log2([1, 2, 4, 8])) # [0. 1. 2. 3.]
# Rounding functions
print("Around (2 decimals):", [Link]([1.234, 2.567], 2)) # [1.23 2.57]
print("Floor:", [Link]([1.2, 2.9, -3.7])) # [ 1. 2. -4.]
print("Ceil:", [Link]([1.2, 2.9, -3.7])) # [ 2. 3. -3.]
OUTPUT:
Exponential: [2.71828183 7.3890561 ]
Natural Log: [0. 1. 2.]
Log base 10: [0. 1. 2.]
Log base 2: [0. 1. 2. 3.]
Around (2 decimals): [1.23 2.57]
Fundamentals of Python Programming for Beginners 282
Python Packages
Floor: [ 1. 2. -4.]
Ceil: [ 2. 3. -3.]
Example Program: Arithmetic and Trigonometric Functions, Exponential,
Logarithmic, and Rounding Functions
import numpy as np
a = [Link]([2, 4])
b = [Link]([1, 3])
print("---- Arithmetic ----")
print("a + b =", [Link](a, b)) # [3 7]
print("a * b =", [Link](a, b)) # [2 12]
print("\n---- Trigonometric ----")
angles = [Link]([0, [Link]/2]) # 0 and 90 degrees in radians
print("sin:", [Link](angles)) # [0. 1.]
print("cos:", [Link](angles)) # [1. 0.]
print("\n---- Exponential & Logarithm ----")
print("exp([1,2]) =", [Link]([1,2])) # [ 2.718 7.389]
print("log([1, e]) =", [Link]([1, np.e])) # [0. 1.]
print("\n---- Rounding ----")
nums = [Link]([2.6, -2.6])
print("around:", [Link](nums)) # [ 3. -3.]
print("floor:", [Link](nums)) # [ 2. -3.]
print("ceil:", [Link](nums)) # [ 3. -2.]
OUTPUT:
---- Arithmetic ----
a + b = [3 7]
a * b = [ 2 12]
---- Trigonometric ----
sin: [0. 1.]
cos: [1. 0.]
---- Exponential & Logarithm ----
exp([1,2]) = [2.71828183 7.3890561 ]
log([1, e]) = [0. 1.]
---- Rounding ----
around: [ 3. -3.]
floor: [ 2. -3.]
ceil: [ 3. -2.]
Example Program: Arithmetic and Trigonometric Functions, Exponential,
Logarithmic, and Rounding Functions
import numpy as np
# Sample arrays
a = [Link]([10, 20, 30])
b = [Link]([2, 5, 10])
print("---- Arithmetic Functions ----")
Fundamentals of Python Programming for Beginners 283
Python Packages
print("Add:", [Link](a, b)) # [12 25 40]
print("Subtract:", [Link](a, b)) # [ 8 15 20]
print("Multiply:", [Link](a, b)) # [ 20 100 300]
print("Divide:", [Link](a, b)) # [5. 4. 3.]
print("Power:", [Link]([2, 3, 4], 2)) # [ 4 9 16]
print("Mod:", [Link](a, 7)) # [3 6 2]
print("\n---- Trigonometric Functions ----")
angles = [Link]([0, 30, 45, 90])
print("Sine:", [Link](np.deg2rad(angles))) # [0. 0.5 0.7071 1.]
print("Cosine:", [Link](np.deg2rad(angles))) # [1. 0.866 0.7071 0.]
print("Tangent:", [Link](np.deg2rad([0, 45])))# [0. 1.]
print("Arcsin:", [Link]([0, 1])) # [0. 1.5708]
print("Deg → Rad:", np.deg2rad([180])) # [3.1416]
print("Rad → Deg:", np.rad2deg([[Link]])) # [180.]
print("\n---- Exponential & Logarithmic Functions ----")
x = [Link]([1, 2, 4, 8])
print("Exponential:", [Link]([1, 2])) # [2.718 7.389]
print("Natural log:", [Link]([1, np.e, np.e**2])) # [0. 1. 2.]
print("Log base 10:", np.log10([1, 10, 100])) # [0. 1. 2.]
print("Log base 2:", np.log2(x)) # [0. 1. 2. 3.]
print("\n---- Rounding Functions ----")
nums = [Link]([1.234, 2.567, -3.789])
print("Around (2 decimals):", [Link](nums, 2)) # [ 1.23 2.57 -3.79]
print("Floor:", [Link](nums)) # [ 1. 2. -4.]
print("Ceil:", [Link](nums)) # [ 2. 3. -3.]
OUTPUT:
---- Arithmetic Functions ----
Add: [12 25 40]
Subtract: [ 8 15 20]
Multiply: [ 20 100 300]
Divide: [5. 4. 3.]
Power: [ 4 9 16]
Mod: [3 6 2]
---- Trigonometric Functions ----
Sine: [0. 0.5 0.7071 1. ]
Cosine: [1. 0.866 0.7071 0. ]
Tangent: [0. 1.]
Arcsin: [0. 1.5708]
Deg → Rad: [3.1416]
Rad → Deg: [180.]
---- Exponential & Logarithmic Functions ----
Exponential: [2.71828183 7.3890561 ]
Natural log: [0. 1. 2.]
Log base 10: [0. 1. 2.]
Log base 2: [0. 1. 2. 3.]
---- Rounding Functions ----
Around (2 decimals): [ 1.23 2.57 -3.79]
Floor: [ 1. 2. -4.]
Ceil: [ 2. 3. -3.]
Fundamentals of Python Programming for Beginners 284
Python Packages
5.6 pandas packages
When we create a DataFrame (a 2D table of rows and columns), pandas provide several
built-in functions to help you inspect or understand the structure, data types, and
content of our data before starting analysis.
Array Inspection in pandas are classified into three groups:
• Structural Inspection
• Data Type & Content Inspection
• Missing Data Inspection
Structural Inspection
These methods tell us about the shape, size, and labels of the DataFrame.
Method Syntax Example Output Explanation
Dimensions of the
shape [Link] [Link] (rows, columns)
DataFrame
Number of
dimensions (1 for
ndim [Link] [Link] 2
Series, 2 for
DataFrame)
Total number of
size [Link] [Link] 12 elements (rows ×
columns)
Displays row
index [Link] [Link] RangeIndex(0, 4)
index/labels
Displays column
columns [Link] [Link] Index([...])
labels
Numpy array
values [Link] [Link] array([...]) representation of
the data
Data Type & Content Inspection
These methods help to check data types, summary, and preview of the data.
Method Syntax Example Output Explanation
int64, float64, Shows datatype of
dtypes [Link] [Link]
object each column
Gives index range,
Summary of non-null counts,
info() [Link]() [Link]()
DataFrame column dtypes,
memory usage
Displays first n
head(n) [Link](n) [Link](3) First 3 rows
rows
Displays last n
tail(n) [Link](n) [Link](2) Last 2 rows
rows
Gives mean, std,
describe() [Link]() [Link]() Summary stats min, max, etc. for
numeric columns
Missing Data Inspection
These methods help identify and handle missing values (NaN/None).
Method Syntax Examplea Output Explanation
DataFrame of Shows True where
isnull() [Link]() [Link]()
True/False data is missing
DataFrame of Shows True where
notnull() [Link]() [Link]()
True/False data is not missing
isna() [Link]() [Link]() Same as isnull() Alias for isnull()
notna() [Link]() [Link]() Same as notnull() Alias for notnull()
Fundamentals of Python Programming for Beginners 285
Python Packages
NOTE:
• Shape, ndim, size → Structure of DataFrame
• Columns, index, dtypes, values → Metadata & types
• Head, tail → Peek at data
• Info, describe → Summary of data
• isna / notna → Missing values check
Example Program: Student Data covering Array Inspection built-in functions of
packages NumPy
import pandas as pd
# Sample DataFrame
data = {
"Name": ["Rahul", "Bharath", "Manoj", "Rakesh"],
"Age": [35, 38, 36, 35],
"Marks": [85.5, 91.0, 78.0, None]
}
df = [Link](data)
print("Shape:", [Link])
print("Dimensions:", [Link])
print("Size:", [Link])
print("\nData Types:\n", [Link])
print("\nIndex:", [Link])
print("Columns:", [Link])
print("\nValues:\n", [Link])
print("\nHead:\n", [Link](2))
print("\nTail:\n", [Link](2))
print("\nInfo:"); print([Link]())
print("\nDescribe:\n", [Link]())
print("\nMissing values:\n", [Link]())
print("\nNot Missing values:\n", [Link]())
OUTPUT:
Shape: (4, 3)
Dimensions: 2
Size: 12
Data Types:
Name object
Age int64
Marks float64
dtype: object
Index: RangeIndex(start=0, stop=4, step=1)
Columns: Index(['Name', 'Age', 'Marks'], dtype='object')
Values:
[['Rahul' 35 85.5]
['Bharath' 38 91.0]
['Manoj' 36 78.0]
['Rakesh' 35 nan]]
Head:
Name Age Marks
0 Rahul 35 85.5
Fundamentals of Python Programming for Beginners 286
Python Packages
1 Bharath 38 91.0
Tail:
Name Age Marks
2 Manoj 36 78.0
3 Rakesh 35 NaN
Info:
<class '[Link]'>
RangeIndex: 4 entries, 0 to 3
Data columns (total 3 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Name 4 non-null object
1 Age 4 non-null int64
2 Marks 3 non-null float64
dtypes: float64(1), int64(1), object(1)
memory usage: 228.0+ bytes
None
Describe:
Age Marks
count 4.000000 3.000000
mean 36.000000 84.833333
std 1.414214 6.658328
min 35.000000 78.000000
max 38.000000 91.000000
Missing values:
Name Age Marks
0 False False False
1 False False False
2 False False False
3 False False True
Not Missing values:
Name Age Marks
0 True True True
1 True True True
2 True True True
3 True True False
Example Program: Product Data covering Array Inspection built-in functions of
packages NumPy
import pandas as pd
# Sample DataFrame
products = {
"Product": ["Pen", "Pencil", "Eraser", "Notebook", "Scale"],
"Price": [10, 5, 3, 50, 7],
"Stock": [100, 200, None, 50, 80]
}
df2 = [Link](products)
print("Shape:", [Link])
print("Dimensions:", [Link])
Fundamentals of Python Programming for Beginners 287
Python Packages
print("Size:", [Link])
print("\nData Types:\n", [Link])
print("\nIndex:", [Link])
print("Columns:", [Link])
print("\nValues:\n", [Link])
print("\nHead:\n", [Link](3))
print("\nTail:\n", [Link](2))
print("\nInfo:"); print([Link]())
print("\nDescribe:\n", [Link]())
print("\nMissing values:\n", [Link]())
print("\nNot Missing values:\n", [Link]())
OUTPUT:
Shape: (5, 3)
Dimensions: 2
Size: 15
Data Types:
Product object
Price int64
Stock float64
dtype: object
Index: RangeIndex(start=0, stop=5, step=1)
Columns: Index(['Product', 'Price', 'Stock'], dtype='object')
Values:
[['Pen' 10 100.0]
['Pencil' 5 200.0]
['Eraser' 3 nan]
['Notebook' 50 50.0]
['Scale' 7 80.0]]
Head:
Product Price Stock
0 Pen 10 100.0
1 Pencil 5 200.0
2 Eraser 3 NaN
Tail:
Product Price Stock
3 Notebook 50 50.0
4 Scale 7 80.0
Info:
<class '[Link]'>
RangeIndex: 5 entries, 0 to 4
Data columns (total 3 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Product 5 non-null object
1 Price 5 non-null int64
2 Stock 4 non-null float64
dtypes: float64(1), int64(1), object(1)
Describe:
Price Stock
Fundamentals of Python Programming for Beginners 288
Python Packages
count 5.00000 4.000000
mean 15.00000 107.500000
std 19.62142 70.710678
min 3.00000 50.000000
max 50.00000 200.000000
Missing values:
Product Price Stock
0 False False False
1 False False False
2 False False True
3 False False False
4 False False False
Example Program: Fruits and Prices covering Array Inspection built-in functions of
packages NumPy
import pandas as pd
# Sample DataFrame
data = {
'Fruit': ['Apple', 'Banana', 'Mango'],
'Price': [120, 60, None],
'Category': ['Premium', 'Regular', 'Seasonal']
}
df = [Link](data)
# Inspection
print("Shape:", [Link])
print("Dimensions:", [Link])
print("Size:", [Link])
print("Columns:", [Link])
print("Data Types:\n", [Link])
print("Missing Values:\n", [Link]())
print("Info:")
[Link]()
OUTPUT:
Shape: (3, 3)
Dimensions: 2
Size: 9
Columns: Index(['Fruit', 'Price', 'Category'], dtype='object')
Data Types:
Fruit object
Price float64
Category object
dtype: object
Missing Values:
Fruit Price Category
0 False False False
1 False False False
2 False True False
Info:
Fundamentals of Python Programming for Beginners 289
Python Packages
<class '[Link]'>
RangeIndex: 3 entries, 0 to 2
Data columns (total 3 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Fruit 3 non-null object
1 Price 2 non-null float64
2 Category 3 non-null object
dtypes: float64(1), object(2)
memory usage: 200.0+ bytes
5.7 GUI PROGRAMMING WITH Tkinter
5.7.1 INTRODUCTION TO Tkinter
• A GUI (Graphical User Interface) allows users to interact with software using
windows, buttons, menus, forms, etc., instead of typing commands.
• Tkinter is Python’s standard library for GUI (Graphical User Interface)
programming.
• It comes bundled with Python (no need for extra installation in most cases).
• It is built on top of the Tcl/Tk toolkit. It is cross-platform: works on Windows,
macOS, and Linux.
• Tkinter allows developers to create windows, buttons, labels, text boxes, menus,
and many other GUI elements.
• Tkinter comes bundled with Python (no separate installation needed).
• It is simple for beginners yet powerful enough for academic and small professional
projects.
ADVANTAGES OF Tkinter
• Beginner-friendly: Easy to learn and use.
• Cross-platform: Works on Windows, Mac, and Linux.
• Widget-based: Provides elements like buttons, labels, text boxes, menus, etc.
• Event-driven: GUI runs based on user actions (click, type, select).
• No external installation required: Comes pre-installed with Python.
• Simple syntax: Enables rapid development.
• Ideal for prototyping and small desktop applications: Quick way to build
functional GUIs.
Tkinter AND PYTHON PROGRAMMING
Python is a versatile, high-level programming language widely used in software
development and education. Tkinter is its standard GUI library, enabling developers to
build interactive desktop applications with minimal code. Together, Python and Tkinter
offer a powerful platform for creating user-friendly interfaces, ideal for teaching event-
driven programming and rapid application development.
Fundamentals of Python Programming for Beginners 290
Python Packages
Tkinter Basic Syntax
import tkinter as tk # 1. Import Tkinter
root = [Link]() # 2. Create the main window (root)
[Link]("Window Title") # 3. Optional: set window title
widget = [Link](root, options)# 4. Create and configure widgets (Label,
Button, etc.)
[Link]() # 5. Place (layout) widgets in the window
[Link]() # 6. Start the event loop
Explanation
1. Import Tkinter: (import tkinter as tk)
• tkinter is the Python library for GUI programming.
• as tk is an alias to make code shorter (so we write [Link] instead of
[Link]).
2. Create Main Window:
root = [Link]()
• Tk() initializes the main application window.
• The variable root represents the window (you can name it anything).
3. Set Window Title (Optional):
[Link]("My App")
You can specify what appears in the title bar.
4. Add Widgets:
widget = [Link](root, options)
[Link]()
Widgets are GUI elements like Label, Button, Entry, Text, Menu.
Example:
label = [Link](root, text="Hello Tkinter")
button = [Link](root, text="Click Me")
pack(), grid(), or place() methods are used to arrange widgets inside the
window.
5. Arrange Widgets:
You need to tell Tkinter where to put widgets uing layout managers
like .pack(), .grid(), or .place().
Example:
[Link]()
[Link]()
6. Start the Main Loop:
[Link]()
• This keeps the window open and waits for user actions (like button clicks, typing,
etc.).
• Without this line, the GUI will close immediately after opening.
Fundamentals of Python Programming for Beginners 291
Python Packages
5.7.2 Tk Widgets (Tkinter Widgets)
In Tkinter, widgets are the building blocks of a GUI application. They are small elements
like buttons, text boxes, labels, menus, etc., that allow users to interact with the program.
HOW DO WIDGETS WORK?
• Each widget is an object (instance of a class).
• We create a widget (like a Button or Label).
• Then we place it inside the main window using geometry managers (pack(),
grid(), place()).
• Widgets can be customized (size, color, text, font, etc.).
• Widgets respond to user actions (clicking, typing, selecting, etc.).
Table: TYPES OF WIDGETS
Type
Widget Purpose Syntax Explanation
Used to show text or
Display static text or
Label Label(master, options) images that cannot be
images
edited by the user.
Basic Widgets
Creates a clickable Triggers an action or
Button Button(master, options)
button command on click.
Single-line text Allows the user to enter
Entry Entry(master, options)
input or edit text in one line.
Container for other Used to group and
Frame Frame(master, options)
widgets organize other widgets.
Checkbox for Checkbutton(master, Used for on/off or
Checkbutton
multiple options options) multiple selections.
Used when only one
Radio button for one Radiobutton(master,
Radiobutton option among many can
option options)
be selected.
Selection Widgets
Allows the user to select
Displays a list of
Listbox Listbox(master, options) one or more items from
items
a list.
Combobox [Link](master, Provides a dropdown list
Dropdown menu
(ttk) options) with text entry.
Numeric input with Lets the user select from
Spinbox Spinbox(master, options)
arrows a range of numbers.
Allows selecting values
Slider for numeric
Scale Scale(master, options) within a range using a
values
slider.
Allows editing of multi-
Text Multi-line text input Text(master, options)
line text.
Used for shapes, images,
Canvas Drawing area Canvas(master, options)
Display Widgets
or custom drawings.
Displays text Similar to Label but
Message Message(master, options)
messages supports longer texts.
Progressbar [Link](master, Visual representation of
Shows task progress
(ttk) options) task progress.
Displays [Link](master, Used for tables, file
Treeview (ttk)
hierarchical data options) browsers, etc.
Fundamentals of Python Programming for Beginners 292
Python Packages
Used to build menus like
Menu Creates menus Menu(master, options)
Menu Widgets
File, Edit, etc.
Container & Button with Menubutton(master, Displays a menu when
Menubutton
dropdown menu options) clicked.
Creates a new Opens additional
Toplevel Toplevel(master, options)
window windows.
Adds scroll bar to Scrollbar(master, Provides scrolling for
Scrollbar
Scrollbar
Widgets
widgets options) Text, Listbox, Canvas, etc.
Treeview Adds scrollbar to Scrollbar(master, Enables scrolling inside
Scrollbar Treeview options) Treeview.
Widgets
Dialog
[Link]("T Shows alerts, warnings,
Messagebox Popup dialogs
itle", "Message") or confirmations.
GEOMETRY MANAGERS
Manager Syntax Purpose Simple Explanation
Places widgets one after another
Arranges widgets in blocks in a sequence. Useful for simple
pack() [Link](options)
(top, bottom, left, right). layouts. Options like side, fill,
expand control placement.
Divides the window into rows and
Arranges widgets in a table-
[Link](row=r, columns. Widgets can be
grid() like structure (rows &
column=c, options) positioned at specific cells. Best for
columns).
forms or structured layouts.
Provides exact control over
[Link](x=val, Places widgets at specific position using x & y (pixels) or
place()
y=val) coordinates. relative values (relx, rely). Best for
custom designs.
Note:
• Use pack() → for simple stacking (quick demos).
• Use grid() → for structured forms (login, calculator).
• Use place() → when you need exact positions (games, designs).
Tkinter Syntax in detail
import tkinter as tk
from tkinter import messagebox
# Create main window first
window = [Link]()
[Link]("Tkinter Syntax Demo")
[Link]("400x300") # Set window size
# Special variable example (must come AFTER window)
name_var = [Link]()
# Event handler function
def on_click():
[Link]("Greeting", f"Hello, {name_var.get()}!")
# Label widget
Fundamentals of Python Programming for Beginners 293
Python Packages
label = [Link](window, text="Enter Your Name:", font=("Arial", 12))
[Link](pady=10)
# Entry widget
entry = [Link](window, textvariable=name_var, width=30)
[Link](pady=5)
# Button widget
button = [Link](window, text="Submit", command=on_click)
[Link](pady=10)
# Frame for grid layout
frame = [Link](window)
[Link](pady=20)
grid_label = [Link](frame, text="Grid Example", font=("Arial", 10))
grid_label.grid(row=0, column=0, padx=10, pady=10)
# Place layout example
place_label = [Link](window, text="Placed Label")
place_label.place(x=250, y=250)
# Start the event loop
[Link]()
Output:
A window titled “Tkinter Syntax Demo” opens.
You’ll see:
A label: “Enter Your Name:”
An entry box
A “Submit” button
A frame with the text “Grid Example”
A placed label at bottom-right: “Placed
Label”
If you type a name (e.g., Rahul) and click Submit, a popup appears:
Greeting
Hello, Rahul!
Fundamentals of Python Programming for Beginners 294
Python Packages
Explanation
Component Syntax Explanation
Imports the Tkinter module with alias tk
Import Tkinter import tkinter as tk
for easy usage.
window= [Link]()
Create main window Create main window using tkinter
Event Handler Defines a function that runs when the
def on_click():
Function button is clicked.
Displays a popup greeting with the user’s
Show Info Popup [Link]("Greeting",
entered name (retrieved using
with Name f"Hello, {name_var.get()}!")
name_var.get()).
Creates a StringVar to hold dynamic text
Special Variable name_var = [Link]()
input from the Entry widget.
Create Main
window = [Link]() Initializes the main application window.
Window
Set Window [Link]("Tkinter Syntax
Sets the title bar text of the window.
Title Demo")
Set Window Size [Link]("400x300") Defines the window size (400px × 300px).
label = [Link](window,
Creates a label with text “Enter Your
Label Widget text="Enter Your Name:",
Name:” in Arial font size 12.
font=("Arial", 12))
Pack Layout Places the label in the window with vertical
[Link](pady=10)
(Label) padding of 10px.
entry = [Link](window, Creates a single-line text box linked to
Entry Widget
textvariable=name_var, width=30) name_var for user input.
Pack Layout Positions the entry box with vertical
[Link](pady=5)
(Entry) padding of 5px.
button = [Link](window, Creates a button labeled “Submit” that
Button Widget
text="Submit", command=on_click) triggers on_click when clicked.
Pack Layout Places the button in the window with
[Link](pady=10)
(Button) vertical padding of 10px.
Creates a frame (container) inside the main
Frame Widget frame = [Link](window)
window for grouping widgets.
Pack Layout Positions the frame with vertical padding
[Link](pady=20)
(Frame) of 20px.
grid_label = [Link](frame,
Label with Grid Creates a label inside the frame with text
text="Grid Example", font=("Arial",
(inside Frame) “Grid Example”.
10))
grid_label.grid(row=0, column=0, Places the label at row=0, column=0 inside
Grid Layout
padx=10, pady=10) the frame using grid layout.
place_label = [Link](window,
Label with Place Creates a label with text “Placed Label”.
text="Placed Label")
Positions the label at absolute coordinates
Place Layout place_label.place(x=250, y=250)
(250, 250) in the window.
Starts the Tkinter event loop to keep the
Event Loop [Link]()
window running and responsive.
Fundamentals of Python Programming for Beginners 295
Python Packages
Example: Basic Window
import tkinter as tk # Import Tkinter library
# Create main window
window = [Link]() # Initialize the window
[Link]("Basic Window") # Set window title
[Link]("300x200") # Set window size
# Run the GUI loop
[Link]()
Output:
Example: Label and Button
import tkinter as tk # Import Tkinter library
# Function to change label text
def say_hello():
[Link](text="Hello, Tkinter!")
window = [Link]() # Create main window
[Link]("Label and Button")
# Create label
label = [Link](window, text="Click the button", font=("Arial", 12))
[Link](pady=20) # Place label with padding
# Create button
button = [Link](window, text="Click Me", command=say_hello)
[Link]() # Place button below label
# Run the GUI loop
[Link]()
Fundamentals of Python Programming for Beginners 296
Python Packages
Output:
Example: Entry Widget (User Input)
import tkinter as tk
# Function to display entered name
def show_name():
name = [Link]() # Get input text from entry
[Link](text=f"Hello, {name}!") # Update label
window = [Link]() # Create window
[Link]("Entry Example")
# Entry widget for user input
entry = [Link](window, width=30)
[Link](pady=10)
# Button to trigger function
button = [Link](window, text="Submit", command=show_name)
[Link]()
# Label to display result
label = [Link](window, text="", font=("Arial", 12))
[Link](pady=20)
# Run the GUI loop
[Link]()
Output:
Fundamentals of Python Programming for Beginners 297
Python Packages
Example: Message box
import tkinter as tk
from tkinter import messagebox # Import messagebox for popups
# Function to show messagebox
def show_message():
[Link]("Greeting", "Welcome to Tkinter!")
window = [Link]() # Create main window
[Link]("Messagebox Example")
# Button to show popup
button = [Link](window, text="Show Message", command=show_message)
[Link](pady=50)
# Run the GUI loop
[Link]()
Output:
Example: Calculator (Addition Only)
import tkinter as tk
# Function to add numbers
def add_numbers():
num1 = int([Link]()) # Get first number
num2 = int([Link]()) # Get second number
result_label.config(text=f"Result: {num1 + num2}") # Show sum
window = [Link]() # Create window
[Link]("Simple Calculator")
# Entry for first number
entry1 = [Link](window, width=10)
[Link](pady=5)
# Entry for second number
entry2 = [Link](window, width=10)
[Link](pady=5)
# Button to add numbers
button = [Link](window, text="Add", command=add_numbers)
[Link](pady=5)
# Label to display result
Fundamentals of Python Programming for Beginners 298
Python Packages
result_label = [Link](window, text="Result: ")
result_label.pack(pady=10)
# Run the GUI loop
[Link]()
Output:
Example: Calculator with Add, Subtract, Multiply & Divide operations
import tkinter as tk # Import Tkinter library
# Function to add numbers
def add_numbers():
num1 = float([Link]()) # Get first number
num2 = float([Link]()) # Get second number
result_label.config(text=f"Result: {num1 + num2}") # Display sum
# Function to subtract numbers
def subtract_numbers():
num1 = float([Link]())
num2 = float([Link]())
result_label.config(text=f"Result: {num1 - num2}") # Display difference
# Function to multiply numbers
def multiply_numbers():
num1 = float([Link]())
num2 = float([Link]())
result_label.config(text=f"Result: {num1 * num2}") # Display product
# Function to divide numbers
def divide_numbers():
num1 = float([Link]())
num2 = float([Link]())
if num2 != 0: # Check division by zero
result_label.config(text=f"Result: {num1 / num2}") # Display quotient
else:
result_label.config(text="Error: Division by Zero")
# Create main window
window = [Link]()
[Link]("Simple Calculator") # Title of the window
# Entry for first number
Fundamentals of Python Programming for Beginners 299
Python Packages
entry1 = [Link](window, width=15)
[Link](pady=5)
# Entry for second number
entry2 = [Link](window, width=15)
[Link](pady=5)
# Buttons for operations
add_button = [Link](window, text="Add", command=add_numbers)
add_button.pack(pady=2)
sub_button = [Link](window, text="Subtract", command=subtract_numbers)
sub_button.pack(pady=2)
mul_button = [Link](window, text="Multiply", command=multiply_numbers)
mul_button.pack(pady=2)
div_button = [Link](window, text="Divide", command=divide_numbers)
div_button.pack(pady=2)
# Label to show the result
result_label = [Link](window, text="Result: ", font=("Arial", 12))
result_label.pack(pady=10)
# Run the GUI loop
[Link]()
Output:
Fundamentals of Python Programming for Beginners 300
Python Packages
Example: Temperature Converter (Celsius ↔ Fahrenheit)
import tkinter as tk
# Convert Celsius to Fahrenheit
def convert():
celsius = float([Link]())
fahrenheit = (celsius * 9/5) + 32
result_label.config(text=f"Fahrenheit: {fahrenheit:.2f}")
# Main window
window = [Link]()
[Link]("Temperature Converter")
# Entry for Celsius
entry = [Link](window, width=15)
[Link](pady=5)
# Button to convert
convert_button = [Link](window, text="Convert to Fahrenheit",
command=convert)
convert_button.pack(pady=5)
# Result label
result_label = [Link](window, text="Fahrenheit: ")
result_label.pack(pady=5)
[Link]()
Output:
Example: Simple To-Do List
import tkinter as tk
# Add task to listbox
def add_task():
task = [Link]()
if task != "":
[Link]([Link], task)
[Link](0, [Link])
# Main window
window = [Link]()
[Link]("To-Do List")
Fundamentals of Python Programming for Beginners 301
Python Packages
# Entry box
entry = [Link](window, width=30)
[Link](pady=5)
# Button to add task
add_button = [Link](window, text="Add Task", command=add_task)
add_button.pack(pady=5)
# Listbox to show tasks
listbox = [Link](window, width=40, height=10)
[Link](pady=5)
[Link]()
Output:
Example: Digital Clock
import tkinter as tk
import time
# Update time every second
def update_time():
current_time = [Link]("%H:%M:%S")
[Link](text=current_time)
[Link](1000, update_time) # Refresh every 1 sec
# Main window
window = [Link]()
[Link]("Digital Clock")
# Label to display time
label = [Link](window, font=("Arial", 40), fg="blue")
[Link](pady=20)
# Start clock
update_time()
[Link]()
Fundamentals of Python Programming for Beginners 302
Python Packages
Output:
Example: Random Password Generator
import tkinter as tk
import random
import string
# Generate password
def generate_password():
length = 8
characters = string.ascii_letters + [Link] + [Link]
password = "".join([Link](characters) for i in range(length))
result_label.config(text=f"Password: {password}")
# Main window
window = [Link]()
[Link]("Password Generator")
# Button
generate_button = [Link](window, text="Generate Password",
command=generate_password)
generate_button.pack(pady=10)
# Result
result_label = [Link](window, text="Password: ")
result_label.pack(pady=10)
[Link]()
Output:
Fundamentals of Python Programming for Beginners 303
Python Packages
Example: Currency Converter (Rupees ↔ Dollars)
import tkinter as tk
# Convert INR to USD
def convert():
inr = float([Link]())
usd = inr / 83 # Approx rate
result_label.config(text=f"USD: {usd:.2f}")
# Main window
window = [Link]()
[Link]("Currency Converter")
# Entry for INR
entry = [Link](window, width=15)
[Link](pady=5)
# Button
convert_button = [Link](window, text="Convert to USD", command=convert)
convert_button.pack(pady=5)
# Result
result_label = [Link](window, text="USD: ")
result_label.pack(pady=5)
[Link]()
Output:
Example: Trigonometric Calculator (Sin, Cos, Tan)
import tkinter as tk
import math
# Function to calculate sin, cos, tan
def calculate():
try:
angle_deg = float([Link]()) # Get input from user in degrees
angle_rad = [Link](angle_deg) # Convert degree → radians
sin_val = [Link](angle_rad) # Calculate sine
cos_val = [Link](angle_rad) # Calculate cosine
tan_val = [Link](angle_rad) # Calculate tangent
Fundamentals of Python Programming for Beginners 304
Python Packages
result_label.config(text=f"Sin: {sin_val:.4f}\nCos: {cos_val:.4f}\nTan:
{tan_val:.4f}")
except ValueError:
result_label.config(text="Please enter a valid number!")
# Create main window
window = [Link]()
[Link]("Trigonometric Calculator")
# Label
label = [Link](window, text="Enter Angle in Degrees:", font=("Arial", 12))
[Link](pady=5)
# Entry box
entry = [Link](window, width=20)
[Link](pady=5)
# Button
button = [Link](window, text="Calculate", command=calculate)
[Link](pady=5)
# Result
result_label = [Link](window, text="", font=("Arial", 12))
result_label.pack(pady=10)
[Link]()
Output:
Explanation:
• User enters an angle in degrees (e.g., 30, 45, 60, 90).
• Program converts it into radians (since Python math functions use radians).
• Calculates sin, cos, tan using [Link](), [Link](), [Link]().
• Displays results up to 4 decimal places.
ADVANTAGES OF Tkinter WIDGETS
1. Easy to Use
• Tkinter widgets are simple and beginner-friendly.
• They can be created and customized quickly using Python.
Fundamentals of Python Programming for Beginners 305
Python Packages
2. Interactive GUI
• Widgets allow users to interact with the program (buttons, text input,
checkboxes).
• This makes applications more user-friendly compared to text-only programs.
3. Wide Variety
• Tkinter provides many widgets: labels, buttons, entry fields, listboxes, canvas,
menus, dialogs, and more.
• Covers most needs for desktop GUI applications.
4. Customizable
• Widgets can be styled and configured (text, font, color, size, border, etc.).
• Supports building attractive and functional interfaces.
5. Event Handling
• Widgets can respond to user actions like clicks, typing, or selection.
• Supports building dynamic and interactive applications.
6. Lightweight & Built-in
• Tkinter comes pre-installed with Python, so no additional installation is
required.
• Runs on Windows, Mac, and Linux without extra dependencies.
7. Organized Layouts
• Widgets can be arranged neatly using geometry managers (pack, grid, place).
• Supports building structured and easy-to-navigate interfaces.
8. Extendable
• Widgets can be combined to create complex GUIs like forms, games,
calculators, or editors.
• Works well with additional libraries like ttk for modern themed widgets.
5.8 PYTHON IDE (Integrated Development Environment)
• An IDE is a software application that provides tools to write, edit, debug, and
run Python programs efficiently.
• It combines a code editor, debugger, and interpreter in one interface.
Fundamentals of Python Programming for Beginners 306
Python Packages
5.8.1 CLASSIFICATION OF PYTHON IDEs
Python IDEs can be classified into four main types depending on their features, purpose,
and target users:
Table: Classification of Python IDEs
Type IDE Description / Features
Default IDE, simple interface, suitable for beginners and small
IDLE
programs.
Very easy for beginners, step-by-step debugger, simple
Beginner- Thonny
interface.
Friendly /
Focused on teaching programming and object-oriented
Educational IDEs BlueJ
concepts.
• Purpose: Designed for new learners to practice Python programming.
• Features: Simple interface, easy to use, basic debugging, minimal setup.
Advanced debugging, large project support, Git integration,
PyCharm
refactoring.
Professional development, intelligent code analysis,
Wing IDE
productivity features.
Komodo IDE Supports multiple languages, debugging, and version control.
Good for PyQt applications, beginner-friendly but advanced
Eric Python IDE
enough for projects.
Professional /
PyDev Python plugin for Eclipse, supports professional development
Full-Featured
(Eclipse Plugin) and Java integration.
IDEs
NetBeans
Full-featured IDE, suitable for large projects with multiple
(with Python
languages.
plugin)
• Purpose: For professional development, large projects, or commercial
applications.
• Features: Advanced debugging, project management, Git/version control, code
refactoring, plugins support.
Lightweight editor, supports extensions, flexible for multiple
VS Code
languages.
Atom Hackable and customizable text editor with Python packages.
Lightweight / Sublime Text Fast, lightweight editor with Python plugin support.
Text Editor Geany Lightweight, cross-platform, suitable for small projects.
Based IDEs • Purpose: Flexible and fast coding, often used by students or developers who
prefer minimal interfaces.
• Features: Lightweight, customizable with plugins/extensions, supports multiple
languages.
Scientific IDE, integrates with data analysis and machine
Spyder
learning libraries.
Data Science / Interactive notebooks, supports code, text, visualizations;
Jupyter Notebook
Interactive ideal for data science and learning.
Coding IDEs • Purpose: Designed for data analysis, visualization, and scientific computing.
• Features: Supports interactive code execution, inline plots, notebooks, and
integration with scientific libraries.
Fundamentals of Python Programming for Beginners 307
Python Packages
PYTHON IDEs SYNTAX AND HOW TO LAUNCH
• An IDE (Integrated Development Environment) is a software tool used to write,
run, and debug Python programs easily.
• Each IDE can be opened (launched) in different ways depending on how it is
installed.
Table: Python IDEs Syntax and how to launch
Type IDE How to Launch / Syntax Features
idle (Windows: Start Menu → Default IDE; simple editor
IDLE
IDLE) and console.
Beginner-Friendly Launch from Start Menu / Beginner-friendly, step-by-
Thonny
/ Educational thonny in terminal step debugger.
Launch from Start Menu / Mainly for teaching object-
BlueJ
Installed application oriented programming.
Launch application or Advanced debugging, project
PyCharm
pycharm (if added to PATH) management, Git integration.
Launch from Start Menu / Professional IDE with
Wing IDE
Installed app intelligent code analysis.
Supports multiple languages,
Komodo IDE Launch application
Professional / version control.
Full-Featured Launch from Start Menu /
Eric Python IDE Good for PyQt development.
Terminal
PyDev (Eclipse Python plugin inside Eclipse
Eclipse → PyDev perspective
Plugin) IDE.
NetBeans (with NetBeans → Open Python Full-featured IDE, multi-
Python plugin) project language support.
code in terminal / Launch Requires Python extension
VS Code
from app for IDE features.
Install Python packages for
Atom Launch application
Lightweight / full IDE support.
Text Editor Based Can install Python plugins for
Sublime Text Launch application
IDE functionality.
Lightweight editor, supports
Geany Launch application
Python scripting.
Launch from Anaconda Scientific IDE, integrates with
Spyder
Data Science / Navigator or terminal: spyder Python libraries.
Interactive Coding Jupyter Opens browser interface for
Terminal: jupyter notebook
Notebook interactive notebooks.
BASIC STEPS TO USE A PYTHON IDE
1. Install/Launch IDE (if not IDLE, install PyCharm or VS Code).
2. Create a new Python file (.py).
3. Write Python code in the editor.
4. Run the code using Run/Execute button or shortcut (e.g., F5).
5. View output in console/terminal.
Fundamentals of Python Programming for Beginners 308
Python Packages
BENEFITS OF USING AN IDE
1. All-in-One Environment
• Combines editor, debugger, terminal, and project management in one place.
• No need to switch between multiple tools.
2. Easy Code Writing
• Provides syntax highlighting (different colors for keywords, variables, strings).
• Auto-completion suggests functions, variables, and libraries while typing.
3. Debugging Support
• Helps find and fix errors with breakpoints and step-by-step execution.
• Shows where the error occurred with clear messages.
4. Code Management
• Organizes large projects with multiple files easily.
• Supports version control (Git, SVN).
5. Productivity Boost
• Built-in shortcuts and templates speed up coding.
• Some IDEs have intelligent code analysis (suggest better ways to write code).
6. Integrated Testing
• Many IDEs support unit testing and test frameworks directly.
• Useful for professional and large-scale projects.
7. Cross-Platform Development
• Most IDEs work on Windows, macOS, and Linux.
• Makes collaboration easier across different systems.
8. Specialized Tools
• Data Science IDEs (like Spyder, Jupyter) support plots, graphs, and interactive
coding.
• Web development IDEs (like VS Code, PyCharm) support frameworks (Django,
Flask).
Note: IDEs that Support Multiple Languages
IDE Languages Supported
VS Code Python, JS, C++, Java, HTML, etc.
Eclipse Java, C++, Python (via plugins)
IntelliJ IDEA Java, Kotlin, Python, JS
PyCharm Python, HTML, JS
JupyterLab Python, R, Julia
Replit Python, JS, C++, Java, Bash
Fundamentals of Python Programming for Beginners 309
Python Packages
Example Programs
Example Python Programs – Unit-5 (Packages)
Q1. Matplotlib – Simple line plot
import [Link] as plt
x = [0, 1, 2, 3, 4]
y = [0, 1, 4, 9, 16]
[Link](x, y)
[Link]("y = x^2")
[Link]("x")
[Link]("y")
[Link]()
Output:
Explanation: plot() draws a basic line; labels/title add context.
Q2. Matplotlib – Line plot with legend & grid
import [Link] as plt
x = [1,2,3,4,5]
y1 = [1,4,9,16,25]
y2 = [1,2,3,4,5]
[Link](x, y1, label="Squares")
[Link](x, y2, label="Line")
[Link]("Two Lines")
[Link]("x"); [Link]("y")
[Link](); [Link](True)
[Link]()
Fundamentals of Python Programming for Beginners 310
Python Packages
Output:
Explanation: legend() identifies each series; grid(True) improves readability.
Q3. Matplotlib – Bar chart
import [Link] as plt
subjects = ["Math","Physics","Chem"]
marks = [85, 90, 78]
[Link](subjects, marks)
[Link]("Student Marks"); [Link]("Subject"); [Link]("Marks")
[Link]()
Output: Vertical bars for the three subjects.
Explanation: bar() maps categories to bar heights.
Q4. Matplotlib – Horizontal bar chart
import [Link] as plt
cats = ["A","B","C"]
vals = [10, 20, 15]
[Link](cats, vals)
[Link]("Value"); [Link]("Category"); [Link]("barh() demo")
[Link]()
Output: Three horizontal bars (A=10, B=20, C=15).
Fundamentals of Python Programming for Beginners 311
Python Packages
Explanation: barh() plots data horizontally.
Q5. Matplotlib – Scatter plot
import [Link] as plt
x = [1,2,3,4,5]
y = [2,4,6,8,10]
[Link](x, y, s=80, alpha=0.8, edgecolors="black")
[Link]("Basic Scatter"); [Link]("x"); [Link]("y")
[Link]()
Output: Points along the line y=2x.
Explanation: scatter() plots individual points with size/alpha options.
Q6. Matplotlib – Histogram
import [Link] as plt
data = [1,2,2,3,3,3,4,4,4,4,5,5]
[Link](data, bins=5, edgecolor="black")
[Link]("Value"); [Link]("Frequency"); [Link]("Histogram")
[Link]()
Output: Histogram bars showing frequency by bin.
Fundamentals of Python Programming for Beginners 312
Python Packages
Explanation: hist() groups values into bins.
Q7. Matplotlib – Pie chart
import [Link] as plt
sizes = [25, 35, 40]
labels = ["Apples","Bananas","Cherries"]
[Link](sizes, labels=labels, autopct="%.0f%%", startangle=90)
[Link]("equal")
[Link]("Fruit Share")
[Link]()
Output: Pie chart with percentages.
Explanation: pie() shows proportions; autopct prints percent.
Q8. Matplotlib – Axis limits (xlim/ylim)
import [Link] as plt
x = [1,2,3,4,5]
y = [10,20,25,30,40]
[Link](x, y)
[Link](2, 4); [Link](15, 35)
[Link]("Zoomed View")
[Link]()
Output: Plot cropped to x=2..4 and y=15..35.
Fundamentals of Python Programming for Beginners 313
Python Packages
Explanation: xlim/ylim zoom into a range.
Q9. NumPy – Array creation basics
import numpy as np
a = [Link]([1,2,3])
z = [Link]((2,2))
o = [Link]((2,3))
print(a); print(z); print(o)
Output:
[1 2 3]
[[0. 0.]
[0. 0.]]
[[1. 1. 1.]
[1. 1. 1.]]
Explanation:
• [Link]([1,2,3]) → creates a 1D array [1 2 3].
• [Link]((2,2)) → creates a 2×2 array filled with zeros.
• [Link]((2,3)) → creates a 2×3 array filled with ones.
Q10. NumPy – arange & linspace
import numpy as np
print([Link](0,10,2)) # step of 2
print([Link](0,1,5)) # 5 evenly spaced numbers
Output:
[0 2 4 6 8]
[0. 0.25 0.5 0.75 1. ]
Explanation:
• [Link](0,10,2) → generates numbers from 0 to 10 (exclusive) with a step of 2
→ [0, 2, 4, 6, 8].
• [Link](0,1,5) → generates 5 evenly spaced numbers between 0 and 1
(inclusive) → [0., 0.25, 0.5, 0.75, 1.].
Fundamentals of Python Programming for Beginners 314
Python Packages
Q11. NumPy – Shape, ndim, size
import numpy as np
a = [Link]([[1,2],[3,4],[5,6]])
print([Link], [Link], [Link])
Output: (3, 2) 2 6
Explanation:
• [Link] → (3, 2) → array has 3 rows and 2 columns.
• [Link] → 2 → it is a 2-dimensional array (matrix).
• [Link] → 6 → total number of elements (3 × 2).
Q12. NumPy – dtype, itemsize, nbytes
import numpy as np
a = [Link]([[1,2],[3,4],[5,6]], dtype=np.int32)
print([Link], [Link], [Link])
Output (typical): int32 4 24
Explanation:
• [Link] → int32 → each element is a 32-bit integer.
• [Link] → 4 → each element takes 4 bytes.
• [Link] → 24 → total memory = 6 elements × 4 bytes = 24 bytes.
Q13. NumPy – Slicing & reshape
import numpy as np
a = [Link](1,7) # [1 2 3 4 5 6]
print(a[1:4]) # [2 3 4]
print([Link](2,3)) # 2x3 matrix
Output:
[2 3 4]
[[1 2 3]
[4 5 6]]
Explanation:
• a = [Link](1,7) → creates [1 2 3 4 5 6].
• a[1:4] → slices elements at indices 1, 2, 3 → [2 3 4].
• [Link](2,3) → reshapes array into a 2×3 matrix.
Q14. NumPy – Elementwise ops & statistics
import numpy as np
a = [Link]([1,2,3,4])
b = [Link]([10,20,30,40])
print(a + b) # elementwise add
Fundamentals of Python Programming for Beginners 315
Python Packages
print(a * 2) # scalar multiply
print([Link](), [Link]())
Output:
[11 22 33 44]
[2 4 6 8]
2.5 1.118033988749895 (std ≈ 1.118)
Explanation:
• a + b → elementwise addition → [1+10, 2+20, 3+30, 4+40] = [11 22 33 44].
• a * 2 → scalar multiplication → [2, 4, 6, 8].
• [Link]() → average of [1,2,3,4] = 2.5.
• [Link]() → standard deviation ≈ 1.118.
Q15. NumPy – Dot product
import numpy as np
a = [Link]([1,2,3])
b = [Link]([4,5,6])
print([Link](a,b))
Output: 32
Explanation:
• [Link](a, b) → computes the dot product:
1*4 + 2*5 + 3*6 = 4 + 10 + 18 = 32.
Q16. pandas – Series and DataFrame basics
import pandas as pd
s = [Link]([10,20,30], index=["a","b","c"])
df = [Link]({"Name":["A","B","C"], "Score":[85,90,78]})
print(s)
print(df)
Output:
a 10
b 20
c 30
dtype: int64
Name Score
0 A 85
1 B 90
2 C 78
Fundamentals of Python Programming for Beginners 316
Python Packages
Explanation:
• [Link]([10,20,30], index=["a","b","c"]) → creates a Series with custom index
labels.
• [Link]({...}) → creates a DataFrame with two columns: "Name" and
"Score".
Q17. pandas – Selecting columns & basic stats
import pandas as pd
df = [Link]({"Math":[80,90,85], "Sci":[78,92,88]})
print(df["Math"]) # column
print([Link](numeric_only=True))
Output:
0 80
1 90
2 85
Name: Math, dtype: int64
Math 85.0
Sci 86.0
dtype: float64
Explanation:
• df["Math"] → selects the Math column.
• [Link](numeric_only=True) → computes the mean of each numeric column:
✓ Math → (80+90+85)/3 = 85.0
✓ Sci → (78+92+88)/3 = 86.0
Q18. Tkinter – Small window with a label
import tkinter as tk
root = [Link]()
[Link]("Hello Tkinter")
[Link](root, text="Welcome!").pack()
[Link]()
Output: A small window showing “Welcome!”.
Explanation: Minimal GUI: create window, add label, start loop.
Fundamentals of Python Programming for Beginners 317
Python Packages
Q19. Tkinter – Button that updates label
import tkinter as tk
def greet():
[Link](text="Hello, Python!")
root = [Link]()
lbl = [Link](root, text="Click the button"); [Link]()
[Link](root, text="Greet", command=greet).pack()
[Link]()
Output: On click, label text changes to “Hello, Python!”.
Explanation: command binds the button to a function.
Q20. Tkinter – Entry box and show text
import tkinter as tk
def show():
[Link](text="You typed: " + [Link]())
root = [Link]()
ent = [Link](root); [Link]()
[Link](root, text="Show", command=show).pack()
out = [Link](root, text=""); [Link]()
[Link]()
Output: After typing and clicking “Show”, label displays entered text.
Explanation: [Link]() reads user input; label displays it.
Fundamentals of Python Programming for Beginners 318
Python Packages
Previous Year Examination Questions with Solutions
How to use the functions defined in [Link] in [Link]
Solution:
Steps:
1. Create [Link] with the functions
2. Create [Link] with the import statement
3. Run [Link] - it will automatically use functions from [Link]
4. Both files must be in the same folder
File 1: [Link]
# [Link]
# This file contains some useful functions
def add(a, b):
return a + b
def multiply(a, b):
return a * b
Output:
3.5
3
File 2: [Link]
# [Link]
# This file uses the functions from [Link]
# Step 1: Import the functions from [Link]
from library import add, multiply
# Step 2: Use the imported functions
num1 = 5
num2 = 3
print("Addition Result:", add(num1, num2))
print("Multiplication Result:", multiply(num1, num2))
Output:
Addition Result: 8
Multiplication Result: 15
Explanation:
1. [Link] – contains function definitions (add and multiply).
2. [Link] – imports those functions using
from library import add, multiply.
3. The functions are then called directly in [Link].
4. You only run [Link], and it automatically uses the functions from [Link].
Note:
Both files ([Link] and [Link]) must be saved in the same folder.
Fundamentals of Python Programming for Beginners 319
Python Packages
Describe the difference between linspace and argspace.
Solution:
linspace:
Generates a specified number of evenly spaced values between a start and stop value.
When you want a fixed number of points between two values, especially useful in plotting
or interpolation.
Syntax for linspace
[Link](start, stop, num)
Parameters:
• start: Beginning of the interval.
• stop: End of the interval (inclusive by default).
• num: Number of values to generate.
Example Program
[Link](0, 10, 5)
Output:
[0.0, 2.5, 5.0, 7.5, 10.0]
[Link]:
Generates values from start to stop (exclusive) using a fixed step size. When you want
values spaced by a constant interval, similar to Python’s built-in range() but supports
floats.
Syntax for [Link]
[Link](start, stop, step)
Parameters:
• start: Beginning of the sequence.
• stop: End of the sequence (not included).
• step: Difference between consecutive values.
Example Program
[Link](0, 10, 2)
Output:
[0, 2, 4, 6, 8]
Describe about different functions of matplotlib and pandas.
Solution:
Purpose
Matplotlib (Visualization) Pandas (Data Manipulation)
Creates visual representations of data Organizes, cleans, and analyzes tabular data
Difference between Matplotlib vs Pandas
Matplotlib Pandas
Like a paintbrush Like an Excel sheet
Creates visualizations Organizes and cleans data
Fundamentals of Python Programming for Beginners 320
Python Packages
Makes graphs and charts Handles tables and calculations
Output: Pictures/Graphs Output: Cleaned/Processed Data
Function Comparison
Matplotlib
Purpose Pandas Function Purpose
Function
[Link]() Line charts pd.read_csv() Read data files
[Link]() Dot plots [Link]() View first few rows
Data structure and
[Link]() Vertical bar charts [Link]()
types
[Link]() Histograms [Link]() Summary statistics
Select specific
[Link]() Pie charts df['column']
column
Group data for
[Link]() Add chart title [Link]()
aggregation
[Link]() / Sort data by
Axis labels df.sort_values()
[Link]() column
Remove missing
[Link]() Add legend to chart [Link]()
values
[Link]() Add grid lines [Link]() Fill missing values
Correlation
[Link]() Display the plot [Link]()
between columns
Construct a plot for following dataset using matplotlib:
Food Calories Potassium fat
Meat 250 40 8
Banana 130 55 5
Avocados 140 20 3
Sweet
120 30 6
Potatoes
Spinach 20 40 1
Watermelon 20 32 1.5
Coconut
10 10 0
water
Beans 50 26 2
Legumes 40 25 1.5
Tomato 19 20 2.5
Solution:
Example: Separate Each Character by a Comma
import [Link] as plt
import numpy as np
# Data
food = ["Meat", "Banana", "Avocados", "Sweet Potatoes", "Spinach",
"Watermelon", "Coconut water", "Beans", "Legumes", "Tomato"]
Fundamentals of Python Programming for Beginners 321
Python Packages
calories = [250, 130, 140, 120, 20, 20, 10, 50, 40, 19]
potassium = [40, 55, 20, 30, 40, 32, 10, 26, 25, 20]
fat = [8, 5, 3, 6, 1, 1.5, 0, 2, 1.5, 2.5]
# X-axis positions
x = [Link](len(food))
width = 0.25 # width of each bar
# Plot bar chart
[Link](x - width, calories, width, label='Calories', color='red')
[Link](x, potassium, width, label='Potassium', color='green')
[Link](x + width, fat, width, label='Fat', color='blue')
# Labels and title
[Link]("Food Items")
[Link]("Nutritional Values")
[Link]("Nutritional Comparison of Food Items")
[Link](x, food, rotation=30)
[Link]()
# Display chart
[Link]()
Output:
Explanation:
1. Import libraries:
✓ [Link] → used to create graphs.
✓ numpy → used for handling numerical data and positions on the X-axis.
2. Data creation:
✓ Lists food, calories, potassium, and fat store the nutritional information for
each food item.
3. X-axis setup:
✓ [Link](len(food)) creates numeric positions for each food item.
✓ width = 0.25 sets the thickness of each bar.
4. Plotting bars:
Fundamentals of Python Programming for Beginners 322
Python Packages
✓ [Link](x - width, calories, ...) → plots red bars for Calories.
✓ [Link](x, potassium, ...) → plots green bars for Potassium.
✓ [Link](x + width, fat, ...) → plots blue bars for Fat.
✓ This arrangement groups the bars for each food item side by side.
5. Labels and formatting:
✓ Adds X-axis, Y-axis labels, and a title.
✓ [Link](..., rotation=30) rotates the food names for readability.
✓ [Link]() shows the color key (Calories, Potassium, Fat).
6. Show the chart:
✓ [Link]() displays the final grouped bar chart comparing nutritional
values.
Construct a program to read [Link] dataset, remove last column and save it in an
array. Save the last column to another array. Plot the first two columns.
Solution:
import pandas as pd
import [Link] as plt
import io
# ---- 1. Sample CSV with your header & extra column ----
csv_content = """City, State, Population, Temperature
Delhi, Delhi, 30000000, 35
Mumbai, Maharashtra, 20000000, 32
Bangalore, Karnataka, 13000000, 28
Chennai, Tamil Nadu, 11000000, 33
Kolkata, West Bengal, 15000000, 30"""
# ---- 2. Load as DataFrame ----
cities_df = pd.read_csv([Link](csv_content))
# ---- 3. Convert to arrays ----
cities_array = cities_df.values
last_column = cities_array[:, -1] # Temperature
data_without_last = cities_array[:, :-1] # City, State, Population
# ---- 4. PLOT: Population vs Temperature (Numeric!) ----
population = data_without_last[:, 2].astype(float) # 3rd column
temperature = last_column.astype(float)
[Link](figsize=(8, 5))
[Link](population, temperature, color='blue', s=100, edgecolors='black')
# Add city names on points
cities = data_without_last[:, 0]
for i, city in enumerate(cities):
[Link](population[i] + 200000, temperature[i], city, fontsize=10)
[Link]('Population vs Temperature')
[Link]('Population')
[Link]('Temperature (°C)')
Fundamentals of Python Programming for Beginners 323
Python Packages
[Link](True, alpha=0.5)
plt.tight_layout()
[Link]()
# ---- 5. Print arrays correctly ----
print("Data WITHOUT last column (City, State, Population):")
print(data_without_last)
print("\nLast column (Temperature):")
print(last_column)
Output:
Data WITHOUT last column (City, State, Population):
[['Delhi' 'Delhi' 30000000]
['Mumbai' 'Maharashtra' 20000000]
['Bangalore' 'Karnataka' 13000000]
['Chennai' 'Tamil Nadu' 11000000]
['Kolkata' 'West Bengal' 15000000]]
Last column (Temperature):
[35. 32. 28. 33. 30.]
Explanation
Step 1: Import Libraries
import pandas as pd
import [Link] as plt
import io
• pandas (pd): helps read and organize tabular data.
• [Link] (plt): used for drawing plots and graphs.
• io: allows us to read data from a string instead of a file.
Step 2: Create Sample CSV Data
csv_content = """City, State, Population, Temperature
Fundamentals of Python Programming for Beginners 324
Python Packages
Delhi, Delhi, 30000000, 35
...
"""
• This is sample CSV text stored in a string (like a file’s content).
• Each line represents a city’s data:
✓ City name
✓ State name
✓ Population
✓ Temperature
Step 3: Read Data into a DataFrame
cities_df = pd.read_csv([Link](csv_content))
• Converts the text data into a DataFrame (table format).
• Example DataFrame:
City State Population Temperature
Delhi Delhi 30000000 35
Mumbai Maharashtra 20000000 32
Bangalore Karnataka 13000000 28
Chennai Tamil Nadu 11000000 33
Kolkata West Bengal 15000000 30
Step 4: Convert DataFrame to Array
cities_array = cities_df.values
• Converts the table to a NumPy array, making it easier to extract columns by index.
Step 5: Separate Columns
last_column = cities_array[:, -1]
data_without_last = cities_array[:, :-1]
• [:, -1] → takes the last column (Temperature).
• [:, :-1] → takes everything except the last column (City, State, Population).
Step 6: Extract Numeric Data
population = data_without_last[:, 2].astype(float)
temperature = last_column.astype(float)
• Converts Population and Temperature columns into numeric values (float).
• Needed for plotting on the graph.
Step 7: Create a Scatter Plot
[Link](figsize=(8,5))
[Link](population, temperature, color='blue', s=100, edgecolors='black')
• [Link]() → plots dots on a graph (X=Population, Y=Temperature).
• Blue circles represent each city.
Step 8: Add City Names
for i, city in enumerate(cities):
[Link](population[i] + 200000, temperature[i], city, fontsize=10)
• Loops through each city and adds its name next to its point.
• +200000 shifts the text slightly to the right.
Step 9: Label and Show the Plot
[Link]('Population vs Temperature')
Fundamentals of Python Programming for Beginners 325
Python Packages
[Link]('Population')
[Link]('Temperature (°C)')
[Link](True, alpha=0.5)
plt.tight_layout()
[Link]()
• Adds title, axis labels, and grid for readability.
• [Link]() displays the plot window.
Step 10: Print the Arrays
print("Data WITHOUT last column...")
print(data_without_last)
print("Last column...")
print(last_column)
• Displays both arrays clearly in the console output.
Design a calculator with the following buttons and functionalities like addition,
subtraction, multiplication, division and clear.
Solution:
Solution:
import tkinter as tk
# Function to update the display
def update_display(value):
current_text = display_var.get()
if current_text == "0":
display_var.set(value)
else:
display_var.set(current_text + value)
# Function to clear the display
def clear_display():
display_var.set("0")
# Function to evaluate the expression and display the result
def calculate_result():
try:
result = eval(display_var.get())
display_var.set(result)
except Exception as e:
display_var.set("Error")
# Create the main window
parent = [Link]()
[Link]("Calculator")
# Create a variable to store the current display value
display_var = [Link]()
display_var.set("0")
# Create the display label
display_label = [Link](parent, textvariable=display_var, font=("Arial", 24), anchor="e",
bg="lightgray", padx=10, pady=10)
display_label.grid(row=0, column=0, columnspan=4)
Fundamentals of Python Programming for Beginners 326
Python Packages
# Define the button layout
button_layout = [
("7", 1, 0), ("8", 1, 1), ("9", 1, 2), ("/", 1, 3),
("4", 2, 0), ("5", 2, 1), ("6", 2, 2), ("*", 2, 3),
("1", 3, 0), ("2", 3, 1), ("3", 3, 2), ("-", 3, 3),
("0", 4, 0), (".", 4, 1), ("=", 4, 2), ("+", 4, 3),
]
# Create and place the buttons
for (text, row, col) in button_layout:
button = [Link](parent, text=text, padx=20, pady=20, font=("Arial", 18),
command=lambda t=text: update_display(t) if t != "=" else calculate_result())
[Link](row=row, column=col)
# Create a Clear button
clear_button = [Link](parent, text="C", padx=20, pady=20, font=("Arial", 18),
command=clear_display)
clear_button.grid(row=5, column=0, columnspan=3)
# Start the Tkinter event loop
[Link]()
OUTPUT:
Describe how to generate random numbers using NumPy. Write a Python program
to create an array of 5 random integers between 10 and 50.
Solution:
Generating Random Numbers Using NumPy
• NumPy is a powerful Python library used for scientific and numerical computations.
• It provides a special module called [Link] which can be used to generate
random numbers efficiently
• These random numbers can be integers, floating-point numbers, or values from different
probability distributions.
• Random numbers are often used in data science, simulations, games, and machine
learning.
Function & Example Description
[Link](low, high, size) Generates random integers between low
Example: [Link](1, 10, 5) (inclusive) and high (exclusive)
[Link](size) Generates random floating-point numbers
Example: [Link](5) between 0 and 1
Fundamentals of Python Programming for Beginners 327
Python Packages
[Link](list) Randomly selects elements from a given list
Example: [Link]([1,2,3]) or array
[Link](value) Sets the seed to reproduce the same
Example: [Link](10) random values each time
[Link]( ) Syntax: [Link](low, high, size)
Parameters:
• low → Lower bound (inclusive)
• high → Upper bound (exclusive)
• size → Number of random integers to generate
Example:
[Link](10, 51, size=5) generates 5 random integers between 10 and 50 (since
upper limit 51 is exclusive).
Python program to create an array of 5 random integers between 10 and 50.
import numpy as np
# Generate an array of 5 random integers between 10 and 50
random_array = [Link](10, 51, size=5)
# Display the result
print("Random integers between 10 and 50:", random_array)
Output:
Random integers between 10 and 50: [23 47 12 35 18]
Note: Output will vary each time you run the program.
Explanation:
1. Import NumPy:
The statement import numpy as np imports the NumPy library.
2. Generate Random Numbers:
[Link](10, 51, size=5) creates 5 random integers between 10 and
50.
3. Print Result:
The array of random numbers is printed using the print() function.
Advantages of Using NumPy for Random Numbers
1. Fast and Efficient:
Generates large arrays of random numbers quickly.
2. Memory Efficient:
Handles big data arrays efficiently without using loops.
3. Supports Multiple Distributions:
Can generate random data for uniform, normal, and other distributions.
4. Reproducibility:
Using [Link]() ensures the same output each time.
5. Widely Used in Real Projects:
Common in data analysis, simulations, and AI model training.
Fundamentals of Python Programming for Beginners 328
Python Packages
Explain the concept of DataFrame in pandas. Write a Python program to create a
DataFrame from a dictionary and print it.
Solution:
• A DataFrame is one of the most important data structures provided by the Pandas
library in Python.
• It is used to store and manage data in tabular form (rows and columns) similar
to a spreadsheet or SQL table.
• Each column in a DataFrame can contain data of different types such as integers,
floats, strings, or even dates.
Key Features of a DataFrame:
Feature Description
2-Dimensional Data is organized in rows and columns (like a table).
Labeled Axes Rows and columns have labels (called index and column names).
Heterogeneous
Each column can have different data types.
Data
Size Mutable You can add or delete columns and rows.
Data Alignment Handles missing data gracefully.
Data Sources Can be created from dictionaries, lists, CSV files, Excel sheets, etc.
Creating a DataFrame:
You can create a DataFrame in many ways:
• From a dictionary
• From a list of lists or tuples
• From external data files (CSV, Excel, SQL, etc.)
Example-1: Python program to create DataFrame from a Dictionary
import pandas as pd
# Create a dictionary of data
data = {
'Name': ['Rahul', 'Mayank'],
'Age': [35, 42],
'Department': ['ECE', 'CSE'],
'Institute': ['JSSATE, Noida.', 'JSS University, Noida.']
}
# Create DataFrame from dictionary
df = [Link](data)
# Display the DataFrame
print("DataFrame created from dictionary:")
print(df)
Output:
DataFrame created from dictionary:
Name Age Department Institute
0 Rahul 35 ECE JSSATE, Noida.
1 Mayank 42 CSE JSS University, Noida.
Explanation:
• The data dictionary contains column names as keys and lists as values.
• The [Link](data) function converts this dictionary into a DataFrame.
Fundamentals of Python Programming for Beginners 329
Python Packages
• Each list becomes a column, and each element of the list becomes a row entry.
• Finally, print(df) displays the table neatly.
OR
Example-2: Python program to create DataFrame from a Dictionary
import pandas as pd
# Create a dictionary of data
data = {
'Name': ['Rahul', 'Arun', 'Mayank', 'Neha'],
'Age': [35, 43, 42, 25],
'Department': ['ECE', 'ECE', 'CSE', 'CSE'],
'Institute': ['JSSATE, Noida.', 'JSSATE, Noida.', 'JSS University, Noida.', 'GL Bajaj.']
}
# Create DataFrame from dictionary
df = [Link](data)
# Display the DataFrame
print("DataFrame created from dictionary:")
print(df)
Output:
DataFrame created from dictionary:
Name Age Department Institute
0 Rahul 35 ECE JSSATE, Noida.
1 Arun 43 ECE JSSATE, Noida.
2 Mayank 42 CSE JSS University, Noida.
3 Neha 25 CSE GL Bajaj.
Explanation:
• The dictionary data contains four columns Name, Age, Department, and Institute.
• [Link](data) converts this dictionary into a tabular DataFrame.
• Each key becomes a column name, and each list of values becomes a column’s
data.
• The DataFrame is displayed neatly using print(df).
Explain why numpy is used instead of python arrays for mathematical calculations?
Solution:
Python List / Array:
• A list (or built-in array using the array module) is a general-purpose container in
Python that can hold elements of different data types (e.g., integers, strings,
floats).
• It is not optimized for mathematical or numerical operations.
NumPy Array:
• A NumPy array is a special type of box made only for numbers.
• It is fast, powerful, and uses less memory, best for mathematics, statistics,
and data analysis.
Example: Python List (Normal Addition)
a = [1, 2, 3]
Fundamentals of Python Programming for Beginners 330
Python Packages
b = [4, 5, 6]
# Adding two lists concatenates them
print(a + b)
Output:
[1, 2, 3, 4, 5, 6]
Example: NumPy Array (Mathematical Addition)
import numpy as np
a = [Link]([1, 2, 3])
b = [Link]([4, 5, 6])
# Adding two arrays performs element-wise addition
print(a + b)
Output:
[5 7 9]
Advantages of NumPy over Python Lists:
Feature NumPy Array Python List / Array
Much faster (implemented in
Speed Slower
C)
Memory Consumes less memory Uses more memory
Heterogeneous (mixed types
Data Type Homogeneous (all same type)
allowed)
Mathematical Needs loops or list
Direct element-wise support
Operations comprehension
Rich set of mathematical,
Functions statistical, and linear algebra Limited built-in operations
functions
Multi-
Mostly 1D lists (no native matrix
dimensional Supports 1D, 2D, 3D... arrays
support)
Support
Create a pie chart using matplotlib to represent the following data:
Languages Popularity
Python 30
Java 25
C++ 20
JavaScript 15
Ruby 10
Solution:
Method-1: Using Variables (Best for Learning)
import [Link] as plt
# Data
languages = ['Python', 'Java', 'C++', 'JavaScript', 'Ruby']
popularity = [30, 25, 20, 15, 10]
# Create pie chart
[Link](popularity, labels=languages)
Fundamentals of Python Programming for Beginners 331
Python Packages
# Add title
[Link]('Programming Language Popularity')
# Show the chart
[Link]()
Output:
Method-2: Direct Values (Short & Fast)
import [Link] as plt
[Link]([30,25,20,15,10], labels=['Python','Java','C++','JavaScript','Ruby'])
[Link]("Language Popularity")
[Link]()
Output:
Method-3: With Percentages (Most Informative)
import [Link] as plt
[Link]([30, 25, 20, 15, 10],
labels=['Python','Java','C++','JavaScript','Ruby'],
autopct='%1.0f%%') # ← This adds percentages!
Fundamentals of Python Programming for Beginners 332
Python Packages
[Link]("Language Popularity")
[Link]()
Output:
Note:
autopct:
1. autopct stands for “automatic percentage”.
2. It tells Matplotlib to display the percentage value for each slice of the pie chart.
autopct='%1.0f%%')
Part Meaning
'%' Starts a format string
Tells Python to format the number as a floating-point number with 0 digits
1.0f
after the decimal
%% Prints a literal percent sign (%) after the number
So, ' %1.0f%% ' means: Show the number as a floating-point value with no decimal places,
followed by a percent sign.
Write a program to read a CSV file and display the rows where a specific column value
exceeds a given threshold.
Solution:
Example Program:
Initial File Content [Link]
Name,Marks
Rahul,45
Bharat,78
Manoj,62
Ritesh,39
import csv
# Set threshold value
threshold = 50
# Open and read the CSV file
Fundamentals of Python Programming for Beginners 333
Python Packages
with open("[Link]", "r") as file:
reader = [Link](file) # Reads rows as dictionaries
print("Rows where Marks > 50:")
for row in reader:
if int(row["Marks"]) > threshold:
print(row)
Output:
Rows where Marks > 50:
{'Name': 'Bharat', 'Marks': '78'}
{'Name': 'Manoj', 'Marks': '62'}
Explanation:
1. import csv Loads the CSV module to handle file reading.
2. threshold = 50 Sets the minimum marks to filter.
3. open("[Link]", "r") Opens the file in read mode.
4. [Link](file) Reads each row as a dictionary: Example → {'Name': 'Rahul',
'Marks': '45'}
5. int(row["Marks"]) > threshold Converts the "Marks" value to integer and checks if
it's greater than 50.
6. print(row) Displays the entire row if condition is true.
Write a program to read data from a CSV file '[Link]', calculate the average
marks for each student, and display the results
Solution:
Method-1: Using [Link] (Basic CSV Reading with Lists)
Assume the CSV file looks like this (3 subjects per student):
Name,Math,Science,English
Rahul,80,75,90
Bharat,60,70,65
Manoj,90,95,85
Ritesh,50,55,58
import csv
with open("[Link]", "r") as f:
reader = [Link](f)
next(reader) # skip header row: Name,Math,Science,English
for row in reader:
name = row[0]
m1 = int(row[1])
m2 = int(row[2])
m3 = int(row[3])
avg = (m1 + m2 + m3) / 3
print(name, "-> Average:", round(avg, 2))
Output:
Student Averages:
Rahul -> Average: 81.67
Bharat -> Average: 65.0
Manoj -> Average: 90.0
Fundamentals of Python Programming for Beginners 334
Python Packages
Ritesh -> Average: 54.33
Explanation:
1. import csv
✓ We import the csv module so we can read data from a CSV file.
2. with open("[Link]", "r") as f:
✓ Opens the file named [Link] in read mode ("r").
✓ with makes sure the file will close automatically.
3. reader = [Link](f)
✓ Creates a CSV reader that reads the file line by line.
4. next(reader)
✓ Skips the first row in the file (Name,Math,Science,English) because that row
is just column titles, not data.
5. for row in reader:
✓ Goes through each remaining row in the file.
✓ Each row is a list of values from the CSV, for example:
["Rahul", "80", "75", "90"]
6. name = row[0]
✓ Gets the student's name (first column).
7. m1 = int(row[1]), m2 = int(row[2]), m3 = int(row[3])
✓ Gets the three marks (Math, Science, English) and converts them from strings
to integers.
8. avg = (m1 + m2 + m3) / 3
✓ Calculates the average marks for that student.
9. print(name, "-> Average:", round(avg, 2))
✓ Prints the student's name and their average.
✓ round(avg, 2) keeps only 2 decimal places (like 81.67).
Method-2: Using [Link] (Reading CSV as Dictionaries)
Assume the CSV file looks like this (3 subjects per student):
Name,Math,Science,English
Rahul,80,75,90
Bharat,60,70,65
Manoj,90,95,85
Ritesh,50,55,58
import csv
# Open and read the CSV file
with open("[Link]", "r") as file:
reader = [Link](file) # reads each row as a dictionary
print("Student Averages:")
for row in reader:
name = row["Name"]
# Get marks for the subjects and convert to int
math = int(row["Math"])
sci = int(row["Science"])
eng = int(row["English"])
# Calculate average
avg = (math + sci + eng) / 3
Fundamentals of Python Programming for Beginners 335
Python Packages
# Print result (rounded to 2 decimal places)
print(name, "-> Average:", round(avg, 2))
Output:
Student Averages:
Rahul -> Average: 81.67
Bharat -> Average: 65.0
Manoj -> Average: 90.0
Ritesh -> Average: 54.33
Explanation:
1. import csv → Imports Python’s CSV module for reading CSV files easily.
2. with open("[Link]", "r") as file:
Opens the file in read mode ("r"). The with statement ensures the file closes
automatically.
3. [Link](file) → Reads each line as a dictionary.
Example row:
4. {'Name': 'Rahul', 'Math': '80', 'Science': '75', 'English': '90'}
5. Extract name:
name = row["Name"]
6. Extract marks:
[int(value) for key, value in [Link]() if key != "Name"]
→ Converts all subject marks into integers.
7. Find average:
avg = sum(marks) / len(marks)
→ Adds marks and divides by total subjects.
8. Display result:
print(name, "-> Average:", round(avg, 2))
→ Prints average up to two decimal places.
Method-3: Using pandas (DataFrame-Based Calculation of Averages)
Assume the CSV file looks like this (3 subjects per student):
Name,Math,Science,English
Rahul,80,75,90
Bharat,60,70,65
Manoj,90,95,85
Ritesh,50,55,58
import pandas as pd
df = pd.read_csv("[Link]")
df["Average"] = df[["Math", "Science", "English"]].mean(axis=1)
print(df[["Name", "Average"]].round(2))
Output:
Name Average
0 Rahul 81.67
1 Bharat 65.00
2 Manoj 90.00
3 Ritesh 54.33
Note:
• pd.read_csv() → Reads data from a CSV file into a DataFrame.
• df["Average"] → Creates a new column with calculated averages.
Fundamentals of Python Programming for Beginners 336
Python Packages
• [Link]() → Loops through each row in the DataFrame.
• round(value, 2) → Rounds the average to 2 decimal places.
Explanation:
Step 1: import pandas as pd
• This loads the pandas library.
• Pandas helps us work with table data (like data in Excel or CSV files).
Step 2: df = pd.read_csv("[Link]")
• pd.read_csv("[Link]") reads the CSV file named [Link].
• The data is stored in a table called df (DataFrame).
• Now df has columns: Name, Math, Science, English.
Example of what df looks like:
Name Math Science English
Rahul 80 75 90
Bharat 60 70 65
Manoj 90 95 85
Ritesh 50 55 58
Step 3:
df["Average"] = df[["Math", "Science", "English"]].mean(axis=1)
Break it:
• df[["Math", "Science", "English"]]
✓ Take only the three marks columns from the table.
• .mean(axis=1)
✓ For each row (for each student), calculate the average of those three marks.
✓ Example for Rahul:
▪ (80 + 75 + 90) / 3 = 81.67
• df["Average"] = ...
✓ Create a new column called Average in the table and store the result there.
Now the table df looks like:
Name Math Science English Average
Rahul 80 75 90 81.6667
Bharat 60 70 65 65.0000
Manoj 90 95 85 90.0000
Ritesh 50 55 58 54.3333
Step 4:
print(df[["Name", "Average"]].round(2))
Break it:
• df[["Name", "Average"]]
✓ Pick only the Name column and the new Average column.
✓ We don't print all marks now.
• .round(2)
✓ Round the Average to 2 decimal places (for neat output like 81.67 instead of
81.6666667).
• print(...)
✓ Show the result.
Fundamentals of Python Programming for Beginners 337
Python Packages
Final Output on screen:
Name Average
0 Rahul 81.67
1 Bharat 65.00
2 Manoj 90.00
3 Ritesh 54.33
Write a Python program using numpy to perform matrix operations.
Solution:
Example 1: Matrix Operations Using NumPy (2×2)
import numpy as np
# Create two matrices
x = [Link]([ [1, 2],
[3, 4]])
y = [Link]([ [1, 2],
[3, 4]])
print("Matrix x:\n", x)
print("Matrix y:\n", y)
# Matrix Addition
add = x + y
print("\nAddition of x and y:\n", add)
# Matrix Subtraction
sub = x - y
print("\nSubtraction of x and y:\n", sub)
# Matrix Multiplication (element-wise)
mul = x * y
print("\nElement-wise Multiplication of x and y:\n", mul)
# Matrix Division (element-wise)
divide = x / y
print("\nElement-wise Division of x and y:\n", divide)
# Transpose of a Matrix
trans = x.T
print("\nTranspose of Matrix x:\n", trans)
Output:
Matrix x:
[[1 2]
[3 4]]
Matrix y:
[[1 2]
Fundamentals of Python Programming for Beginners 338
Python Packages
[3 4]]
Addition of x and y:
[[ 2 4]
[ 6 8]]
Subtraction of x and y:
[[0 0]
[0 0]]
Element-wise Multiplication of x and y:
[[ 1 4]
[ 9 16]]
Element-wise Division of x and y:
[[1. 1.]
[1. 1.]]
Transpose of Matrix x:
[[1 3]
[2 4]]
Explanation:
1. [Link]() creates 2×2 matrices.
2. x + y adds elements of both matrices.
3. x - y subtracts elements of y from x.
4. x * y multiplies corresponding elements (not matrix multiplication).
5. x / y divides corresponding elements.
6. x.T gives the transpose of x (rows become columns).
OR
Example 2: Matrix Operations Using NumPy (3×3)
import numpy as np
# ----- CREATE MATRICES -----
X = [Link]([[2, 4, 6], [1, 3, 5], [7, 8, 9]])
Y = [Link]([[9, 8, 7], [6, 5, 4], [3, 2, 1]])
print("Matrix X:\n", X)
print("Matrix Y:\n", Y)
# ----- ELEMENT-WISE MULTIPLICATION -----
elementwise = X * Y
print("\nElement-wise Multiplication (X * Y):\n", elementwise)
# ----- MATRIX MULTIPLICATION -----
matrix_mul = [Link](X, Y)
print("\nMatrix Multiplication (X @ Y):\n", matrix_mul)
Fundamentals of Python Programming for Beginners 339
Python Packages
# ----- TRANSPOSE -----
transpose_Y = Y.T
print("\nTranspose of Y:\n", transpose_Y)
# ----- DETERMINANT -----
det_X = [Link](X)
print("\nDeterminant of X:", round(det_X, 2))
Output:
Matrix X:
[[2 4 6]
[1 3 5]
[7 8 9]]
Matrix Y:
[[9 8 7]
[6 5 4]
[3 2 1]]
Element-wise Multiplication (X * Y):
[[18 32 42]
[6 15 20]
[21 16 9]]
Matrix Multiplication (X @ Y):
[[60 48 36]
[42 33 24]
[150 126 102]]
Transpose of Y:
[[9 6 3]
[8 5 2]
[7 4 1]]
Determinant of X: 6.0
Explanation
• X * Y → Element-wise multiplication.
• [Link](X, Y) → Matrix multiplication.
• Y.T → Transpose of matrix Y.
• [Link](X) → Determinant of matrix X.
Explain the use of matplotlib for data visualization. Write a program to visualize Line
plots using these data:
x = [1, 2, 3, 4, 5]
y = [10, 20, 25, 30, 40]
Solution:
import [Link] as plt
Fundamentals of Python Programming for Beginners 340
Python Packages
# Given data
x = [1, 2, 3, 4, 5]
y = [10, 20, 25, 30, 40]
# Plot line graph
[Link](x, y)
# Add labels and title
[Link]("X values")
[Link]("Y values")
[Link]("Simple Line Plot")
# Show the graph
[Link]()
What is GUI programming in Python? Write a GUI-based Python program using
Tkinter to accept and display student data.
Solution:
GUI programming:
• GUI stands for Graphical User Interface.
• GUI programming in Python means creating windows, buttons, labels, text
boxes, menus, and other visual elements that allow users to interact with a
program easily instead of typing commands in the console.
Purpose of GUI:
• The main purpose of GUI programming is to make applications user-friendly and
interactive.
It allows users to input data, click buttons, view messages, and perform tasks
visually.
Fundamentals of Python Programming for Beginners 341
Python Packages
Python GUI Library:
Python provides a built-in module called Tkinter for GUI programming.
It is one of the simplest and most commonly used libraries for building desktop
applications.
Other Popular GUI Libraries in Python:
Library Description
PyQt Advanced GUI toolkit based on Qt framework; supports complex interfaces
Kivy Used for multi-touch applications and mobile-friendly GUIs
wxPython Native-looking GUI toolkit for desktop apps
Key Features of GUI Applications:
• User-friendly interface
• Interactive components (buttons, forms, sliders)
• Event-driven (responds to user actions like clicks or typing)
• Used in desktop apps, tools, and educational software
How do we use packages in Python programming? Explain the use of pandas.
Solution:
Packages in Python:
A package in Python is a collection of modules (Python files) that are grouped together
to organize related functions, classes, and variables.
Packages help to:
• Reuse code easily
• Keep programs organized
• Avoid name conflicts
A package usually contains a special file named __init__.py, which tells Python that this
directory is a package.
Using Packages
To use a package in Python, we import it using the import statement.
Syntax:
import package_name
or
from package_name import module_name
Example:
import math
print([Link](25))
This imports the math package and uses its sqrt() function to find the square root of 25.
Pandas:
Pandas is a powerful Python package used for data handling, data analysis, and data
manipulation. It is widely used in data science and machine learning.
Pandas provides two main data structures:
1. Series – one-dimensional (like a list or column)
2. DataFrame – two-dimensional (like a table with rows and columns)
Fundamentals of Python Programming for Beginners 342
Python Packages
Applications of Pandas:
• To handle large data sets easily
• To perform operations like filtering, sorting, merging, and grouping
• To read and write data from files like CSV, Excel, or SQL
Example 1: Program to Create and Display a DataFrame using pandas in Python
import pandas as pd
# Create a DataFrame
data = {
'Name': ['Rahul', 'Vimal', 'Rakesh'],
'Age': [35, 48, 37],
'Branch': ['ECE', 'CSE', 'ECE']
}
df = [Link](data)
# Display the DataFrame
print(df)
Output:
Name Age Branch
0 Rahul 35 ECE
1 Vimal 48 CSE
2 Rakesh 37 ECE
OR
Example 2: Program Demonstrating pandas Operations in Python
import pandas as pd
# Create a DataFrame
data = {
'Name': ['Rahul', 'Vimal', 'Rakesh'],
'Age': [35, 48, 37],
'Branch': ['ECE', 'CSE', 'ECE']
}
df = [Link](data)
# Display the original DataFrame
print("Original DataFrame:\n", df)
# 1. Display only one column (Age)
print("\n 1 Display Age column:")
print(df['Age'])
Fundamentals of Python Programming for Beginners 343
Python Packages
# 2. Display multiple columns (Name and Branch)
print("\n 2 Display Name and Branch columns:")
print(df[['Name', 'Branch']])
# 3. Filter rows where Branch is 'ECE'
print("\n 3 Students from ECE branch:")
print(df[df['Branch'] == 'ECE'])
# 4. Add a new row to the DataFrame
new_row = {'Name': 'Suresh', 'Age': 42, 'Branch': 'EEE'}
df = [Link]([df, [Link]([new_row])], ignore_index=True)
print("\n 4 After adding a new student record:")
print(df)
# 5. Sort data by Age
sorted_df = df.sort_values(by='Age')
print("\n 5 Data sorted by Age:")
print(sorted_df)
# 6. Display basic information about the DataFrame
print("\n 6 DataFrame Information:")
print([Link]())
Output
Original DataFrame:
Name Age Branch
0 Rahul 35 ECE
1 Vimal 48 CSE
2 Rakesh 37 ECE
1 Display Age column:
0 35
1 48
2 37
Name: Age, dtype: int64
2 Display Name and Branch columns:
Name Branch
0 Rahul ECE
1 Vimal CSE
2 Rakesh ECE
3 Students from ECE branch:
Name Age Branch
0 Rahul 35 ECE
2 Rakesh 37 ECE
4 After adding a new student record:
Name Age Branch
0 Rahul 35 ECE
Fundamentals of Python Programming for Beginners 344
Python Packages
1 Vimal 48 CSE
2 Rakesh 37 ECE
3 Suresh 42 EEE
5 Data sorted by Age:
Name Age Branch
0 Rahul 35 ECE
2 Rakesh 37 ECE
3 Suresh 42 EEE
1 Vimal 48 CSE
6 DataFrame Information:
<class '[Link]'>
RangeIndex: 4 entries, 0 to 3
Data columns (total: 3 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Name 4 non-null object
1 Age 4 non-null int64
2 Branch 4 non-null object
dtypes: int64(1), object(2)
memory usage: 224.0 bytes
None
Explanation:
• [Link]() → creates a table from dictionary data
• df['Age'] → displays one column
• df[['Name','Branch']] → shows specific columns
• df[df['Branch']=='ECE'] → filters only ECE students
• [Link]() → adds new rows
• df.sort_values(by='Age') → sorts records
• [Link]() → shows structure and data types
Fundamentals of Python Programming for Beginners 345