0% found this document useful (0 votes)
24 views20 pages

Unit 5

The document provides an overview of Python packages, focusing on libraries such as NumPy, Matplotlib, Pandas, and Tkinter. It explains their functionalities, features, and provides code examples for creating visualizations and data manipulations. Additionally, it highlights the importance of Tkinter for GUI programming in Python.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views20 pages

Unit 5

The document provides an overview of Python packages, focusing on libraries such as NumPy, Matplotlib, Pandas, and Tkinter. It explains their functionalities, features, and provides code examples for creating visualizations and data manipulations. Additionally, it highlights the importance of Tkinter for GUI programming in Python.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

UNIT- V PACKAGES & GUI

PART A ( 2 Marks)
1. Write about packages in Python.
Packages in Python are directories that contain multiple modules (Python files). A package must contain a special file
named __init__.py to be recognized as a package. Packages help in organizing related modules together and promote
code reusability.
2. Define NumPy and give its features.
NumPy (Numerical Python) is a library used for numerical computations in Python.
Features:
 Supports multi-dimensional arrays (ndarrays)
 Fast mathematical operations
 Functions for linear algebra, Fourier transforms, and random numbers
3. What function is used in Matplotlib to plot a basic line graph? Provide an example.
The function plot() is used to draw a line graph in Matplotlib.
Example:
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [4, 5, 1])
plt.show()
4. Write about pandas in Python.
Pandas is a Python library used for data manipulation and analysis. It provides two main data structures: Series (1D)
and DataFrame (2D). It helps in handling large data sets efficiently.
5. Which Python library is commonly used for creating GUI applications?
Tkinter is the standard Python library used for creating GUI (Graphical User Interface) applications. It provides
various widgets like buttons, labels, and text boxes.

6. Write a simple code snippet to create and display a bar chart using Matplotlib.
import matplotlib.pyplot as plt
x = ['A', 'B', 'C']
y = [10, 20, 15]
plt.bar(x, y)
plt.show()

7. Name any four Tkinter widgets and their purposes.


 Label – Displays text
 Button – Triggers an action
 Entry – Accepts user input
 Text – Multi-line text input area
8. Write about Matplotlib.
Matplotlib is a data visualization library in Python. It allows users to create static, animated, and interactive plots such
as line charts, bar charts, scatter plots, and histograms.
9. What is the purpose of the mainloop() method in Tkinter?
The mainloop() method starts the GUI event loop. It waits for user actions like clicks or key presses and updates the
GUI accordingly.
10. Define Tkinter programming.
Tkinter programming is the use of the Tkinter library in Python to create GUI applications. It includes creating
windows, adding widgets, and handling user events.
DESCRIPTIVE QUESTIONS ( 13 MARKS)
1. Explain the use of built-in functions from the Matplotlib package and write a Python program to create a
simple line graph plot.
Introduction to Matplotlib:
Matplotlib is a powerful data visualization library in Python used to create static, animated, and interactive plots. It
is especially useful in presenting data through various graphical formats like line charts, bar charts, histograms,
scatter plots, and more.
Key Built-in Functions in Matplotlib:
Matplotlib has a module called pyplot which is commonly used. Below are some important built-in functions from the
matplotlib.pyplot module:
Function Description
plot() Draws a line graph based on x and y values.
xlabel() Adds a label to the x-axis.
ylabel() Adds a label to the y-axis.
title() Adds a title to the graph.
grid() Displays grid lines on the graph.
legend() Shows the legend when multiple plots are used.
show() Displays the final output graph window.
figure() Creates a new figure for plotting multiple graphs.
bar() Used to create bar charts.
hist() Creates histogram plots.
scatter() Plots a scatter plot using x and y coordinates.
Python Program to Create a Simple Line Graph:
# Import the pyplot module from matplotlib
import matplotlib.pyplot as plt

# Define x and y coordinates


x = [1, 2, 3, 4, 5]
y = [2, 4, 1, 8, 7]

# Create a line plot


plt.plot(x, y, color='blue', marker='o', linestyle='--', label='Data Line')

# Add labels and title


plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Simple Line Graph')

# Add grid and legend


plt.grid(True)
plt.legend()

# Show the graph


plt.show()
Explanation of the Code:
 plt.plot() – plots a line graph connecting points (x, y).
 color='blue', marker='o', linestyle='--' – optional arguments to customize the graph.
 xlabel() and ylabel() – label the axes.
 title() – gives the graph a heading.
 grid(True) – displays background grid lines.
 legend() – shows the label in the graph.
 show() – displays the final graphical output.
Y-axis
^
| o
| o -- Dashed line connects all points
| o
|
|
| o
|
| o
+---------------------------------> X-axis
1 2 3 4 5
2. Write a Python program to create and manipulate a NumPy array with mathematical operations.
Introduction to NumPy:
NumPy (Numerical Python) is a powerful Python library used for numerical computing. It provides support for
multi-dimensional arrays and many mathematical functions to operate on arrays efficiently.
Features of NumPy:
 Fast and memory-efficient operations
 Vectorized computations (no need for loops)
 Supports broadcasting
 Provides functions for linear algebra, statistical operations, and more
Python Program to Create and Manipulate a NumPy Array:
import numpy as np

# Creating a 1D NumPy array


arr = np.array([10, 20, 30, 40, 50])
print("Original Array:", arr)

# Basic Mathematical Operations


print("Array + 5:", arr + 5) # Add 5 to each element
print("Array * 2:", arr * 2) # Multiply each element by 2
print("Array squared:", arr ** 2) # Square of each element

# Statistical operations
print("Sum of elements:", np.sum(arr))
print("Mean of array:", np.mean(arr))
print("Max value:", np.max(arr))
print("Min value:", np.min(arr))

# Create a 2D NumPy array


arr2 = np.array([[1, 2], [3, 4]])
print("2D Array:\n", arr2)

# Matrix multiplication
result = np.dot(arr2, arr2)
print("Matrix multiplication result:\n", result)

# Transpose of the array


print("Transpose of 2D array:\n", np.transpose(arr2))
Explanation of the Code:
 np.array(): Creates NumPy arrays (1D and 2D).
 arr + 5: Adds 5 to every element (vectorized operation).
 arr * 2: Multiplies every element by 2.
 arr ** 2: Squares every element in the array.
 np.sum() / np.mean(): Performs statistical calculations.
 np.dot(): Used for matrix multiplication.
 np.transpose(): Transposes rows and columns in a 2D array.
Sample Output:
Original Array: [10 20 30 40 50]
Array + 5: [15 25 35 45 55]
Array * 2: [ 20 40 60 80 100]
Array squared: [ 100 400 900 1600 2500]
Sum of elements: 150
Mean of array: 30.0
Max value: 50
Min value: 10
2D Array:
[[1 2]
[3 4]]
Matrix multiplication result:
[[ 7 10]
[15 22]]
Transpose of 2D array:
[[1 3]
[2 4]]

3. Write a Python program to create a Pandas DataFrame using a 2D list and perform basic data
manipulations.
Introduction to Pandas:
Pandas is a powerful data analysis and manipulation library in Python. It provides two primary data structures:
 Series – one-dimensional labeled array
 DataFrame – two-dimensional labeled table (like Excel)
A DataFrame is similar to a table with rows and columns.
Python Program: Create DataFrame from a 2D list and manipulate it
import pandas as pd

# Step 1: Create a 2D list


data = [
[101, 'Alice', 85],
[102, 'Bob', 90],
[103, 'Charlie', 78],
[104, 'David', 92]
]

# Step 2: Define column names


columns = ['ID', 'Name', 'Marks']

# Step 3: Create DataFrame


df = pd.DataFrame(data, columns=columns)
print("Original DataFrame:")
print(df)

# Step 4: Add a new column


df['Grade'] = ['B', 'A', 'C', 'A']
print("\nDataFrame after adding 'Grade' column:")
print(df)

# Step 5: Filter students with Marks > 80


high_scorers = df[df['Marks'] > 80]
print("\nStudents with Marks > 80:")
print(high_scorers)

# Step 6: Update a value


df.loc[df['Name'] == 'Charlie', 'Marks'] = 88
print("\nDataFrame after updating Charlie's marks:")
print(df)

# Step 7: Sort by Marks


sorted_df = df.sort_values(by='Marks', ascending=False)
print("\nDataFrame sorted by Marks (descending):")
print(sorted_df)
Explanation of Code:
 pd.DataFrame() – creates the DataFrame using a 2D list and column names
 df['Grade'] = ... – adds a new column
 df[df['Marks'] > 80] – filters rows using a condition
 df.loc[...] = ... – updates a specific value
 sort_values() – sorts the DataFrame based on a column
Sample Output:
Original DataFrame:
ID Name Marks
0 101 Alice 85
1 102 Bob 90
2 103 Charlie 78
3 104 David 92

DataFrame after adding 'Grade' column:


ID Name Marks Grade
0 101 Alice 85 B
1 102 Bob 90 A
2 103 Charlie 78 C
3 104 David 92 A

Students with Marks > 80:


ID Name Marks Grade
0 101 Alice 85 B
1 102 Bob 90 A
3 104 David 92 A

DataFrame after updating Charlie's marks:


ID Name Marks Grade
0 101 Alice 85 B
1 102 Bob 90 A
2 103 Charlie 88 C
3 104 David 92 A

DataFrame sorted by Marks (descending):


ID Name Marks Grade
3 104 David 92 A
1 102 Bob 90 A
2 103 Charlie 88 C
0 101 Alice 85 B

4. Explain the use of Matplotlib, write a Python program for plotting a histogram using Matplotlib.
Introduction to Matplotlib:
Matplotlib is a widely used Python library for creating visualizations like line charts, bar graphs, scatter plots,
histograms, pie charts, and more.
It helps in visualizing large data sets in an understandable and insightful way.
The commonly used module in Matplotlib is matplotlib.pyplot, which provides simple functions to plot different types
of graphs.
Uses of Matplotlib:
 To plot line charts, bar charts, and histograms
 To analyze trends and patterns in data
 To visualize scientific and statistical results
 Supports labels, legends, grids, and multiple plots
 Works well with NumPy and Pandas
Histogram:
A histogram is used to represent the distribution of numerical data. It shows how data is grouped into bins or
intervals.
Python Program to Plot a Histogram Using Matplotlib:
import matplotlib.pyplot as plt

# Sample data
marks = [55, 67, 78, 90, 45, 62, 73, 80, 85, 50, 65, 70, 88, 92, 60]

# Create histogram
plt.hist(marks, bins=5, color='skyblue', edgecolor='black')

# Add title and axis labels


plt.title("Student Marks Distribution")
plt.xlabel("Marks Range")
plt.ylabel("Number of Students")

# Show the plot


plt.show()
Explanation of Code:
 plt.hist() – creates the histogram
o marks – data to be plotted
o bins=5 – divides the range into 5 intervals
o color and edgecolor – improve readability
 title(), xlabel(), ylabel() – add context to the graph
 show() – displays the histogram
Sample Output (Graph Description):
 X-axis: Ranges of marks (e.g., 40–55, 56–70, etc.)
 Y-axis: Number of students in each range
 Each bar shows how many students fall in that range
 A light blue histogram with black edges is displayed
5. Explain the uses of Pandas and mention the data structures supported by Pandas.
Introduction to Pandas:
Pandas is a popular Python library used for data analysis and manipulation. It provides flexible and easy-to-use
data structures for handling structured data like tables, time series, and labeled datasets.
Pandas is built on top of NumPy, and integrates well with Matplotlib, SciPy, and other data science tools.
Uses of Pandas:
Use Case Description
Data Cleaning Handle missing data, filter rows, drop duplicates
Use Case Description
Data Transformation Modify data (add/remove columns, apply functions)
Data Analysis Grouping, aggregation, statistics
Data Import/Export Read from or write to CSV, Excel, SQL, JSON, etc.
Data Visualization Simple plotting using .plot()
Handling Time Series Date/time indexing, resampling, time-shifted data

Example Uses:
 Reading data from a CSV file: pd.read_csv("data.csv")
 Displaying top 5 rows: df.head()
 Filtering rows: df[df['age'] > 30]
 Calculating average: df['marks'].mean()
Data Structures Supported by Pandas:
Pandas supports two core data structures:
1. Series:
 A one-dimensional labeled array
 Can store any data type (int, float, string, etc.)
 Similar to a single column in a spreadsheet
Example:
import pandas as pd
s = pd.Series([10, 20, 30, 40])
2. DataFrame:
 A two-dimensional labeled data structure (rows and columns)
 Similar to an Excel sheet or SQL table
 Most commonly used structure in Pandas
Example:
data = {'Name': ['Alice', 'Bob'], 'Marks': [85, 90]}
df = pd.DataFrame(data)

Difference Between Series and DataFrame:


Feature Series DataFrame
Dimension 1D 2D
Structure Single column Rows and columns
Example Student marks Student details (name, marks, ID)

6. What is Tkinter in Python? Explain its importance in GUI programming with an example.
What is Tkinter?
Tkinter is the standard GUI (Graphical User Interface) library for Python.
It provides tools to create windows, buttons, text fields, menus, and other GUI components in desktop applications.
Tkinter is built on the Tcl/Tk GUI toolkit and comes pre-installed with Python, so no extra installation is required.

Importance of Tkinter in GUI Programming:


Feature Description
Ease of Use Beginner-friendly and simple syntax
Cross-platform Works on Windows, Linux, and macOS
Rich Widgets Provides buttons, labels, entries, frames, menus, etc.
Customizable GUI layout, font, color, and size can be modified easily
Event-driven Responds to user actions like clicks, inputs, etc.
Feature Description
Educational Use Widely used to teach GUI basics in Python

Common Tkinter Widgets:


 Label – Display text
 Button – Clickable button
 Entry – Single-line text input
 Text – Multi-line text box
 Frame – Container for grouping widgets
 Canvas – Drawing shapes and images
Example Program Using Tkinter:
import tkinter as tk

# Create the main window


window = tk.Tk()
window.title("Simple GUI Example")
window.geometry("300x200")

# Create a label
label = tk.Label(window, text="Welcome to Tkinter!", font=("Arial", 14))
label.pack(pady=10)

# Create a button
def say_hello():
label.config(text="Hello, Python GUI!")

button = tk.Button(window, text="Click Me", command=say_hello)


button.pack(pady=10)

# Start the GUI event loop


window.mainloop()
Explanation of Code:
 tk.Tk() – Initializes the main window
 Label() – Displays a message
 Button() – Creates a button and links it to a function (say_hello)
 pack() – Layout manager to place widgets
 mainloop() – Keeps the window open and listens for user actions
Output (GUI Window):
 A window titled “Simple GUI Example”
 A label saying “Welcome to Tkinter!”
 A button labeled “Click Me”
 When clicked, the label changes to “Hello, Python GUI!”
7. Write a Python program using Tkinter to create a Student Mark Sheet GUI application.
Objective:
To create a GUI application using Tkinter that allows a user to enter a student's name, roll number, and marks in three
subjects. The program calculates and displays the total, average, and result (Pass/Fail).
Python Program:
import tkinter as tk

def calculate():
try:
m1 = float(entry_mark1.get())
m2 = float(entry_mark2.get())
m3 = float(entry_mark3.get())

total = m1 + m2 + m3
avg = total / 3
result = "Pass" if m1 >= 35 and m2 >= 35 and m3 >= 35 else "Fail"

label_total.config(text=f"Total: {total}")
label_avg.config(text=f"Average: {avg:.2f}")
label_result.config(text=f"Result: {result}")
except ValueError:
label_result.config(text="Please enter valid marks!")

# Main window
window = tk.Tk()
window.title("Student Mark Sheet")
window.geometry("350x350")

# Labels and Entry Widgets


tk.Label(window, text="Student Name").pack()
entry_name = tk.Entry(window)
entry_name.pack()

tk.Label(window, text="Roll Number").pack()


entry_roll = tk.Entry(window)
entry_roll.pack()

tk.Label(window, text="Mark 1").pack()


entry_mark1 = tk.Entry(window)
entry_mark1.pack()

tk.Label(window, text="Mark 2").pack()


entry_mark2 = tk.Entry(window)
entry_mark2.pack()

tk.Label(window, text="Mark 3").pack()


entry_mark3 = tk.Entry(window)
entry_mark3.pack()

# Button to calculate result


tk.Button(window, text="Calculate", command=calculate).pack(pady=10)

# Output Labels
label_total = tk.Label(window, text="Total: ")
label_total.pack()

label_avg = tk.Label(window, text="Average: ")


label_avg.pack()

label_result = tk.Label(window, text="Result: ")


label_result.pack()

# Run the window


window.mainloop()
Explanation of the Program:
 The program uses Tkinter widgets like Label, Entry, and Button.
 calculate() is a function that:
o Fetches the entered marks
o Calculates total and average
o Displays "Pass" if all marks are ≥ 35; otherwise "Fail"
 .pack() is used to arrange widgets vertically.
 mainloop() keeps the GUI window running.
Output:
 A GUI form appears where the user can enter:
o Student Name
o Roll Number
o 3 Subject Marks
 On clicking "Calculate", it displays:
o Total Marks
o Average Marks
o Result (Pass/Fail)
8. Explain about packages and their advantages with an example.
What is a Package in Python?
In Python, a package is a collection of modules (files containing Python code) organized in a directory hierarchy.
Packages allow you to organize related modules into a folder structure, making the codebase cleaner, more
manageable, and reusable.
A module is a single file of Python code, while a package is a directory that can contain multiple modules and sub-
packages.
Advantages of Using Packages:
Advantage Explanation
Code Organization Packages help to organize large codebases into smaller, manageable modules.
Reusability Once a package is created, it can be reused across multiple projects without modification.
Namespace Packages help avoid naming conflicts by grouping related modules under a common
Management namespace.
Packages can be extended by adding new modules, making the code scalable and easier to
Scalability
maintain.
Namespace Control With packages, you can control the scope of your module's functions and classes.
Improved Teams can work on different parts of a project in separate packages, making collaboration
Collaboration easier.

Structure of a Package:
A package is typically represented as a directory with an __init__.py file (which makes Python treat the directory as a
package). It can contain modules and sub-packages.
Example structure:
markdown
CopyEdit
my_package/

├── __init__.py
├── module1.py
├── module2.py
└── sub_package/
├── __init__.py
└── sub_module.py

Example: Creating and Using a Package


Let's create a simple package that contains two modules: math_operations.py and string_operations.py.
1. Create the Package Structure:
my_package/

├── __init__.py
├── math_operations.py
└── string_operations.py
2. Code for math_operations.py:
# math_operations.py
def add(a, b):
return a + b

def subtract(a, b):


return a - b
3. Code for string_operations.py:
# string_operations.py
def concatenate(str1, str2):
return str1 + str2

def reverse_string(s):
return s[::-1]
4. Using the Package in Main Program:
# main.py
from my_package import math_operations, string_operations

# Using math_operations module


sum_result = math_operations.add(10, 5)
print(f"Sum: {sum_result}")

# Using string_operations module


concatenated_result = string_operations.concatenate("Hello", " World")
print(f"Concatenated String: {concatenated_result}")
Explanation of the Code:
 my_package/ is the directory that contains the package.
 __init__.py makes Python treat the directory as a package (can be empty or contain initialization code).
 math_operations.py and string_operations.py are the modules that are part of the package.
 The main.py file demonstrates how to import and use functions from the package using from my_package
import module_name.
Sample Output:
Sum: 15
Concatenated String: Hello World
9. Discuss NumPy features and usages with an example.
What is NumPy?
NumPy (Numerical Python) is an open-source library used for numerical computing in Python. It provides support
for large, multi-dimensional arrays and matrices, along with a collection of mathematical functions to operate on these
arrays. NumPy is widely used in data science, machine learning, scientific computing, and engineering for high-
performance operations on data.
Features of NumPy:
Feature Explanation
Feature Explanation
NumPy provides a powerful ndarray object for multi-dimensional arrays, which is more
Efficient Array Objects
efficient than Python’s native list or tuple.
Supports element-wise operations (e.g., addition, multiplication) on entire arrays without
Vectorized Operations
using explicit loops, making operations faster and more concise.
Mathematical Provides a wide range of mathematical operations, such as linear algebra, Fourier
Functions transform, and statistical functions.
Allows NumPy arrays of different shapes to work together in operations (e.g., adding a
Broadcasting
scalar to all elements of an array).
Integration with Other Can be integrated with libraries like Pandas, SciPy, and Matplotlib for data analysis,
Libraries statistical operations, and visualization.
NumPy arrays take up less memory compared to standard Python lists, as the data is stored
Memory Efficiency
in contiguous blocks of memory.
Random Number NumPy has a sub-module (numpy.random) that is used for generating random numbers and
Generation performing random sampling.

Usage of NumPy:
1. Creating Arrays:
NumPy arrays can be created from Python lists, or using built-in functions like np.array(), np.zeros(), and np.ones().
import numpy as np

# Create a 1D array from a list


arr = np.array([1, 2, 3, 4])
print("1D Array:", arr)

# Create a 2D array using a list of lists


arr_2d = np.array([[1, 2, 3], [4, 5, 6]])
print("2D Array:")
print(arr_2d)

# Create an array of zeros


zeros = np.zeros((3, 3))
print("3x3 Zeros Array:")
print(zeros)

# Create an array of ones


ones = np.ones((2, 4))
print("2x4 Ones Array:")
print(ones)
2. Array Operations:
NumPy supports element-wise arithmetic and mathematical operations on arrays.
# Array addition
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
result = arr1 + arr2
print("Addition:", result)

# Array multiplication
result = arr1 * arr2
print("Multiplication:", result)
# Element-wise square root
result = np.sqrt(arr1)
print("Square Root:", result)
3. Indexing and Slicing:
You can access or modify elements in a NumPy array using indexing and slicing techniques.
# Accessing an element
print("Element at index 1:", arr[1])

# Slicing the array (Get first two elements)


print("Sliced Array:", arr[:2])
4. Statistical Operations:
NumPy provides functions for computing basic statistics.
python
CopyEdit
# Mean, median, standard deviation
print("Mean:", np.mean(arr))
print("Median:", np.median(arr))
print("Standard Deviation:", np.std(arr))
5. Reshaping and Resizing:
NumPy arrays can be reshaped without changing their data.
# Reshaping an array
reshaped = arr_2d.reshape((3, 2))
print("Reshaped Array:")
print(reshaped)
6. Matrix Operations:
NumPy has built-in functions for performing matrix operations such as dot product, matrix multiplication, etc.
# Matrix multiplication (dot product)
matrix1 = np.array([[1, 2], [3, 4]])
matrix2 = np.array([[5, 6], [7, 8]])
dot_product = np.dot(matrix1, matrix2)
print("Matrix Dot Product:")
print(dot_product)
Example Program:
Let's create a simple NumPy-based program that calculates the total sales for each product in a store based on the
quantity sold and price, and displays the results.
import numpy as np

# Data: quantity sold and price per unit for 3 products


quantities = np.array([50, 30, 70]) # Quantities sold
prices = np.array([20, 15, 10]) # Price per unit

# Calculate total sales for each product


total_sales = quantities * prices
print("Total Sales for Each Product:", total_sales)

# Calculate the total sales for all products


total_sales_sum = np.sum(total_sales)
print("Total Sales for All Products:", total_sales_sum)

# Calculate the average sales


average_sales = np.mean(total_sales)
print("Average Sales:", average_sales)
Output:
Total Sales for Each Product: [1000 450 700]
Total Sales for All Products: 2150
Average Sales: 716.6666666666666

10. Explain the use of built-in functions from the Matplotlib package and write a Python program to create a
simple pie chart.
What is Matplotlib?
Matplotlib is a widely-used library in Python for creating static, animated, and interactive visualizations. It
provides tools for generating a variety of plots, such as line charts, bar charts, histograms, pie charts, and more. The
most commonly used module in Matplotlib is pyplot, which provides simple plotting functionality.
Built-in Functions in Matplotlib:
Here are some important built-in functions available in Matplotlib, specifically from the matplotlib.pyplot module:
Function Description
plot() Used to plot data on a 2D line graph.
scatter() Used to create a scatter plot of data points.
bar() Used to create a bar chart.
hist() Used to create a histogram to display the distribution of data.
pie() Creates a pie chart to represent proportions of a whole.
show() Displays the plot on the screen.
title() Sets the title of the plot.
xlabel() Sets the label for the x-axis.
ylabel() Sets the label for the y-axis.
legend() Adds a legend to the plot.
xlim() / ylim() Sets the limits for the x-axis and y-axis.
grid() Displays grid lines on the plot.

Creating a Pie Chart:


The pie() function in Matplotlib is used to create pie charts. Pie charts are circular charts where each slice represents a
proportion of the whole.
Syntax:
matplotlib.pyplot.pie(data, labels=None, colors=None, autopct=None, startangle=None, radius=None)
Parameter Description
data A sequence of numerical values (sizes of slices).
labels Labels for each slice.
colors List of colors for the slices.
autopct String or function to format the percentage display.
startangle The angle at which the first slice will be drawn.
radius Radius of the pie chart.

Example Program to Create a Pie Chart:


Let's write a simple program that creates a pie chart representing the market share of different mobile brands.
import matplotlib.pyplot as plt

# Data for the pie chart (market share of different mobile brands)
labels = ['Apple', 'Samsung', 'Huawei', 'Xiaomi', 'Others']
sizes = [40, 30, 15, 10, 5] # Market share in percentage
colors = ['gold', 'yellowgreen', 'lightcoral', 'lightskyblue', 'lightgreen']
explode = (0.1, 0, 0, 0, 0) # "Explode" the first slice (Apple)

# Create a pie chart


plt.pie(sizes, labels=labels, colors=colors, autopct='%1.1f%%', startangle=140, explode=explode)

# Set the title of the pie chart


plt.title("Market Share of Mobile Brands")

# Display the pie chart


plt.show()
Explanation of the Code:
 labels: A list containing the names of mobile brands.
 sizes: The corresponding market share for each brand in percentage.
 colors: A list of colors to represent each slice.
 explode: This tuple is used to "explode" a slice, i.e., make it stand out. The first slice (Apple) is exploded by
setting its value to 0.1.
 autopct='%1.1f%%': This formats the display of the percentage value inside each slice to one decimal place.
 startangle=140: Rotates the pie chart to start at a specific angle.
 plt.title(): Sets the title for the chart.
 plt.show(): Displays the pie chart on the screen.
Output:
The pie chart will look something like this:
 A circle divided into slices, each slice representing a mobile brand.
 The slice for Apple will be slightly "exploded" outwards.
 The percentage value for each slice will be shown inside the chart.
PART – C (15 MARKS)
1. Discuss the various widgets available in Tkinter with an example.
Introduction to Tkinter Widgets:
In Tkinter, widgets are elements that allow you to interact with the graphical user interface (GUI). Widgets provide an
interface for user input or display information. Tkinter offers a wide range of widgets to create functional and
interactive applications. Some commonly used widgets include buttons, labels, entries, checkboxes, radio buttons, and
more.
List of Common Tkinter Widgets and Their Usage:
1. Label
o A Label widget is used to display text or images.
o It does not allow the user to interact with it, just for showing information.
Example:
import tkinter as tk
root = tk.Tk()
label = tk.Label(root, text="Hello, Tkinter!")
label.pack()
root.mainloop()
2. Button
o The Button widget is used to display a clickable button that can trigger an event or function when
clicked.
Example:
def on_click():
print("Button Clicked!")

root = tk.Tk()
button = tk.Button(root, text="Click Me", command=on_click)
button.pack()
root.mainloop()
3. Entry
o The Entry widget is used to create a text input box where users can type in data (single-line input).
Example:
def show_input():
entered_text = entry.get()
label.config(text=f"You entered: {entered_text}")

root = tk.Tk()
label = tk.Label(root, text="Enter something:")
label.pack()

entry = tk.Entry(root)
entry.pack()

button = tk.Button(root, text="Show Input", command=show_input)


button.pack()

root.mainloop()
4. Text
o The Text widget is used for multi-line text input or output. It supports rich text formatting like
changing font and color.
Example:
root = tk.Tk()
text_widget = tk.Text(root, height=5, width=30)
text_widget.pack()
text_widget.insert(tk.END, "This is a Text Widget\nYou can type multiple lines here.")
root.mainloop()
5. Checkbutton
o The Checkbutton widget is used to create a checkbox. It allows the user to select one or more
options.
Example:
def show_check_value():
value = var.get()
label.config(text=f"Checkbox is {'checked' if value else 'unchecked'}")

root = tk.Tk()
var = tk.IntVar()
checkbutton = tk.Checkbutton(root, text="Accept Terms and Conditions", variable=var,
command=show_check_value)
checkbutton.pack()

label = tk.Label(root)
label.pack()

root.mainloop()
6. Radiobutton
o The Radiobutton widget is used to create a set of mutually exclusive options (radio buttons). Only
one radio button can be selected at a time in a group.
Example:
def show_selected_option():
selection = var.get()
label.config(text=f"You selected option {selection}")
root = tk.Tk()
var = tk.IntVar()

radiobutton1 = tk.Radiobutton(root, text="Option 1", variable=var, value=1,


command=show_selected_option)
radiobutton1.pack()

radiobutton2 = tk.Radiobutton(root, text="Option 2", variable=var, value=2,


command=show_selected_option)
radiobutton2.pack()

label = tk.Label(root)
label.pack()

root.mainloop()
7. Listbox
o The Listbox widget is used to create a list of items where users can select one or more items.
Example:
def show_selection(event):
selection = listbox.curselection()
label.config(text=f"You selected: {listbox.get(selection)}")

root = tk.Tk()
listbox = tk.Listbox(root)
listbox.pack()

items = ["Apple", "Banana", "Orange", "Grapes"]


for item in items:
listbox.insert(tk.END, item)

listbox.bind("<<ListboxSelect>>", show_selection)

label = tk.Label(root)
label.pack()

root.mainloop()
8. Scale
o The Scale widget is used to create a slider, allowing the user to select a value from a range.
Example:
def show_scale_value(val):
label.config(text=f"Selected value: {val}")

root = tk.Tk()
scale = tk.Scale(root, from_=0, to=100, orient=tk.HORIZONTAL, command=show_scale_value)
scale.pack()

label = tk.Label(root)
label.pack()

root.mainloop()
9. Scrollbar
o The Scrollbar widget is used to add scrolling functionality to a widget, such as a listbox, text widget,
or canvas.
Example:
root = tk.Tk()
text_widget = tk.Text(root, height=5, width=30)
text_widget.pack(side=tk.LEFT)

scrollbar = tk.Scrollbar(root, command=text_widget.yview)


scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
text_widget.config(yscrollcommand=scrollbar.set)
root.mainloop()

10. Canvas
 The Canvas widget is used for drawing shapes, images, and other graphical elements.
Example:
root = tk.Tk()
canvas = tk.Canvas(root, width=400, height=400)
canvas.pack()

# Draw a line
canvas.create_line(50, 50, 350, 350)

# Draw a rectangle
canvas.create_rectangle(100, 100, 300, 200)

# Draw an oval
canvas.create_oval(100, 250, 300, 350)

root.mainloop()
11. Menu
 The Menu widget is used to create menus in an application, such as dropdown menus, which can contain
multiple items.
Example:
def hello():
print("Hello, Tkinter!")
root = tk.Tk()
menu_bar = tk.Menu(root)
root.config(menu=menu_bar)
file_menu = tk.Menu(menu_bar, tearoff=0)
menu_bar.add_cascade(label="File", menu=file_menu)
file_menu.add_command(label="Hello", command=hello)
file_menu.add_separator()
file_menu.add_command(label="Exit", command=root.quit)
root.mainloop()

2. Write a python program to create a Pandas series using NumPy and perform basic operations on it.
import pandas as pd
import numpy as np

# Step 1: Create a NumPy array


data = np.array([10, 20, 30, 40, 50])

# Step 2: Create a Pandas Series using the NumPy array


series = pd.Series(data)

# Display the created series


print("Created Pandas Series:")
print(series)

# Step 3: Perform basic operations

# 1. Accessing elements (get the element at index 2)


element_at_index_2 = series[2]
print("\nElement at index 2:", element_at_index_2)

# 2. Adding a constant value to each element of the series


series_plus_5 = series + 5
print("\nSeries after adding 5 to each element:")
print(series_plus_5)

# 3. Multiplying the series by a constant value


series_multiplied_by_2 = series * 2
print("\nSeries after multiplying each element by 2:")
print(series_multiplied_by_2)

# 4. Getting the mean of the series


mean_value = series.mean()
print("\nMean of the series:", mean_value)

# 5. Getting the sum of the series


sum_value = series.sum()
print("\nSum of the series:", sum_value)

# 6. Apply a function to the series (square each element)


squared_series = series.apply(lambda x: x**2)
print("\nSeries after squaring each element:")
print(squared_series)

# Step 4: Adding a custom index to the series


custom_index = ['A', 'B', 'C', 'D', 'E']
custom_series = pd.Series(data, index=custom_index)
print("\nSeries with custom index:")
print(custom_series)

Explanation of the Code:


Creating a NumPy Array:
The code first creates a NumPy array data containing five elements: [10, 20, 30, 40, 50].

Creating a Pandas Series:


A Pandas Series is created using pd.Series(data), where data is the NumPy array.

Performing Basic Operations:

 Accessing elements: You can access individual elements of the Series using indexing, for example, series[2]
returns the element at index 2.
 Arithmetic operations: The Series is manipulated using basic arithmetic operations like addition (series + 5)
and multiplication (series * 2).
 Statistical operations: The mean() function calculates the mean of the series, and sum() calculates the sum of
all elements.
 Applying functions: You can apply a custom function (like squaring each element) using the apply() method.
 Custom Indexing: A custom index (['A', 'B', 'C', 'D', 'E']) is applied to the Series to make it more meaningful.

Output:
Created Pandas Series:
0 10
1 20
2 30
3 40
4 50
dtype: int64

Element at index 2: 30
Series after adding 5 to each element:
0 15
1 25
2 35
3 45
4 55
dtype: int64

Series after multiplying each element by 2:


0 20
1 40
2 60
3 80
4 100
dtype: int64

Mean of the series: 30.0


Sum of the series: 150
Series after squaring each element:
0 100
1 400
2 900
3 1600
4 2500
dtype: int64

Series with custom index:


A 10
B 20
C 30
D 40
E 50
dtype: int64

You might also like