Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Python unit 5

The document covers Python packages, highlighting their structure, benefits, and popular libraries like Matplotlib, NumPy, and Pandas. It explains how to create and use packages, as well as provides examples of data visualization and manipulation techniques. Additionally, it discusses GUI development with Tkinter and various Integrated Development Environments (IDEs) for Python programming.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Python unit 5

The document covers Python packages, highlighting their structure, benefits, and popular libraries like Matplotlib, NumPy, and Pandas. It explains how to create and use packages, as well as provides examples of data visualization and manipulation techniques. Additionally, it discusses GUI development with Tkinter and various Integrated Development Environments (IDEs) for Python programming.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

Python Programming

Unit-5 One Shot


(BCC302 / BCC402/ BCC302H / BCC402H)
Python Packages

Multi Atoms Plus


Unit-5 Aktu Updated Syllabus

Multi Atoms Plus


Python Packages
A Python package is a collection of modules bundled together. These modules can
include functions, classes, and variables that can be used in your Python programs.
Packages help to organize and structure code, making it more modular, reusable, and
maintainable.

Key Concepts:
1. Module: A single file containing Python code (functions, classes, variables, etc.)
with a .py extension.
2. Package: A directory containing multiple modules and an __init__.py file, which
makes it a package. The __init__.py file can be empty or execute initialization code
for the package.

Multi Atoms Plus


Creating a Package
1. Directory Structure:

2. module1.py:

3. module2.py:

Multi Atoms Plus


4. __init__.py:

Using the Package

Multi Atoms Plus


Benefits of Using Packages
1. Modularity: Break down large programs into smaller, manageable, and reusable
modules.
2. Namespace Management: Avoid name conflicts by organizing code into separate
namespaces.
3. Reusability: Easily reuse code across different projects.
4. Maintainability: Easier to manage and maintain code.

Multi Atoms Plus


Popular Python Packages
Matplotlib: For creating static, animated, and interactive visualizations.

Numpy: For numerical computations and operations on large arrays and matrices.

Pandas: For data manipulation and analysis.

Requests: For making HTTP requests.

Installing Packages
Use pip, the Python package installer, to install packages from the Python Package
Index (PyPI).

Multi Atoms Plus


Introduction to Matplotlib
Matplotlib is a comprehensive library for creating static, animated, and interactive
visualizations in Python. It is widely used for data visualization in scientific computing,
data science, and machine learning.

Installation

Multi Atoms Plus


Types of Matplotlib
1. Line Plot - Displays data trends over time.
2. Scatter Plot - Shows relationships between variables.
3. Bar Chart - Compares categorical data values.
4. Histogram - Represents data distribution frequencies.
5. Pie Chart - Illustrates proportions of a whole.
6. Box Plot - Summarizes data distribution quartiles.
7. Violin Plot - Displays data distribution and density.
8. Heatmap - Visualizes matrix-like data with color.
9. Area Plot - Fills the area under a curve.
10. 3D Plot - Represents three-dimensional data visually.
11. Subplots - Multiple plots in one figure.
Multi Atoms Plus
Matplotlib Pyplot
Most of the Matplotlib utilities lies under the pyplot submodule, and are usually
imported under the plt alias: import matplotlib.pyplot as plt
Now the Pyplot package can be referred to as plt.
import matplotlib.pyplot as plt
import numpy as np
xpoints = np.array([0, 6])
ypoints = np.array([0, 250])
plt.plot(xpoints, ypoints)
plt.show()

Multi Atoms Plus


Line plot with Matplotlib:
A line plot in Matplotlib is used to display data points connected by straight lines. It's
particularly useful for showing trends over time or continuous data.

Multi Atoms Plus


Customizations
Line Color:

Use color names (e.g., 'blue'), hex codes (e.g., '#FF5733'), or RGB tuples (e.g., (0.1, 0.2,
0.5)).

Markers:

Types include '.' (point), 'o' (circle), 's' (square), '^' (triangle), etc.

Multi Atoms Plus


Bar plot with Matplotlib
A bar plot (or bar chart) in Matplotlib is used to display categorical data with
rectangular bars. Each bar's length represents the value of the category it represents.

Multi Atoms Plus


Horizontal Bar Plot:

Multi Atoms Plus


Scatter plot with Matplotlib
A scatter plot in Matplotlib is used to display the relationship between two variables by
plotting data points on a Cartesian plane. Each point represents a pair of values from
two datasets.

Multi Atoms Plus


pie chart with Matplotlib:
A pie chart in Matplotlib is used to display data as slices of a circle, representing
proportions of a whole. Each slice corresponds to a category and its size represents the
proportion of that category relative to the total.

Multi Atoms Plus


area plot in Matplotlib
An area plot in Matplotlib is used to display data where the area under a line is filled
in, making it easy to visualize cumulative totals or the relative size of different
categories over time.

Multi Atoms Plus


NumPy
NumPy is a fundamental library for numerical computing in Python. It provides
support for arrays, matrices, and a wide range of mathematical functions to operate on
these data structures.

Key Features of NumPy


N-dimensional Arrays:
numpy.array(): Creates arrays for efficient storage and manipulation of numerical data.
Mathematical Functions:
Functions for mathematical operations, including addition, subtraction, multiplication, and
complex functions like trigonometric functions.
Array Operations:
Operations like element-wise addition, multiplication, and other mathematical operations on
arrays.
Multi Atoms Plus
Linear Algebra:

Functions for linear algebra operations such as dot products, matrix multiplication,
and eigenvalue decomposition.

Random Number Generation:

Functions to generate random numbers and distributions.

Array Manipulation:

Functions for reshaping, slicing, and aggregating data.

Multi Atoms Plus


Example Output

Multi Atoms Plus


Pandas
Pandas is a powerful data manipulation and analysis library for Python. It provides data
structures like DataFrames and Series that make it easy to handle and analyze large
datasets. Pandas is especially useful for working with tabular data and provides a
variety of functions to clean, transform, and analyze data.

Core Features of Pandas


Data Structures:

Series: A one-dimensional labeled array that can hold any data type.

DataFrame: A two-dimensional labeled data structure with columns of potentially different data
types.
Multi Atoms Plus
Creating Data Structures
# Creating a Series
s = pd.Series([1, 2, 3, 4, 5], name='numbers')
print(s)
# Creating a DataFrame
df = pd.DataFrame({
'A': [1, 2, 3],
'B': ['a', 'b', 'c'],
'C': [4.5, 5.5, 6.5]
})
print(df) Multi Atoms Plus
Data Manipulation:

Indexing and Selection: Accessing and manipulating data using labels and
integer-based indexing.

1. Indexing and Selection using Labels (loc): Accessing data using labels.

Multi Atoms Plus


Multi Atoms Plus
Filtering: Methods for filtering

Multi Atoms Plus


Data Cleaning:

Handling Missing Data: Functions for detecting, filling, and dropping missing values.

Data Transformation: Tools for reshaping and transforming data.

Multi Atoms Plus


Multi Atoms Plus
Data Input/Output:

Reading/Writing Data: Functions for reading from and writing to various file formats including CSV, Excel

1. Reading CSV Files: Using pd.read_csv() to read data from a CSV file.

2. Reading Excel Files: Using pd.read_excel() to read data from an Excel file.

Multi Atoms Plus


The to_csv('output.csv', index=False) function writes the DataFrame df to the
CSV file output.csv. The index=False parameter ensures that the row indices
are not written to the file.

Multi Atoms Plus


What is a GUI in Python?
A Graphical User Interface (GUI) in Python is a visual interface that allows users to
interact with the application through graphical elements like windows, buttons, text
fields, and other widgets, rather than using text-based commands. GUIs make
applications user-friendly and visually appealing.

Python offers several libraries to create GUIs, with Tkinter being the most commonly
used due to its simplicity and integration with Python's standard library. Other popular
GUI frameworks include PyQt, Kivy, and wxPython.

Multi Atoms Plus


Multi Atoms Plus
Explanation
1. Import the Tkinter module:
This imports the Tkinter module and makes it available
in the script.
2. Define the function to update the label:
This function retrieves the text from the entry widget
and updates the label widget with a greeting.
3. Create the main window:
● tk.Tk() creates the main window.
● root.title("Simple GUI Example") sets the title of
the window.
● root.geometry("300x200") sets the size of the
window.

Multi Atoms Plus


4. Create and pack the label widget:
● tk.Label(root, text="Enter your name:") creates a
label widget with the specified text.
● label.pack(pady=10) adds the label to the window
with some padding.
5. Create and pack the entry widget:
● tk.Entry(root) creates an entry widget for text
input.
● entry.pack(pady=5) adds the entry widget to the
window with some padding.
6. Create and pack the button widget:
● tk.Button(root, text="Submit",
command=update_label) creates a button widget
that calls the update_label function when clicked.

● button.pack(pady=10) adds the button to the


window with some padding.

Multi Atoms Plus


7. Run the main event loop:

This starts the Tkinter event loop, which waits


for user interactions and updates the GUI
accordingly.

Multi Atoms Plus


Common Tkinter Widgets with Examples and Definitions
Tkinter provides a variety of widgets to create interactive GUI applications. Here are
some of the common Tkinter widgets along with their definitions and examples:

1. Button: A Button widget is used to display a clickable button that can trigger a
function or event when clicked.

● tk.Button(root, text="Click Me", command=on_button_click): Creates a button with the


text "Click Me" that calls the on_button_click function when clicked.
● button.pack(): Adds the button to the window.

Multi Atoms Plus


2. Label: A Label widget is used to display text or images on the screen.

● tk.Label(root, text="This is a label"): Creates a label with the text "This is a label".
● label.pack(): Adds the label to the window.

Multi Atoms Plus


3. Entry: An Entry widget is used to create a single-line text input field.

● tk.Entry(root): Creates a single-line text input field.


● entry.pack(): Adds the entry field to the window.

Multi Atoms Plus


4. Text: A Text widget is used to create a multi-line text input field.

● tk.Text(root): Creates a multi-line text input field.


● text.pack(): Adds the text field to the window.

Multi Atoms Plus


5. Checkbutton (Checkbox): A Checkbutton widget is used to create a checkbox
that can be toggled on or off.

● checkbox_var = tk.IntVar(): Creates an integer variable to hold the state of the


checkbox (1 for checked, 0 for unchecked).
● tk.Checkbutton(root, text="Check me", variable=checkbox_var): Creates a
checkbox with the text "Check me" linked to the checkbox_var variable.
● checkbox.pack(): Adds the checkbox to the window.

Multi Atoms Plus


Simple Calculator Using Tkinter
import tkinter as tk
add_button = tk.Button(root, text="Add", command=add)
def add(): add_button.pack()
result.set(float(entry1.get()) + float(entry2.get()))
subtract_button = tk.Button(root, text="Subtract",
def subtract(): command=subtract)
result.set(float(entry1.get()) - float(entry2.get())) subtract_button.pack()

def multiply(): multiply_button = tk.Button(root, text="Multiply",


result.set(float(entry1.get()) * float(entry2.get())) command=multiply)
multiply_button.pack()
def divide():
result.set(float(entry1.get()) / float(entry2.get())) divide_button = tk.Button(root, text="Divide",
command=divide)
root = tk.Tk() divide_button.pack()
root.title("Simple Calculator")
root.mainloop()
entry1 = tk.Entry(root)
entry1.pack()

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

result = tk.DoubleVar()
result_label = tk.Label(root, textvariable=result)
result_label.pack()
Multi Atoms Plus
1. Import Tkinter Module:

2. Define Functions:

This function retrieves the values from entry1 and entry2, adds
them, and sets the result in the result variable.

Multi Atoms Plus


3. Create Main Window:

This creates the main window of the application and sets its title to "Simple Calculator".

4. Create Entry Widgets:

Creates the second entry widget for user input and adds it to the window.

5. Create Variable for Result:

This creates a Tkinter DoubleVar to hold the result of the calculations.

6. Create Result Label:

This creates a label that displays the result of the calculation. The label's text is bound to the result variable.

Multi Atoms Plus


7. Create Buttons:

8. Run the Main Event Loop:

This starts the Tkinter event loop, which waits for user interactions and updates the GUI accordingly.

Multi Atoms Plus


Python Programming with IDE (Integrated Development Environment)
An Integrated Development Environment (IDE) is a software application that provides
comprehensive facilities to computer programmers for software development. An IDE typically
includes a source code editor, build automation tools, and a debugger. Here are some popular
IDEs for Python programming and their key features:

1. PyCharm: Developed by JetBrains, PyCharm is a powerful and widely-used IDE for Python. It
comes in two versions: Community (free) and Professional (paid).

● Intelligent Code Editor: Code completion, real-time error checking, and quick fixes.
● Debugging and Testing: Integrated debugger and test runner.
● Version Control: Supports Git, SVN and more.
● Web Development: Supports Django, Flask, and other web frameworks.

Multi Atoms Plus


2. Visual Studio Code (VS Code): A lightweight, open-source code editor developed by
Microsoft, with extensive Python support through extensions.

● Extensible: Rich ecosystem of extensions, including Python support.


● Debugging: Built-in debugger.
● Integrated Terminal: Access to the terminal within the editor.
● Version Control: Built-in Git support.

3. Spyder: An open-source IDE specifically designed for scientific computing and data analysis,
often used with Anaconda distribution.

● Integrated IPython Console: Enhanced interactive Python shell.


● Editor: Syntax highlighting, code completion, and introspection.
● Documentation Viewer: Built-in help system.
● Plotting: Inline plotting with Matplotlib support.

Multi Atoms Plus


2. Visual Studio Code (VS Code): A lightweight, open-source code editor developed by
Microsoft, with extensive Python support through extensions.

● Extensible: Rich ecosystem of extensions, including Python support.


● Debugging: Built-in debugger.
● Integrated Terminal: Access to the terminal within the editor.
● Version Control: Built-in Git support.

3. Spyder: An open-source IDE specifically designed for scientific computing and data analysis,
often used with Anaconda distribution.

● Integrated IPython Console: Enhanced interactive Python shell.


● Editor: Syntax highlighting, code completion, and introspection.
● Documentation Viewer: Built-in help system.
● Plotting: Inline plotting with Matplotlib support.

Multi Atoms Plus


IDEs that support Python development
● PyCharm ● Eric Python IDE
● Visual Studio Code ● Rodeo
● Spyder ● Anaconda Navigator
● Jupyter Notebook ● IDLE
● Atom ● Geany
● Sublime Text ● NetBeans with Python Plugin
● Eclipse with PyDev ● Pyzo
● Thonny ● Bluefish
● Wing IDE ● Emacs with Python Mode
● Komodo IDE ● IntelliJ IDEA with Python Plugin

Multi Atoms Plus


Thank You
Please Subscribe Multi Atoms & Multi Atoms Plus
Join Telegram Channel for Notes
All the Best for your Exams

Multi Atoms Plus

You might also like