[go: up one dir, main page]

0% found this document useful (0 votes)
2K views34 pages

Unit 5-Python Packages 240127 185930

The document discusses Python programming using various packages and GUI programming using Tkinter. It provides an overview of packages like NumPy, Matplotlib and Pandas for scientific computing and data analysis. It describes how to import and use basic functions from these packages to create arrays, plots and dataframes. The document also introduces Tkinter for GUI programming in Python and provides examples to create simple windows and widgets.

Uploaded by

bhaviyatalwar18
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)
2K views34 pages

Unit 5-Python Packages 240127 185930

The document discusses Python programming using various packages and GUI programming using Tkinter. It provides an overview of packages like NumPy, Matplotlib and Pandas for scientific computing and data analysis. It describes how to import and use basic functions from these packages to create arrays, plots and dataframes. The document also introduces Tkinter for GUI programming in Python and provides examples to create simple windows and widgets.

Uploaded by

bhaviyatalwar18
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/ 34

Unit 5 :Python Programming (BCC-302)

Department of CSE, ABES, Institute of


Technology, GZB
UNIT V
• Python Packages
• Simple Programs Using Built-in function of Packages
– NumPy
– Matplotlib
– Pandas

• GUI Programming
– Tkinter Introduction,
– Tkinter and Python Programming
– Tk widgets
– Tkinter Example

• Python Programming with IDE


Python Packages
• A package is a container that contains various functions to
perform specific tasks.
For example, the math package includes the sqrt() function
to perform the square root of a number.
• While working on big projects, we have to deal with a large
amount of code, and writing everything together in the same
file will make our code look messy.
• Instead, we can separate our code into multiple files by
keeping the related code together in packages.
• Now, we can use the package whenever we need it in our
projects. This way we can also reuse our code.
Package Model Structure
• Suppose we are developing a game. One possible
organization of packages and modules could be as
shown in the figure below
---Continue
Note: A directory must contain a file named __init__.py in order
for Python to consider it as a package. This file can be left empty
but we generally place the initialization code for that package in
this file
Importing Module from a Package
• In Python, we can import modules from packages using the dot
(.) operator.
For example, if we want to import the start module in the
above example, it can be done as follows:
import game.Level.start
• Now, if this module contains
a function named select_difficulty(), we must use the full
name to reference it.
game.Level.start.select_difficulty(2)
---Continue
Import Without Package Prefix
• If this construct seems lengthy, we can import the module
without the package prefix as follows:
from Game.Level import start
• We can now call the function simply as follows:
start.selectdifficulty(2)
Import Required Functionality Only
• Another way of importing just the required function (or class or
variable) from a module within a package would be as follows:
from game.Level.start import select_difficulty
• Now we can directly call this function.
select_difficulty(2)
Basic Programs using in-built functions of
Packages in Python
 NumPy
 Matplotlib
 Pandas
NumPy in Python

 NumPy is a Python library used for working with


arrays.
 It also has functions for working in domain of linear
algebra, Fourier transform, and matrices.
 NumPy was created in 2005 by Travis Oliphant. It is an
open source project and you can use it freely.
 Although list is used as substitute for array but numpy
airway is 50 times faster than list in processing.
--Continue
Numpy Installation
Install numpy before using it
Importing NumPy
import numpy
Using Alias: We can use short notation for
numpy called alias.
import numpy as np # np is alias for numpy
#We can access functionality of numpy using np
---Continue
• array() function: Used to create ndarray. Numpy array
is called ndarray
• Creating 0-D array
import numpy as np
arr=np.array(5)
print(arr) # Output 5
print (arr.ndim) # Output 0

• Creating 1-D array


import numpy as np
arr=np.array([1,2,3,4,5])
print(arr) # Output [1,2,3,4,5]
print(arr.dim) # Output 0
---Continue
• Creating 2-D array
import numpy as np
arr=np.array([[1,2],[3,4]])
print(arr)
print (“dimension ->”,arr.ndim)
# Output
[[1 2]
[3 4] ]
Dimension->2
---Continue

• Creating 3-D array


import numpy as np
arr=np.array([[[1,2,3],[2,3,4]], ([[1,2,3],[2,3,4]]])
print(arr)
Output
[[[1 2 3]
[2 3 4]
[ [1 2 3]
[2 3 4]]]
In the same way n-dimetioal array can be created/
Indexing
Indexing of ndarray starts at 0 and goes to
length-1.
Example :
import numpy as np
arr=np.array([1,2,3,4])
print(arr[0]) # print 1 element at index 0
arr1=np.array([[1,2],[2,2]])
print(arr1[1,1]) # print 2 element at index (1,1)
Array are mutable

import numpy as np
arr=np.array([1,2,3,4])
arr[1]=5
print(arr) # print [1 5 3 4]
print(type(arr)) # print <class 'numpy.ndarray'>
# slicing
print(arr[0:3]) # print [1 5 3]
arange() function
Converts number in given range to array
import numpy as np
arr=np.arange(0,5)
print(arr) print [0 1 2 3 4]
print(arr.shape) print (4,)
arr=np.array([[1,2],[2,2]])
print(arr.shape) print (2,2)

# shape tells element in each dimention


reshape() function
This function change shape of array. Number element
should same in both original and reshaped array
otherwise it will generate error
import numpy as np
arr=np.array([[1,2],[2,2]])
x=np.reshape(arr,4)
print(x) #print [ 1 2 2 2]
# 3-d array converted to 1-D array
ones() function create array of ones
arr=np.ones(5)
print(arr) #print [ 1 1 1 1 1]
Matplotlib
• Matplotlib is a low level graph plotting library in
python that serves as a visualization utility.
• Matplotlib was created by John D. Hunter.
• Matplotlib is open source and we can use it freely.
• Matplotlib is mostly written in python, a few
segments are written in C, Objective-C and Javascript
for Platform compatibility.
Installation of Matplotlib
• If you have Python and PIP already installed on a
system, then installation of Matplotlib is very easy.
• The command is
C:\Users\Your Name>pip install matplotlib
Import Matplotlib
• Once Matplotlib is installed, import it in your
applications by adding the import module statement:
import matplotlib
• Since most of functionality of matplotlib library is
found in sub-package pyplot so we use
import matplotlib.pyplot as plt
• plt is alias for matplotlib.pyplot
Draw a line in a diagram from position (0,0) to position (6,250)
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()
# Output
Creating Barchart
import matplotlib.pyplot as plt
import numpy as np
x = np.array(["A", "B", "C", "D"])
y = np.array([3, 8, 1, 10])
plt.bar(x,y) # bar () creates barchart
plt.show()
# Output
Creating Pie Chart
import matplotlib.pyplot as plt
import numpy as np
y = np.array([35, 25, 25, 15])
plt.pie(y) # Create Pie Chart of ndarray y
plt.show()
# Output
Pandas
• Pandas is a Python library used for working with data sets.
• It has functions for analyzing, cleaning, exploring, and manipulating data.
• The name "Pandas" has a reference to both "Panel Data", and "Python
Data Analysis" and was created by Wes McKinney in 2008.

Installation of Pandas

• If you have Python and PIP already installed on a system, then installation
of Pandas is very easy.
• Install it using this command:
C:\Users\Your Name>pip install pandas

• If this command fails, then use a python distribution that already has
Pandas installed like, Anaconda, Spyder etc.
Import Pandas
• Once Pandas is installed, import it in your applications by
adding the import keyword:
Import pandas as pd # pd is alias for pandas
dataset = { 'cars': ["BMW", "Volvo", "Ford"], 'passings': [3, 7, 2]}
var1 = pd.DataFrame(ataset, index=['Row 1','Row 2','Row 3'])
print(var1)
# Output
cars passings
Row 1 BMW 3
Row 2 Volvo 7
Row 3 Ford 2
DataFrame-Explanation
A Data frame is a two-dimensional data structure, i.e., data is
aligned in a tabular fashion in rows and columns.
Features of DataFrame
• Potentially columns are of different types
• Size – Mutable
• Labeled axes (rows and columns)
• Can Perform Arithmetic operations on rows and
columns
The syntax of creating a DataFrame object is:
pandas.DataFrame(Data, index, columns, dtype, copy)
 Data: It can be represented as series, list, dictionary, constant
or other DataFrames.
 index: For the row labels, the index to be used for the
resulting frame is optional. The default value is displayed from
0 to n-1.
 columns: For column labels, The optional default syntax is :
np.arange(n).
 dtype: It is the data type of each column. If no data type is
defined. None is applied.
 copy: This command is used for copying data if the default is
false.
Series() method
• Pandas Series is a one-dimensional labeled array capable of holding
data of any type (integer, string, float, python objects, etc.).
import pandas as pd
# simple array
data = [1, 2, 3, 4]
ser = pd.Series(data)
print(ser)
# Output
01
12
23
34
dtype: int64
GUI Programming
Tkinter Introduction :
 Tkinter is an open source, portable graphical user interface (GUI)
toolkit designed for use in Python scripts.
 „Tkinter is a python interface for the Tk GUI toolkit (originally
developed for the Tcl language)
Advantages offered by Tkinter
 „Layered implementation
 „Accessibility
 „Portability
 „Availability
Drawback of Tkinter
 „ Due to the layered approach used in its implementation,
execution speed becomes a concern.
Tkinter and Python Programming
# install tkinter before use program executed on pycharm IDE
# Basic Program
from tkinter import *
root = Tk( )
root.title("A simple application") # Displays title on the title bar of window
root.mainloop( )
# Output
Tkinter and Python Programming
from tkinter import * : Imports everything from tkinter library
Tk( ):
In order to create a tkinter application, we generally create an
instance of tkinter frame, i.e., Tk().
It helps to display the root window and manages all the other
components of the tkinter application.
We can initialize the tkinter instance by assigning the variable
to it
mainloop():
mainloop() is used when your application is ready to run.
 mainloop() is an infinite loop used to run the application, wait
for an event to occur and process the event as long as the
window is not closed.
Tkinter and Python Programming
# We can place graphical components on the window like label,
button etc
from tkinter import *
root = Tk( )
root.title("A simple application")
# Creating Label
label=Label(root, text="Python Label", font=('Courier 20
underline'))
label.pack() # Adding Label to root window
# Creating button
button = Button(root, text="Press")
# Adding button
button.pack()
root.mainloop( )
Output
Tk widgets

 Tkinter’s components are called Widgets


 Widgets are equivalents to OOP’s objects or components
 All widgets inherit from the Widget class
Widget Options
 Options are attributes of the widget.
 Not all widgets have the same attributes.
 Some which are common to all widgets such as ‘text’, specifying
the text to be displayed, or ‘Padx’, which specifies the space
between itself and its neighbor widget.
 Other options like ‘wrap’ for a text widget or ‘orient’ for a
scrollbar widget are widget specific.
Widget Types
Toplevel
Frame
Label
Button
Entry
Radiobutton
Checkbutton
Menu
Message
Text
Scrollbar
Listbox
Scale
Canvas
Working With Python IDE
• Already discussed in begning about working
with IDLE.
• Other popular IDE are pycharm and spyder tou
can work with

You might also like