0% found this document useful (0 votes)
0 views30 pages

Unit 5

This document covers Python packages, including the use of built-in functions from libraries like matplotlib, numpy, and pandas, as well as GUI programming with Tkinter. It explains the structure of Python packages, how to import modules, and provides examples of creating plots using matplotlib and basic numpy functions. The document also details the installation of libraries and the syntax of various numpy functions essential for data manipulation.

Uploaded by

manishxyz416
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)
0 views30 pages

Unit 5

This document covers Python packages, including the use of built-in functions from libraries like matplotlib, numpy, and pandas, as well as GUI programming with Tkinter. It explains the structure of Python packages, how to import modules, and provides examples of creating plots using matplotlib and basic numpy functions. The document also details the installation of libraries and the syntax of various numpy functions essential for data manipulation.

Uploaded by

manishxyz416
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/ 30

PYTHON PROGRAMMING (BCC302)

(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.

Package Model Structure in Python Programming


Suppose we are developing a game. One possible organization of packages and modules could be as
shown in the figure below.

Game Package Model Structure

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)

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.select_difficulty(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)

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

# importing the required module


import matplotlib.pyplot as plt

# x axis values
x = [1,2,3]
# corresponding y axis values
y = [2,4,1]

# plotting the points


plt.plot(x, y)

# naming the x axis


plt.xlabel('x - axis')
# naming the y axis
plt.ylabel('y - axis')

# giving a title to my graph


plt.title('My first graph!')

# function to show the plot


plt.show()

Output: The code seems self-


explanatory. Following steps were followed:
 Define the x-axis and corresponding y-axis values as lists.
 Plot them on canvas using .plot() function.
 Give a name to x-axis and y-axis using .xlabel() and .ylabel() functions.
 Give a title to your plot using .title() function.
 Finally, to view your plot, we use .show() function.
Let’s have a look at some of the basic functions that are often used in matplotlib.
Method Description

it creates the plot at the background of computer, it


doesn‟t displays it. We can also add a label as it‟s
plot()
argument that by what name we will call this plot –
utilized in legend()

show() it displays the created plots

xlabel() it labels the x-axis

ylabel() it labels the y-axis

title() it gives the title to the graph

it helps to get access over the all the four axes of the
gca()
graph

gca().spines[„right/left/top/bottom‟].s it access the individual spines or the individual


et_visible(True/False) boundaries and helps to change theoir visibility

it decides how the markings are to be made on the x-


xticks()
axis

it decides how the markings are to be made on the y-


yticks()
axis

pass a list as it‟s arguments of all the plots made, if


gca().legend() labels are not explicitly specified then add the values in
the list in the same order as the plots are made

it is use to write comments on the graph at the


annotate()
specified position

whenever we want the result to be displayed in a


separate window we use this command, and figsize
figure(figsize = (x, y))
argument decides what will be the initial size of the
window that will be displayed after the run

it is used to create multiple plots in the same figure


with r signifies the no of rows in the figure, c signifies
subplot(r, c, i)
no of columns in a figure and i specifies the
positioning of the particular plot
Method Description

it is used to set the range and the step size of the


set_xticks
markings on x – axis in a subplot

it is used to set the range and the step size of the


set_yticks
markings on y – axis in a subplot

Note: Try removing the features added one by one and understand how does the output result
changes Example 1:
 Python3

import matplotlib.pyplot as plt

a = [1, 2, 3, 4, 5]
b = [0, 0.6, 0.2, 15, 10, 8, 16, 21]
plt.plot(a)

# o is for circles and r is


# for red
plt.plot(b, "or")

plt.plot(list(range(0, 22, 3)))

# naming the x-axis


plt.xlabel('Day ->')

# naming the y-axis


plt.ylabel('Temp ->')

c = [4, 2, 6, 8, 3, 20, 13, 15]


plt.plot(c, label = '4th Rep')

# get current axes command


ax = plt.gca()

# get command over the individual


# boundary line of the graph body
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)

# set the range or the bounds of


# the left boundary line to fixed range
ax.spines['left'].set_bounds(-3, 40)

# set the interval by which


# the x-axis set the marks
plt.xticks(list(range(-3, 10)))

# set the intervals by which y-axis


# set the marks
plt.yticks(list(range(-3, 20, 3)))

# legend denotes that what color


# signifies what
ax.legend(['1st Rep', '2nd Rep', '3rd Rep', '4th Rep'])

# annotate command helps to write


# ON THE GRAPH any text xy denotes
# the position on the graph
plt.annotate('Temperature V / s Days', xy = (1.01, -2.15))

# gives a title to the Graph


plt.title('All Features Discussed')

plt.show()

Output:
Example 2:
 Python3

import matplotlib.pyplot as plt

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]

# use fig whenever u want the


# output in a new window also
# specify the window size you
# want ans to be displayed
fig = plt.figure(figsize =(10, 10))

# creating multiple plots in a


# single plot
sub1 = plt.subplot(2, 2, 1)
sub2 = plt.subplot(2, 2, 2)
sub3 = plt.subplot(2, 2, 3)
sub4 = plt.subplot(2, 2, 4)

sub1.plot(a, 'sb')

# sets how the display subplot


# x axis values advances by 1
# within the specified range
sub1.set_xticks(list(range(0, 10, 1)))
sub1.set_title('1st Rep')

sub2.plot(b, 'or')

# sets how the display subplot x axis


# values advances by 2 within the
# specified range
sub2.set_xticks(list(range(0, 10, 2)))
sub2.set_title('2nd Rep')

# can directly pass a list in the plot


# function instead adding the reference
sub3.plot(list(range(0, 22, 3)), 'vg')
sub3.set_xticks(list(range(0, 10, 1)))
sub3.set_title('3rd Rep')

sub4.plot(c, 'Dm')

# similarly we can set the ticks for


# the y-axis range(start(inclusive),
# end(exclusive), step)
sub4.set_yticks(list(range(0, 24, 2)))
sub4.set_title('4th Rep')

# without writing plt.show() no plot


# will be visible
plt.show()
Output:

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.

What are Numpy Functions in Python?

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.

Syntax of Numpy Functions in Python

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.

Parameters of Numpy Functions in Python

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.

Return Value of Numpy Functions in Python

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.

Important Numpy Functions in Python

Here are some of the important NumPy functions in Python which every Data scientist must know:

1. np.array(): This function is used to create an array in NumPy.

Example Code:

import numpy as np

arr = np.array([1, 2, 3])

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.

2. np.arange(): This function is used to create an array with a range of values.

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.

3. np.zeros(): This function is used to create an array filled with zeros.

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.

4. np.ones(): This function is used to create an array filled with ones.

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:

[0. 0.25 0.5 0.75 1. ]

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:

[0.5488135 0.71518937 0.60276338]

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.

8. np.max(): This function is used to find the maximum value in an array.

Example Code:

import numpy as np

arr = np.array([1, 2, 3])

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.

9. np.min(): This function is used to find the minimum value in an array.

Example Code:

import numpy as np

arr = np.array([1, 2, 3])

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

arr = np.array([1, 2, 3])

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

arr = np.array([1, 2, 3])

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

arr1 = np.array([1, 2, 3])

arr2 = np.array([4, 5, 6])

dot_product = np.dot(arr1, arr2)

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.

FAQs Related to Numpy Function

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.

Q2 – What is the difference between a NumPy array and a Python list?


Ans – A NumPy array is a homogeneous multidimensional container of elements of the same data
type. It is much faster and more memory efficient than a Python list for large data sets. A Python list
can contain elements of different data types and is generally slower and less memory efficient than a
NumPy 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.

Q4 – Can I use NumPy with non-numeric data types like strings?


Ans – NumPy is primarily designed for numerical data, but it can be used with other data types like
strings. However, string operations in NumPy are generally slower and less memory efficient than
numerical operations, so it is not recommended to use NumPy with large string datasets.

Q5 – What is broadcasting in NumPy?


Ans – NumPy broadcasting allows you to perform operations on arrays of different shapes and sizes.
When performing an operation between two arrays with different shapes, NumPy will automatically
broadcast the smaller array to match the shape of the larger array.

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.

Key Features of Pandas

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

The following are the advantages of pandas overusing other languages:

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:

Data: It can be any list, dictionary, or scalar value.

Creating Series from Array:

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.

Python Pandas DataFrame

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:

he sections can be heterogeneous sorts like int, bool, etc.

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.

Create a DataFrame using List:

We can easily create a DataFrame in Pandas using list.

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.

1. import the Tkinter module.


2. Create the main application window.
3. Add the widgets like labels, buttons, frames, etc. to the window.
4. Call the main event loop so that the actions can take place on the user's computer screen.

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.

3 Checkbutton The Checkbutton is used to display the CheckButton 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.

9 Menu It is used to add 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.

12 Scale It is used to provide the slider to the user.

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.

14 Toplevel It is used to create a separate window container.

15 Spinbox It is an entry widget used to select from options of values.


16 PanedWindow It is like a container widget that contains horizontal or vertical panes.

17 LabelFrame A LabelFrame is a container widget that acts as the container

18 MessageBox This module is used to display the message-box in the desktop based applications.

Python Tkinter Geometry

The Tkinter geometry specifies the method by using which, the widgets are represented on display.
The python Tkinter provides the following geometry methods.

1. The pack() method


2. The grid() method
3. The place() method

Let's discuss each one of them in detail.

Python Tkinter pack() method

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.

The syntax to use the pack() is given below.

syntax
1. widget.pack(options)

A list of possible options that can be passed in pack() is given below.

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:

Python Tkinter grid() method

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:

Python Tkinter place() method

Syntax
1. widget.place(options)

A list of possible options is given below.

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.

There are some Python IDEs which are as follows:

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.

It offers code auto-completion and cross-platform capability.

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

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

3. Charles Dierbach, “Introduction to Computer Science using Python”, Wiley, 2015

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

Learning Publications, 2013, ISBN 978- 1590282410

8. Michel Dawson, “Python Programming for Absolute Beginers” , Third Edition, Course Technology
Cengage Learning

Publications, 2013, ISBN 978-1435455009

9. David Beazley, Brian Jones., “Python Cookbook”, Third Edition, Orelly Publication, 2013, ISBN
978-1449340377

You might also like