Unit 5
Unit 5
(Unit 5)
V Python packages: Simple programs using the built-in functions of packages matplotlib, numpy,
pandas etc. GUI Programming: Tkinter introduction, Tkinter and PythonProgramming, Tk Widgets,
Tkinter examples. Python programming with IDE. 04
Python Package
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.
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.
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)
If this construct seems lengthy, we can import the module without the package prefix as follows:
start.select_difficulty(2)
Another way of importing just the required function (or class or variable) from a module within a
package would be as follows:
select_difficulty(2)
Although easier, this method is not recommended. Using the full namespace avoids confusion and
prevents two same identifier names from colliding.
While importing packages, Python looks in the list of directories defined in sys.path, similar as
for module search path.
Simple programs using the built-in functions of packages matplotlib, numpy, pandas etc:
Built-in functions are pre-defined in the programming language‟s library for the programming to
directly call the functions wherever required in the program for achieving certain functional
operations. A few of the frequently used built-in functions in Python programs are abs(x) for fetching
the absolute value of x, bin() for getting the binary value, bool() for retrieving the boolean value of an
object, list() for lists, len() to get the length of the value, open() to open the files, pow() for returning
the power of a number, sum() for fetching the sum of the elements, reversed() for reversing the order,
etc.
Matplotlib is a Python library that helps in visualizing and analyzing the data and helps in better
understanding of the data with the help of graphical, pictorial visualizations that can be simulated
using the matplotlib library. Matplotlib is a comprehensive library for static, animated and
interactive visualizations.
Installation of matplotlib library
Step 1: Open command manager (just type “cmd” in your windows start search bar) Step 2: Type
the below command in the terminal.
cd Desktop
Step 3: Then type the following command.
pip install matplotlib
Creating a Simple Plot
Python3
# x axis values
x = [1,2,3]
# corresponding y axis values
y = [2,4,1]
it helps to get access over the all the four axes of the
gca()
graph
Note: Try removing the features added one by one and understand how does the output result
changes Example 1:
Python3
a = [1, 2, 3, 4, 5]
b = [0, 0.6, 0.2, 15, 10, 8, 16, 21]
plt.plot(a)
plt.show()
Output:
Example 2:
Python3
a = [1, 2, 3, 4, 5]
b = [0, 0.6, 0.2, 15, 10, 8, 16, 21]
c = [4, 2, 6, 8, 3, 20, 13, 15]
sub1.plot(a, 'sb')
sub2.plot(b, 'or')
sub4.plot(c, 'Dm')
NumPy is a powerful library for scientific computing in Python that provides a multidimensional
array object and a wide range of tools for working with these arrays. It is widely used in fields such as
data analysis, machine learning, and scientific computing. In this article, we will be discussing
NumPy functions in Python, which are essential for the efficient and effective manipulation of
NumPy arrays.
NumPy functions are built-in functions provided by the NumPy library that operate on NumPy arrays.
These functions are designed to efficiently process large amounts of data and perform complex
calculations on multidimensional arrays. NumPy functions are designed to work with NumPy arrays
and offer superior performance compared to traditional Python functions.
The syntax of NumPy functions in Python typically follows the following structure:
numpy.function_name(array, parameters)
where "function_name" is the name of the NumPy function, "array" is the NumPy array on which the
function is to be applied, and "parameters" are any additional parameters required by the function.
NumPy functions in Python take one or more arrays as input and can also accept additional
parameters that modify their behavior. The parameters of NumPy functions depend on the specific
function being used. Here are some common parameters:
axis: This parameter specifies the axis along which the function is applied. It is an optional parameter
and its default value is None. If axis is set to None, the function will be applied to the entire array.
dtype: This parameter specifies the data type of the returned array. It is an optional parameter and its
default value is None. If dtype is set to None, the data type of the returned array will be the same as
the input array.
out: This parameter specifies the output array where the result of the function will be stored. It is an
optional parameter and its default value is None. If out is set to None, the function will create a new
array to store the result.
keepdims: This parameter specifies whether to keep the dimensions of the input array in the output
array. It is an optional parameter and its default value is False. If keepdims is set to True, the
dimensions of the output array will be the same as the input array. If keepdims is set to False, the
dimensions of the output array will be reduced by one.
The return value of a NumPy function in Python depends on the specific function being used. Some
NumPy functions return a new array with the calculated results, while others modify the original array
in place. However, some NumPy functions have optional output parameters such as the „out‟
parameter. These functions allow you to specify an output array where the result will be stored. In this
case, the return value will be a reference to the output array rather than a new array.
Here are some of the important NumPy functions in Python which every Data scientist must know:
Example Code:
import numpy as np
print(arr)
Output:
[1 2 3]
Explanation: In this example, we created a numpy array by passing a list of 3 numbers as a parameter
into np.array() function.
Example Code:
import numpy as np
arr = np.arange(1, 6)
print(arr)
Output:
[1 2 3 4 5]
Explanation: In this example, we created a numpy array with a range of values which is (1,6), where
6 is excluded.
Example Code:
import numpy as np
arr = np.zeros(3)
print(arr)
Output:
[0. 0. 0.]
Explanation: In this example, we created an array of size 3 which is filled with only zeroes.
Example Code:
import numpy as np
arr = np.ones(3)
print(arr)
Output:
[1. 1. 1.]
Explanation: In this example, we created an array of size 3 which is filled with only ones.
5. np.linspace(): This function is used to create an array with a specified number of evenly spaced
values.
Example Code:
import numpy as np
arr = np.linspace(0, 1, 5)
print(arr)
Output:
6. np.random.rand(): This function is used to create an array with random values between 0 and 1.
Example Code:
import numpy as np
arr = np.random.rand(3)
print(arr)
Output:
Explanation: In this example, we created an array of size 3 which is filled with random values which
lie between 0 and 1.
7. np.random.randint(): This function is used to create an array with random integer values between
a specified range.
Example Code:
import numpy as np
arr = np.random.randint(0, 10, 5)
print(arr)
Output:
[1 5 8 9 8]
Explanation: In this example, we created an array of size 5 which is filled with random values which
lie between 0 and 10.
Example Code:
import numpy as np
max_value = np.max(arr)
print(max_value)
Output:
Explanation: In this example, we used max() function to find the max element in our array, which is
3 in this case.
Example Code:
import numpy as np
min_value = np.min(arr)
print(min_value)
Output:
Explanation: In this example, we used min() function to find the min element in our array, which is 1
in this case.
10. np.mean(): This function is used to find the mean value of an array.
Example Code:
import numpy as np
mean_value = np.mean(arr)
print(mean_value)
Output:
2.0
11. np.median(): This function is used to find the median value of an array.
Example Code:
import numpy as np
median_value = np.median(arr)
print(median_value)
Output:
2.0
12. np.dot(): This function is used to find the dot product of two arrays.
Example Code:
import numpy as np
print(dot_product)
Output:
32
Explanation: In this example, we created two NumPy arrays called array1 and array2, which contain
the values [1, 2, 3] and [4, 5, 6], respectively. We then used np.dot() to calculate the dot product of
these two arrays, which is equal to 14 + 25 + 3*6, or 32. The resulting value is stored in the variable
result and printed to the console.
Summary
Here‟s a summary of the article on NumPy functions in Python:
NumPy is a Python library for numerical computing that provides powerful data structures and
functions for scientific computing tasks.
NumPy arrays are the primary data structure used in NumPy, and they can be one-dimensional or
multi-dimensional.
NumPy functions are used to create, manipulate, and analyze NumPy arrays.
The syntax of NumPy functions generally involves calling the function and passing one or more
parameters, such as the shape of the array, the range of values to generate, or the type of data to use.
The return value of NumPy functions can be an array, a scalar value, or a tuple of values.
Some important NumPy functions include np.array(), np.arange(), np.zeros(), np.ones(), np.linspace(),
and np.random.rand().
These functions can be used to create NumPy arrays with specific shapes, ranges of values, and data
types.
NumPy functions are powerful tools for data analysis and scientific computing, and they are essential
for many applications in fields such as physics, engineering, and data science.
Here are some frequently asked questions about NumPy functions in Python:
Q1 – What is the difference between a view and a copy in NumPy?
Ans – A view is a shallow copy of an array that shares the same memory as the original array.
Changes made to a view will also affect the original array. A copy, on the other hand, is a deep copy
of an array that creates a new array with its own memory. Changes made to a copy will not affect the
original array.
Q3 – Can NumPy be used with other Python libraries like Pandas and Matplotlib?
Ans – Yes, NumPy can be used in conjunction with other Python libraries like Pandas and Matplotlib.
Pandas use NumPy arrays for their data structures, and Matplotlib uses NumPy arrays for plotting
data.
Python Pandas:
The term "Pandas" refers to an open-source library for manipulating high-performance data in Python.
This instructional exercise is intended for the two novices and experts.
It was created in 2008 by Wes McKinney and is used for data analysis in Python. Pandas is an open-
source library that provides high-performance data manipulation in Python. All of the basic and
advanced concepts of Pandas, such as Numpy, data operation, and time series, are covered in our
tutorial.
Pandas Introduction
The name of Pandas is gotten from the word Board Information, and that implies an Econometrics
from Multi-faceted information. It was created in 2008 by Wes McKinney and is used for data
analysis in Python.
Processing, such as restructuring, cleaning, merging, etc., is necessary for data analysis. Numpy,
Scipy, Cython, and Panda are just a few of the fast data processing tools available. Yet, we incline
toward Pandas since working with Pandas is quick, basic and more expressive than different
apparatuses.
Since Pandas is built on top of the Numpy bundle, it is expected that Numpy will work with Pandas.
Before Pandas, Python was able for information planning, however it just offered restricted help for
information investigation. As a result, Pandas entered the picture and enhanced data analysis
capabilities. Regardless of the source of the data, it can carry out the five crucial steps that are
necessary for processing and analyzing it: load, manipulate, prepare, model, and analyze.
o It has a DataFrame object that is quick and effective, with both standard and custom indexing.
o Utilized for reshaping and turning of the informational indexes.
o For aggregations and transformations, group by data.
o It is used to align the data and integrate the data that is missing.
o Provide Time Series functionality.
o Process a variety of data sets in various formats, such as matrix data, heterogeneous tabular
data, and time series.
o Manage the data sets' multiple operations, including subsetting, slicing, filtering, groupBy,
reordering, and reshaping.
o It incorporates with different libraries like SciPy, and scikit-learn.
o Performs quickly, and the Cython can be used to accelerate it even further.
Benefits of Pandas
Representation of Data: Through its DataFrame and Series, it presents the data in a manner that is
appropriate for data analysis.
Clear code: Pandas' clear API lets you concentrate on the most important part of the code. In this
way, it gives clear and brief code to the client.
DataFrame and Series are the two data structures that Pandas provides for processing data. These data
structures are discussed below:
1) Series
A one-dimensional array capable of storing a variety of data types is how it is defined. The term
"index" refers to the row labels of a series. We can without much of a stretch believer the rundown,
tuple, and word reference into series utilizing "series' technique. Multiple columns cannot be included
in a Series. Only one parameter exists:
Before creating a Series, Firstly, we have to import the numpy module and then use array() function in
the program.
1. import pandas as pd
2. import numpy as np
3. info = np.array(['P','a','n','d','a','s'])
4. a = pd.Series(info)
5. print(a)
Output
0 P
1 a
2 n
3 d
4 a
5 s
dtype: object
Explanation: In this code, firstly, we have imported the pandas and numpy library with
the pd and np alias. Then, we have taken a variable named "info" that consist of an array of some
values. We have called the info variable through a Series method and defined it in an "a" variable.
The Series has printed by calling the print(a) method.
It is a generally utilized information design of pandas and works with a two-layered exhibit with
named tomahawks (lines and segments). As a standard method for storing data, DataFrame has two
distinct indexes-row index and column index. It has the following characteristics:
It can be thought of as a series structure dictionary with indexed rows and columns. It is referred to as
"columns" for rows and "index" for columns.
1. import pandas as pd
2. # a list of strings
3. x = ['Python', 'Pandas']
4. # Calling DataFrame constructor on list
5. df = pd.DataFrame(x)
6. print(df)
Output
0
0 Python
1 Pandas
Python Tkinter:
Tkinter tutorial provides basic and advanced concepts of Python Tkinter. Our Tkinter tutorial is
designed for beginners and professionals.
Python provides the standard library Tkinter for creating the graphical user interface for desktop
based applications.
Developing desktop based applications with python Tkinter is not a complex task. An empty Tkinter
top-level window can be created by using the following steps.
Example
1. # !/usr/bin/python3
2. from tkinter import *
3. #creating the application main window.
4. top = Tk()
5. #Entering the event main loop
6. top.mainloop()
Output:
Tkinter widgets
There are various widgets like button, canvas, checkbutton, entry, etc. that are used to build the
python GUI applications.
SN Widget Description
1 Button The Button is used to add various kinds of buttons to the python application.
2 Canvas The canvas widget is used to draw the canvas on the window.
4 Entry The entry widget is used to display the single-line text field to the user. It is commonly used
accept user values.
5 Frame It can be defined as a container to which, another widget can be added and organized.
6 Label A label is a text used to display some message or information about the other widgets.
7 ListBox The ListBox widget is used to display a list of options to the user.
8 Menubutton The Menubutton is used to display the menu items to the user.
10 Message The Message widget is used to display the message-box to the user.
11 Radiobutton The Radiobutton is different from a checkbutton. Here, the user is provided with various opti
and the user can select only one option among them.
13 Scrollbar It provides the scrollbar to the user so that the user can scroll the window up and down.
14 Text It is different from Entry because it provides a multi-line text field to the user so that the user
write the text and edit the text inside it.
18 MessageBox This module is used to display the message-box in the desktop based applications.
The Tkinter geometry specifies the method by using which, the widgets are represented on display.
The python Tkinter provides the following geometry methods.
The pack() widget is used to organize widget in the block. The positions widgets added to the python
application using the pack() method can be controlled by using the various options specified in the
method call.
However, the controls are less and widgets are generally added in the less organized manner.
syntax
1. widget.pack(options)
o expand: If the expand is set to true, the widget expands to fill any space.
o Fill: By default, the fill is set to NONE. However, we can set it to X or Y to determine
whether the widget contains any extra space.
o size: it represents the side of the parent to which the widget is to be placed on the window.
Example
1. # !/usr/bin/python3
2. from tkinter import *
3. parent = Tk()
4. redbutton = Button(parent, text = "Red", fg = "red")
5. redbutton.pack( side = LEFT)
6. greenbutton = Button(parent, text = "Black", fg = "black")
7. greenbutton.pack( side = RIGHT )
8. bluebutton = Button(parent, text = "Blue", fg = "blue")
9. bluebutton.pack( side = TOP )
10. blackbutton = Button(parent, text = "Green", fg = "red")
11. blackbutton.pack( side = BOTTOM)
12. parent.mainloop()
Output:
The grid() geometry manager organizes the widgets in the tabular form. We can specify the rows and
columns as the options in the method call. We can also specify the column span (width) or
rowspan(height) of a widget.
This is a more organized way to place the widgets to the python application. The syntax to use the
grid() is given below.
Syntax
1. widget.grid(options)
A list of possible options that can be passed inside the grid() method is given below.
o Column
The column number in which the widget is to be placed. The leftmost column is represented
by 0.
o Columnspan
The width of the widget. It represents the number of columns up to which, the column is
expanded.
o ipadx, ipady
It represents the number of pixels to pad the widget inside the widget's border.
o padx, pady
It represents the number of pixels to pad the widget outside the widget's border.
o row
The row number in which the widget is to be placed. The topmost row is represented by 0.
o rowspan
The height of the widget, i.e. the number of the row up to which the widget is expanded.
o Sticky
If the cell is larger than a widget, then sticky is used to specify the position of the widget
inside the cell. It may be the concatenation of the sticky letters representing the position of the
widget. It may be N, E, W, S, NE, NW, NS, EW, ES.
Example
1. # !/usr/bin/python3
2. from tkinter import *
3. parent = Tk()
4. name = Label(parent,text = "Name").grid(row = 0, column = 0)
5. e1 = Entry(parent).grid(row = 0, column = 1)
6. password = Label(parent,text = "Password").grid(row = 1, column = 0)
7. e2 = Entry(parent).grid(row = 1, column = 1)
8. submit = Button(parent, text = "Submit").grid(row = 4, column = 0)
9. parent.mainloop()
Output:
Syntax
1. widget.place(options)
o Anchor: It represents the exact position of the widget within the container. The default value
(direction) is NW (the upper left corner)
o bordermode: The default value of the border type is INSIDE that refers to ignore the parent's
inside the border. The other option is OUTSIDE.
o height, width: It refers to the height and width in pixels.
o relheight, relwidth: It is represented as the float between 0.0 and 1.0 indicating the fraction
of the parent's height and width.
o relx, rely: It is represented as the float between 0.0 and 1.0 that is the offset in the horizontal
and vertical direction.
o x, y: It refers to the horizontal and vertical offset in the pixels.
Example
1. # !/usr/bin/python3
2. from tkinter import *
3. top = Tk()
4. top.geometry("400x250")
5. name = Label(top, text = "Name").place(x = 30,y = 50)
6. email = Label(top, text = "Email").place(x = 30, y = 90)
7. password = Label(top, text = "Password").place(x = 30, y = 130)
8. e1 = Entry(top).place(x = 80, y = 50)
9. e2 = Entry(top).place(x = 80, y = 90)
10. e3 = Entry(top).place(x = 95, y = 130)
11. top.mainloop()
Output:
Python programming with IDE: The term "IDE" refers for "Integrated Development
Environment," which is a coding tool that aids in automating the editing, compiling, testing, and other
steps of an SDLC while making it simple for developers to execute, write, and debug code.
It is specifically made for software development and includes a number of tools that are used in the
creation and testing of the software.
o PyCharm
o Spyder
o PyDev
o Atom
o Wing
o Jupyter Notebook
o Thonny
o Rodeo
o Microsoft Visual Studio
o Eric
PyCharm
The Jet Brains created PyCharm, a cross-platform Integrated Development Environment (IDE)
created specifically for Python. It is the most popular IDE and is accessible in both a premium and a
free open-source version. By handling everyday duties, a lot of time is saved.
It is a full-featured Python IDE with a wealth of features including auto code completion, easy project
navigation, quick error checking and correction, support for remote development, database
accessibility, etc.
Features
o Smart code navigation
o Errors Highlighting
o Powerful debugger
o Supports Python web development frameworks, i.e., Angular JS, Javascript
Spyder
Spyder is a well-known open-source IDE that is best suited for data research and has a high level of
recognition in the industry. Scientific Python Development Environment is Spyder's full name. It
supports all popular operating systems, including Windows, MacOS X, and Linux.
A number of features are offered by it, including a localised code editor, a document viewer, a
variable explorer, an integrated console, etc. It also supports a number of scientific modules, including
SciPy and NumPy.
Features
o Proper syntax highlighting and auto code completion
o Integrates strongly with IPython console
o Performs well in multi-language editor and auto code completion mode
PyDev
As an external plugin for Eclipse, PyDev is one of the most popular Python IDEs. The Python
programmers who have a background in Java naturally gravitate towards this Python interpreter
because it is so well-liked by users.
In 2003-2004, Aleksandar Totic, who is well known for his work on the Mosaic browser, contributed
to the Pydev project.
Django integration, code auto-completion, smart and block indents, among other features, are features
of Pydev.
Features
o Strong Parameters like refactoring, debugging, code analysis, and code coverage function.
o It supports virtual environments, Mypy, and black formatter.
o Also supports PyLint integration, remote debugger, Unit test integration, etc.
Atom
ADVERTISEMENT
GitHub, a company that was first founded as an open-source, cross-platform project, is the company
that creates Atom. It is built on the Electron framework, which enables cross-platform desktop
applications utilising Chromium and Node.js and is dubbed the "Hackable Text Editor for the 21st
Century."
Features
o Visualize the results on Atom without open any other window.
o A plugin named "Markdown Preview Plus" provides built-in support for editing and
visualizing Markdown files.
Wing
It's described as a cross-platform IDE with a tonne of useful features and respectable development
support. It is free to use in its personal edition. The 30-day trial period for the pro version is provided
for the benefit of the developers.
Features
o Customizable and can have extensions as well.
o Supports remote development, test-driven development along with the unit test.
Jupyter Notebook
Jupyter is one of the most used Python notebook editors that is used across the Data Science industry.
You can create and edit notebook documents using this web application, which is based on the server-
client architecture. It utilises Python's interpretive nature to its fullest potential.
Features
o Supports markdowns
o Easy creation and editing of codes
o Ideal for beginners in data science
Thonny
Thonny is a Python IDE (Integrated Development Environment) that is open-source, free, and geared
towards beginners. Since its initial release in 2016, it has grown to be a well-liked option for novice
Python coders.
Thonny's user-friendly interface is one of its most distinguishing qualities. It makes it simple for
beginners to learn Python and debug their programmes because it incorporates a code editor,
debugger, and REPL (Read-Eval-Print-Loop) in a single window. To assist users with writing proper
code, Thonny also has tools like code completion, syntax highlighting, and error highlighting.
Thonny IDE that works well for teaching and learning programming is Thonny. Software that
highlights syntax problems and aids code completion was created at the University of Tartu.
Features
o Simple debugger
o Supports highlighting errors and auto code completion
Rodeo
When it comes to gathering data and information from many sources for data science projects, Rodeo
is considered one of the top Python IDEs.
Features
o Allows the functions for comparing data, interact, plot, and inspect data.
o Auto code completion, syntax highlighter, visual file navigator, etc.
Microsoft Visual Studio is an open-source code editor which was best suited for development and
debugging of latest web and cloud projects. It has its own marketplace for extensions.
An integrated development environment (IDE) called Microsoft Visual Studio is used to create
software for the Windows, Android, and iOS operating systems. Since its initial release in 1997, it has
grown to be a well-liked software development tool.
Code editing, debugging, and code analysis are just a few of the capabilities and tools that are
included in the IDE. It supports a variety of programming languages, including Python, C++, C#,
Visual Basic, and others. Additionally, Microsoft Visual Studio comes with a variety of project
templates that make it simpler for developers to get started on their projects right away.
Microsoft Visual Studio 2022, the most recent release, comes with new features like improved
debugging and testing capabilities, improved Git integration, and a revamped user interface. The
enhanced performance of the IDE makes it quicker and more effective to construct complicated
software projects.
Features
o Supports Python Coding in Visual studio
o Available in both paid and free version
Eric Python
The Eric Python is a Python-based editor that may be used for both professional and non-professional
tasks.
Since its initial release in 2000, Eric IDE (Integrated Development Environment) has been a free and
open-source Python IDE. It offers programmers a setting in which to efficiently write, test, and debug
Python programmes since it is user-friendly and simple to use.
Python 2 and 3 are among the Python versions that are supported by Eric IDE, which also offers
features like code highlighting, code completion, and syntax checking. Additionally, it contains an
integrated debugger that enables programmers to effectively debug their programmes.
The Eric IDE's plugin system, which enables developers to increase its capabilities, is one of its
primary features. An integrated version control system, a database browser, and a Python profiler are
just a few of the plugins that are available for the Eric IDE.
Features
o Provides customizable editors, source code folding, and window layouts.
o Advanced version control and project management capabilities
o Built-in debugger and task management support.
Text books:
1. Wesley J. Chun, “Core Python Applications Programming”, 3rd Edition , Pearson Education, 2016
2. Lambert, Fundamentals of Python: First Programs with MindTap, 2nd 1st edition , Cengage
Learning publication
4. Jeeva Jose &P.SojanLal, “Introduction to Computing and Problem Solving with PYTHON”,
Khanna Publishers, New Delhi,
2016
5. Downey, A. et al., “How to think like a Computer Scientist: Learning with Python”, John Wiley,
2015
6. Mark Lutz, “Learning Python”, 5th edition, Orelly Publication, 2013, ISBN 978- 1449355739
7. John Zelle, “Python Programming: An Introduction to Computer Science”, Second edition, Course
Technology Cengage
8. Michel Dawson, “Python Programming for Absolute Beginers” , Third Edition, Course Technology
Cengage Learning
9. David Beazley, Brian Jones., “Python Cookbook”, Third Edition, Orelly Publication, 2013, ISBN
978-1449340377