0% found this document useful (0 votes)
2 views43 pages

Python 2

This document serves as an introduction to Python, detailing its history, key features, and installation process. It covers the graphical user interface (GUI) of Python, various integrated development environments (IDEs), and the importance of Python's modules and libraries. The document also outlines expected learning outcomes for readers, emphasizing Python's accessibility and versatility as a programming language.
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)
2 views43 pages

Python 2

This document serves as an introduction to Python, detailing its history, key features, and installation process. It covers the graphical user interface (GUI) of Python, various integrated development environments (IDEs), and the importance of Python's modules and libraries. The document also outlines expected learning outcomes for readers, emphasizing Python's accessibility and versatility as a programming language.
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

UNIT 1

INTRODUCTION TO PYTHON

Structure
1.1 Introduction Jupyter Notebook

Expected Learning Outcomes 1.5 Anaconda


1.2 Key Features and Graphical Conda
User Interface of Python
Steps to Install Anaconda
Key Features of Phython
PIP
About GUI
1.6 Exploring Python's Modules
GUI toolkits for Phython
Import Module in Python
1.3 Installation and Setup of
Create a Phython Module
Python
1.7 Packages and Libraries
1.4 Integrated Development
Environment 1.8 Summary

IDLE 1.9 Terminal Questions

PyCharm 1.10 Solutions / Answers

Spyder

1.1 INTRODUCTION
Python was developed by Guido van Rossum, a principal author, in the early
1990s at Stitching Mathematisch Centrum ([Link] in the
Netherlands, along with many other contributors. Python is a high-level,
general-purpose, and very dynamic programming language that is widely used
currently. It is an interpreted and open-source programming language for data
analysis, visualization, and machine learning. It was designed with an
emphasis on code readability, and its syntax allows programmers to express
their concepts in fewer lines of code.
In 1995, Guido continued his work on Python at the Corporation for National
Research Initiatives ([Link] in Reston, Virginia and
released several versions of the software.
In May 2000, Guido and the Python core development team moved to
[Link] to form the BeOpen PythonLabs team. In October 2000, the
PythonLabs team moved to Digital Creations, which is now known as Zope 1
Block 1 Getting Started with Python

Corporation ([Link] In 2001, the Python Software Foundation


(PSF) ([Link] was formed, which is a non-profit
organization created specifically to own intellectual property rights related to
Python programming. Zope Corporation is a sponsoring member of the PSF.
In this unit, we shall describe the key features of Python. We shall also discuss
the graphic user interface of Python, as well as installation and setup. We shall
also explain Python's Integrated Development Environments (IDE). Finally, we
shall explore various Python modules, packages, and libraries.
In the next unit, you will learn various data types and operators in Python.

Expected Learning Outcomes


After completing this unit, you should be able to:
❖ explain the development history of Python language development and
features of Python programming language;
❖ acquire how Python setup can be installed in your system;
❖ comprehend various IDEs for Python;
❖ describe the Anaconda distribution for Python; and
❖ explore various modules, Packages and Libraries in Python

1.2 KEY FEATURES AND GRAPHICAL USER


INTERFACE OF PYTHON
Before discussing the graphical user interface of Python, let us first mention its
key features.
1.2.1 Key Features of Python
Some of the key features of Python language are:
• Python is a general-purpose, high-level programming language.
• Every release of Python is open-source, and most of the Python
releases are GPL-compatible. (GPL - General Public License. GPL-
compatible licenses make it possible to combine Python with other
software that is released under the GPL.)
• Any version of Python can be downloaded from [Link], which
is a website of the Python Software Foundation.
• Python can also be freely modified and re-distributed because while the
language is copyrighted, it is available under an open-source license.
• Python Installation and Setup are available for Windows, macOS, Linux,
iOS and Android operating systems.
• Python is an effective object-oriented programming language, though
easy to learn.
• Python has efficient high-level data structures.
• Python uses elegant syntax and has a dynamic typing facility, which
makes the programs easier to write and read.
2
Unit 1 Introduction to Python

• Python has a large suite of standard libraries to support many


programming tasks.
For a programmer/developer, the key features of Python programming
language are:
• It is perfectly fine to learn Python as the first programming language,
though it is common for beginners to start with procedural languages like
Pascal, C, C++ or Java.
• Python has a very simple and consistent syntax.
• A variety of basic data types are available: numbers (integers, floating
point, complex, etc.), strings (both ASCII and Unicode), lists, dictionaries
and other collection data types.
• Python is a dynamic language, meaning there is no need to explicitly
declare the data type of a variable. The type is checked during runtime,
not at compile time.
• Python supports object-oriented programming with classes and other
OOP (Object Oriented Programming) concepts and multiple
inheritances.
• Code can be grouped into modules and packages.
• By learning Python at the beginner's stage, a student can concentrate
more on important programming skills such as problem decomposition
and data type design etc., rather than indulging in the additional
complexity of typing the code statically.
• While learning Python, students can be introduced to basic concepts
such as loops and procedures quite earlier.
• With Python, students are introduced to the concepts of user-defined
objects in their very first course.
• Python has a large standard library, which can help students working on
realistic applications at the beginner's level itself.
• Students are also exposed to code reuse using the standard library.
• Students can also explore third-party modules, such as PyGame, to add
functionality to their code without having to write it themself.
• The language supports raising and catching exceptions, resulting in
cleaner error handling.
• Data types are strongly and dynamically defined. Mixing incompatible
types causes an exception to be raised, so the errors are caught sooner.
• Python contains advanced programming features such as generators
and list comprehension.
• Python's automatic memory management frees the user from having to
manually allocate and free memory in the code.
1.2.2 About GUI
A graphical user interface (GUI) is a type of user interface through which the
users interact with electronic devices via visual representations. A GUI uses a 3
Block 1 Getting Started with Python

combination of technologies and devices to provide a platform that users can


interact with for the tasks of gathering and producing information. This makes
it easier for people with few computer skills to work with and use computer
software. In personal computers, the most common combination of such
elements in GUIs is the windows, icons, text fields, cursors, buttons, menus,
menu bar, toolbar, pointer, etc. These objects can change colour, size, or
visibility when the user interacts with them. These graphical objects are
sometimes enhanced with sounds or visual effects.
In simple terminology, a GUI is a system of interactive visual components for
computer software. A GUI displays objects that convey information and
represent actions that can be taken by the user. For example, to start a
program on a Windows desktop, we can use a mouse to move a pointer and
click a program icon, or we can use windows, icons, and menus to open,
close, delete and move the files.
Generally, to navigate through a GUI operating system, the use of a mouse or
a pointer is most common among the users, but the keyboard shortcuts and
the arrow keys can also be used.
Thus, GUI is considered to be more user-friendly than a text-based command-
line interface, such as MS-DOS or the shell of Unix-like operating systems.
With a command-line interface, the user needs to know the commands to
navigate to the directory containing files, list of files, open the file, run the file,
etc., whereas, with the GUI system, the user can move the pointer to the
program icon and double-click it to open a program. Thus, GUI operating
systems are easier to learn and use because, unlike a command-line
interface, the user is not required to memorize the commands.
Some examples of GUI operating systems are Microsoft Windows, macOS,
Chrome OS, any Microsoft program (such as Word, Excel, Outlook, etc.),
variants of Linux such as Ubuntu, Internet browsers (such as Internet
Explorer, Chrome, Firefox, etc.), etc. However, all operating systems do not
have GUI interface, for example, MS-DOS, some versions of Linux, etc.
1.2.3 GUI toolkits for Python
A GUI toolkit is a library or a collection of libraries containing a set of graphical
control elements (like buttons, menus, labels, etc.) called widgets that are
used to construct the GUI of programs. Widgets are the building blocks of GUI
programming and are used to get input from the user or to display the
information. In other words, the toolkit is the set of Application Programming
Interface (API) that can be used to build the graphical user interface for the
users to enable them to interact with the program. One of the most important
decisions to be taken while starting a new desktop application is which GUI
"toolkit" to choose.
PythonToolkit (PTK) is an interactive environment for Python. It was originally
designed to provide a Python-based environment for scientists and engineers.
However, it can also be used as a general-purpose interactive python
environment especially for interactive GUI programming.
It is built around a console window, a simple python source editor and a Tool
plugin system so that extra features and support for python packages can be
4
Unit 1 Introduction to Python

easily added.
Some of the important features of Python Toolkits are:
• They provide a Console window with support for multiple python
interpreters (Engines)
• It is possible to program interactively with different GUI toolkits
(wxPython, TkInter, pyGTK, pyQT4, PySide, etc.).
• They have a built-in python debugger integrated with tools and editor.
• They provide Object auto-completions facility.
• It is possible to do multi-line command editing.
• They enable the user to browse command history (previous/next and
search for partially typed commands).
• They provide a simple editor for code testing and scripting.
• They provide set, edit and clear debugger breakpoints via the editor.
• They provide a path manager tool to easily change the current working
directory and manage the python search paths.
• They provide Python object importer/exporter system to save and load
data easily.
PTK is written in Python using the cross-platform GUI Library, and therefore,
they are stable, reliable, and easy to learn.
Some of the widely used Python GUI are:
• PyQt5
• Tkinter
• Kivy
• wxPython
• Libavg
• PySimpleGUI
• PyForms
• Wax
• PySide2
• PyGUI
Before going to the next section, answer the following Self Assessment
Questions.

SAQ1
1. What are the key features of Python programming language?
2. What are the advantages of Python programming language compared to
other languages?
3. Explain the GUI. What are the Python toolkits for GUI, and their
important features? 5
Block 1 Getting Started with Python

1.3 INSTALLATION AND SETUP OF PYTHON


Python is not preinstalled on a system with a Windows (or any other) operating
system, and therefore, it needs to be installed explicitly. The following step-by-
step process can be followed to install the latest version of Python on your
system:
Step 1: Open a browser and type the following URL:
[Link]
It will result in the window as shown in Fig. 1.1.

Fig. 1.1: Download Python for Window

Step 2: It is recommended that you download the latest stable version. You
can directly click on Download Python 3.13.3 tab to download the
latest Python installer for 64-bits. A stable and latest version of
Python provides stability and support for older versions, ensuring
compatibility with older projects, along with performance
improvements and the latest features. Fig. 1.1(b) shows a page
containing the list of Python Releases for Windows, where you will
find the Latest Python 3 Release options as you scroll down (See
Fig. 1.2). The latest stable release of Python, as of April 08, 2025, is
Python 3.13.3, as shown in the following figure:

6
Unit 1 Introduction to Python

Fig. 1.2: Python Stable Releases

Step 3: Select an appropriate link, for example, Download Windows


Installer (64-bit) for a 64-bit system or Download Windows Installer
(32-bit) for a 32-bit system, to download an executable Python
installer (Note that it is possible to check whether your system is 32-
bit or 64-bit system). Here, we click on Download Windows Installer
(64-bit) for a 64-bit system, which downloads the Python Installer in
your system. Once the Python Installer is downloaded, run the
executable Python Installer, which results in the following window:

Fig. 1.3: Install Python

Step 4: Make sure to select the two checkboxes, namely, Install launcher
for all users and Add Python 3.13 to PATH. Select Install Now
option for the installation as shown in Fig. 1.3. It will initiate the Setup
Process as shown in the following figure:

Fig. 1.4: Python Setup

Step 5: Once the installation is done successfully, a new window will pop up,
displaying successful Setup. In the same way, you can install
Python on macOS and Linux operating systems.
Step 6: Having installed the selected version of Python successfully, verify
whether the Python installation is successful, either through the
command line or through an IDLE App. (Note that the IDLE App is a
default editor, which gets installed along with the Python installation, 7
Block 1 Getting Started with Python

and IDLE stands for Integrated Development and Learning


Environment). If you want to check through the command line, open
the command prompt and type "python", you can confirm that the
selected Python version has been installed successfully, and you can
notice the prompt ">>>" on the command line. Alternatively, you can
search "Python" from the Start menu and clicking on "IDLE" (with
IDLE, the installed version will also pop up, like IDLE 3.13.2), will
open an IDE (Integrated Development Environment) where you can
start typing your Python code.

Fig. 1.4: IDLE 3.13.2

Now, you can answer the following Self Assessment Question for practice.

SAQ 2
Describe the stepwise Python installation process.

1.4 INTEGRATED DEVELOPMENT ENVIRONMENT


Integrated Development Environment is abbreviated as IDE, which is a
software application that facilitates the programmers to develop the code
efficiently. It provides the functionalities like writing the code, code completion,
auto-indentation, highlighting the errors, editing the code, executing the code,
8
Unit 1 Introduction to Python

etc. An IDE packages these tools into a single GUI, which can be used for
software development. The development environment provides an integrated
toolset for software developers where they can write and test the code.
Development tools include text editors, compilers or interpreters, code libraries
and platforms to test the code, all of which are accessed through a single GUI.
Without an IDE, a software developer will be required to select, deploy,
integrate, and manage all these tools separately.
The most widely used Python IDEs and Code Editors for Windows, Linux and
Mac, are:
• IDLE
• PyCharm
• Spyder
• Jupyter
• Sublime Text 3
• Visual Studio Code
• Atom
• Pydev
• Thonny
• Wing
• PyScripter
All these programming environments provide syntax highlighting, auto-
indenting, and access to the interactive interpreter while coding. Let us explore
the first four widely used Python IDEs more.
1.4.1 IDLE
When we install Python on Windows or Mac, IDLE comes bundled with the
installation, and its view is as shown in the above figure. IDLE stands for
Integrated Development and Learning Environment. Looking at the name, one
can guess that IDLE helps you get started with learning Python. For a
beginner, it can be one of the best tools to learn Python.
Another way we can work with Python IDLE is by using the command prompt.
We can open the command prompt from the folder with the name "Python'
which would have been installed in our system by selecting the option as
shown in the following figure:

9
Block 1 Getting Started with Python

Fig. 1.5: Python IDLE

It will work similarly to the IDLE application. The other applications mentioned
above can also be explored and the user can select the one to work with
which is found comfortable.
IDLE can work as an interactive interpreter. We can write Python commands
line by line, and it will execute them to show the results. We can also call the
interactive Python interpreter a python shell. A python shell is designed to read
the python command, evaluate the statement, print the result, and repeat the
same process until you exit. We can use Python IDLE as an interactive
interpreter and execute statements one by one. We can perform mathematical
operations, comparisons, take input from users, and many more tasks.
If required, one can also write small blocks of code in Python IDLE. However,
it is advisable to use a python file/script (using applications like 'Spyder',
'Jupyter Notebook', 'Visual Studio', etc.) to write blocks of code in a Python
program and then execute it. The python script/file can be saved with a '.py'
extension. It is possible to execute any number of statements using a single
python file at once. With Python IDLE, one can easily create and modify
existing python files.
In IDLE,
• To stop a program execution before its completion, one can type Ctrl+C.
• To close the Python IDLE, one can type Ctrl+D on the keyboard.
1.4.2 PyCharm
PyCharm is another powerful integrated development environment (IDE)
designed specifically for Python programming. It is advanced by the Czech
organization JetBrains and is used with Windows, macOS, and Linux
operating systems. PyCharm has two variations: Community Edition and
Professional Edition. The Community Edition is open source, whereas the
Professional Edition is a paid subscription carrier.
PyCharm is one of the popular applications among Python developers. It is
extensively used by developers who are working on huge or complex
problems. PyCharm can also be a preferred platform for beginners who are
learning to code in Python, as it can assist the developer to keep away from
common mistakes and write more efficient code.
10
Unit 1 Introduction to Python

Key features of PyCharm


• It has an extensive range of capabilities that help developers to write,
debug, and test their code with greater efficiency.
• It has a Smart Code Completion feature that enables the user to write
down the code more quickly and correctly.
• PyCharm can inspect your code for probable errors and troubles. It can
recognize syntax errors, typographical mistakes, and different logical
errors.
• PyCharm has an effective debugger that will allow the user to execute
the code line by line, examine the values of variables, and set
breakpoints.
• PyCharm allows the user to run test codes from the IDE at once.
Advantages of PyCharm
• PyCharm has efficient code inspection features that help programmers in
writing code more speedly and correctly, causing an increase in
productivity.
• PyCharm's code inspection features help programmers to discover the
errors even before the programmer executes the code. This helps users
to develop more reliable codes.
Disadvantages of PyCharm
• While running the codes, sometimes the user may experience lags and
delays.
• PyCharm being highly powerful, novice users may experience a steep
learning curve using PyCharm. Novice users may need an IDE to fit their
pace of workflow.
• While PyCharm Community Edition is open-source, the Professional
Edition requires a paid subscription.
• PyCharm, in comparison to some other editors, tends to have a slower
startup time.
• PyCharm is designed typically for Python development, so it cannot be
used with more than one programming language, unlike Jupyter
notebooks.
1.4.3 Spyder
Spyder (Scientific PYthon Development EnviRonment) is an open-source IDE
for the Python language, specially designed for developing data science
applications by French developer Pierre Raybaut in the year 2000. The Spyder
IDE offers a complete set of tools and functions specifically adapted to data
science tasks. As compared to other Python IDEs, Spyder focuses more on
data analysis and visualization tools with its user-friendly interface.
Key features of Spyder IDE are:

11
Block 1 Getting Started with Python

• The advanced code editor of Spyder provides tools such as syntax


highlighting, code suggestion and auto-completion to increase developer
productivity.
• Spyder integrates popular Python scientific libraries such as NumPy,
Pandas, Matplotlib, and SciPy, which enable data scientists to simplify
their workflow and speed up the development of data applications.
• Spyder's interactive console enables the data scientists to test pieces of
code, verify results, and perform trial and error with the code being newly
developed without requiring them to run the entire script.
• There are many IDEs for Python, and each has its own specific features,
advantages and disadvantages. Spyder offers a more complete interface
and a more traditional development environment with a dedicated code
editor and advanced debugging features.
Spyder is considered one of the most popular IDEs for Python programming.
Spyder for Windows OS can be installed using the URL:
[Link]
Upon successful installation, the Spyder IDE will look as follows:

Fig. 1.6: Spyder IDE

Once Spyder is open, one can write the Python program in the text editor. For
instance, if the following one-line code is written:
print("Hello !")
Once we finish writing the code, we click File > Save as and name the
program. To run the program, click the Run icon or press F11 on the
keyboard.
The program will run in the interactive console. The output of the program will
be displayed in the console in the bottom right corner.
Users who are familiar with R Studio can notice similar panes: on the left side
is the pane for writing the code; on the right side, the upper pane may be used
12
Unit 1 Introduction to Python

as a variable explorer or debugger or to seek help or to visualize plots, etc.;


and the lower pane, on the right-hand side, is the console where the user can
get the output.
1.4.4 Jupyter Notebook
Jupyter Notebook is an open-source web application which is widely used by
data scientists, researchers, and educators for interactive computing and data
analysis. Initially, "Jupyter" had support for the three programming languages-
Julia, Python and R- and therefore, the name "Jupyter" was derived from
these three names. However, "Jupyter" now supports more than 40
programming languages, and therefore, it is a preferred platform for
developers. Because the notebook interface is web-based, users may use
their web browsers to interact with it.
The Jupyter Notebook is made up of the following three components:
(1) The notebook web application
It is an interactive web application that allows the user to write and run
code. Using the notebook, the users can avail features like automatic
syntax highlighting and indentation when editing code in the browser,
check the output in formats such as HTML, LaTex, PNG, PDF, etc.,
contain mathematical formulas presented in Markdown cells, etc.
(2) Kernels
The independent processes launched by the notebook web application
are known as kernels, and they are used to execute user code in the
specified language and return results to the notebook web application.
The following languages are available for the Jupyter Notebook kernel:
• Python
• R
• Julia
• Ruby
• Scala
• [Link]
(3) Notebook documents
All the contents which can be viewed in the online notebook application,
including calculations, inputs and outputs, texts, mathematical
equations, graphs, images, etc., can also be represented in the
notebook document.
In general, a Jupyter notebook will contain the 'Cells' which can be of the
following types:
(i). Code Cell: A code cell's contents are interpreted as statements in
the current kernel's programming language. Python is supported in
code cells because Jupyter Notebook's kernel is, by default,
written in that language. The output of the statement is shown
below the code when it is executed. The output can be shown as 13
Block 1 Getting Started with Python

text, an image, a matplotlib plot, or a set of HTML tables. For


example, in the following image, it can be seen that the 'print'
statements are the Python code and following the code is the
output upon executing the code in that cell.

Fig. 1.7: Python Code in Jupyter

In Fig. 1.7, it can be noticed that the 'code' option is mentioned in a


dropdown menu. Therefore, the text written in this first cell is
considered as Python code followed by output. Another example is
as follows:

(ii). Markdown Cell: The markdown option in the dropdown menu


enables the user to create notebook documentation and enhance
its aesthetic appeal. This cell has usual formatting options, such as
having the text in boldface or italics, adding headers, creating
bulleted lists or hyperlinks, having tabular contents and images,
etc. In the following image, we have the option 'Markdown' in place
of 'code' in the above image, and therefore, the text in that cell will
be considered simple text and not Python code.

Fig. 1.8: Markdown Cell in Jupyter

There are three cells in Fig. 1.8, which are Markdown cells.
Key features of Jupyter Notebook are:
• It supports several programming languages.

14
Unit 1 Introduction to Python

• It integrates Markdown cells with formatted text, providing a textbook


kind of view.
• It can help create outputs like tables and charts.
• It provides flexibility in terms of language switching (by choosing the
appropriate options in the kernels tab).
• The huge applications can be divided into tasks, and code sharing is
possible for working in teams and then integrating the tasks under one
project.
• It can integrate interactive widgets with data science libraries.
The easiest way to install Jupyter Notebook is through the following URL:
[Link]
Now, you can answer the following Self Assessment Questions for practice.

SAQ 3
1. Describe an IDE. Also, explain the most used IDEs for Python
programming.
2. Write a brief note on an IDLE editor and PyCharm for Python.
3. Discuss the key features of Spyder and compare it with other Python
IDEs.

1.5 ANACONDA
Anaconda is an open-source distribution of the Python and R programming
languages for scientific computing, including data visualization, data analytics,
machine learning applications, large-scale data processing, predictive analytics,
robotics, etc. It is the most trusted platform for data science. Anaconda aims to
simplify package management and deployment in order to help the users to
manage a large collection of open-source packages available to them. The
distribution includes data science packages suitable for Windows, Linux,
and macOS. It is developed and maintained by Anaconda, Inc., which was
founded by Peter Wang and Travis Oliphant in 2012. As an Anaconda, Inc.
product, it is also known as Anaconda Distribution or Anaconda Individual
Edition, while other products from the company are Anaconda Team Edition
and Anaconda Enterprise Edition, both of which are not free.
Anaconda distribution comes with over 250 packages that are automatically
installed with Anaconda. In addition, over 7,500 additional open-source
packages can be installed from the Anaconda Repository with the help of
PyPI or the conda package management system and virtual
environment manager using the conda install command.
After successful installation of Anaconda, if the user prefers to work with a
desktop GUI, then the Anaconda Navigator can be used; while if the user
prefers to work with Command Line Interface (CLI), then the Conda package
and environment manager can be used via CLI of the system.

15
Block 1 Getting Started with Python

The Anaconda command prompt can be opened by browsing through


applications installed in your system, and the following window will be opened
by typing 'python' after the path shown as follows:

Fig. 1.9: Anaconda command prompt

1.5.1 Conda
Conda is an open-source package and environment management system that
runs on Windows, macOS, and Linux. As a package manager, Conda helps
the user quickly find, install, run, and update packages as well as their
dependencies. Also, it easily creates, saves, loads, and switches between the
environments on the local computer. That is, if the program needs a package
that requires a different version of Python, the user does not need to switch to
a different environment manager because conda is itself an environment
manager. Just with the help of a few commands, a separate Python
environment can be set up to run the different versions of Python, while the
user can continue working with the current environment in which he/she was
working. Conda was created to develop Python programs, but it can package
and distribute software for any language.
There is also a miniature bootstrap version of Anaconda called Miniconda,
which includes only conda, Python, the packages they depend on, and a small
number of other packages.
Note that the conda package and environment manager is included in all the
versions of Anaconda and Miniconda.
1.5.2 Steps to install Anaconda
Step 1: Browse the Anaconda Documentation website and follow the
instructions to download the installer for an operating system on your
personal computer.
Step 2: Once the installer downloads successfully, double-click on it to start
the installation process.
Step 3: Follow the prompts and agree to the terms and conditions.

16
Unit 1 Introduction to Python

Step 4: Select "Yes" when it is asked whether we want to "add Anaconda to


my PATH environment variable". This will ensure that Anaconda is
added to the system's PATH, which is a list of directories that the
operating system uses to find the files it needs.
Once the installation is complete, we will be asked if we want to "enable
Anaconda as my default Python". Select "Yes" to use Anaconda as the
default Python interpreter.
Also, Conda, Anaconda Navigator, and hundreds of other packages are
installed by default once Anaconda is installed.
1.5.3 PIP
PIP is a package-management system written in Python and is used to install
and manage software packages. The Python Software
Foundation recommends using pip for installing Python applications and its
dependencies during deployment. The pip connects to an online repository of
public packages called the Python Package Index. Pip can be configured to
connect to other package repositories which are locally or remotely hosted,
provided that they comply with the Python Enhancement Proposal.
Most distributions of Python come with pip preinstalled.
It is also worth to note that:
• Thousands of other packages are available from the site [Link].
• The desired packages can be downloaded using the command pip
install, which is installed with Anaconda. PIP is also a package manager
for Python packages and modules. A Python package is a collection of
files that are needed for a module, and a module is a Python code
library.
• The big difference between conda and the pip package manager is in
the way the package dependencies are managed, which is a significant
challenge for Python data science.
• Before version 20.3, when pip installed a package, it automatically
installed any dependent Python packages without checking whether
these packages conflicted with the previously installed packages.
• In contrast, conda analyses the current environment, including
everything currently installed, and, together with any version limitations
specified, works out how to install a compatible set of dependencies. It
will also show a warning if this cannot be accomplished.
• It is also possible to create custom packages as per the requirement of
the application, using the command conda build, and it is also possible
to share that package with the other Python users by uploading it to
[Link], PyPI or another repository.
The following applications are available by default in Navigator:
• JupyterLab
• Jupyter Notebook
• QtConsole 17
Block 1 Getting Started with Python

• Spyder
• Glue
• Orange
• RStudio
• Visual Studio Code
Spyder is one of Python's most popular IDEs and is included in the Anaconda
distribution. To launch Spyder, open the Anaconda Navigator and select the
Spyder IDE from the list of applications.
In addition to using Spyder or Jupyter Notebook, it is also possible to use the
Anaconda Prompt or Terminal to run Python code.
• To launch the Anaconda Prompt, open the Anaconda Navigator and
select Anaconda Prompt from the list of applications.

• To launch Terminal on Mac, open the Applications folder and select


Utilities > Terminal.
• To launch Terminal on Windows, open the Start menu and search for
cmd.
• Once the Anaconda Prompt or Terminal is launched, one can type
Python code directly into the window and press Enter to run it.
• Alternatively, it is possible to use Anaconda Prompt or Terminal to
launch Spyder or Jupyter Notebook. To launch Spyder, type "spyder" in
the window and press Enter. To launch Jupyter Notebook, type "jupyter
notebook" in the window and press Enter.
Anaconda is one of the platforms for beginners who want to learn Python. It is
simple to install and use, and it comes with many features that can help users
get started quickly. With Anaconda, users can continue to develop coding
skills by learning how to use other IDEs and can explore other data science
tools such as R or Julia. The users can also learn how to use Anaconda to
manage the packages and environments or use Conda to create custom
environments.
Let us also understand what an Environment is. An environment is a directory
that contains all the files needed for a particular application, such as Python
interpreter, packages, and configuration files.
Now, you can answer the following Self Assessment Questions for practice.

SAQ4
Explain the following terms:
(i) Anaconda Distribution
(ii) Anaconda Navigator
(iii) Anaconda Prompt
18
Unit 1 Introduction to Python

1.6 EXPLORING PYTHON'S MODULES


A Python module is a file containing Python definitions and statements. A
module can define functions, classes, and variables. A module can also
include runnable code.
Grouping related code into a module makes the code easier to understand
and use. It also makes the code logically organized. There are several built-in
modules in Python that can be imported into code whenever they are required.
1.6.1 Import module in Python
Python has a large number of modules, which are already defined along with
well-defined built-in functions for ready-to-use purposes. We can import the
functions and classes defined in a module to another module using the import
statement in another Python source file.
When the interpreter encounters an import statement, it imports the module if
the module is present in the search path.
Syntax to use a ready-to-use module:
import module_name
To use a function from a module:
module_name.function_name
For example, there is a 'math' module in Python consisting of several
mathematical and trigonometric functions, like 'sqrt' for computing the square
root of a number, or 'sin' to compute the sine of a value, etc. To import the
'math' module and then use the 'sqrt' function from the 'math' module, we can
write the code:
import math
x = 35
[Link] (x)
The 'from' statement in Python allows one to import specific functions from a
module without importing the entire module. For example, if it is required to
use only the 'sqrt' function from the 'math' module in a code, then it is possible
to write:
from math import sqrt
sqrt (x) # so now into more requires to write [Link](x)
Alternatively, if it is required to use 'sqrt' and 'factorial' functions from the 'math'
module in a code, then it is possible to write:
from math import sqrt, factorial
factorial (5)
The * symbol with the import statement is used to import all the functions from
a module to a current namespace by writing a line in the code:
from math import *

19
Block 1 Getting Started with Python

Now, any function from the 'math' module can be used in the code in which
this statement is written just by using the name of the function, like
abs(x) # in place of [Link](x)
To get an exhaustive list of all the functions available in a module, we can
write the code:
import math
help(math)

1.6.2 Create a Python Module


At times, it may be possible that the user wants to create their own functions
for specific applications, and these functions need to be used repetitively.
Then, it is possible to bundle those functions into a 'module', which will be a
module created by the user as a Python file itself (file with '.py' extension like a
usual Python code file). Thus, creating a Python module simply requires to
write the desired code and save that in a file with .py extension.
Renaming the Python Module
It is possible to rename the module while importing it using its original name.
The syntax for renaming the module is:
import module_name as alias_name
This can be useful for instances where we want to avoid writing long names
whenever the functionalities of that module are used several times in the code.
For example, to rename the 'math' module with a shorter name, say, 'mt', we
can write:
import math as mt
Now, any function of the 'math' module can be used by writing code:
[Link] (x)
[Link] (5)
Now, you can answer the following Self Assessment Questions for practice.

SAQ5
What is a Python module? How can a particular function from a specific
Python module be used in a current working environment?

1.7 PACKAGES AND LIBRARIES


A package, also known as a library, is a collection of modules installed using
Conda. A module is a Python file created as a Python file with a .py extension.
The packages in Python are a way to organize and structure code by grouping
related modules into directories. Some of the packages that are defined in
Python for Statistical computing are:
• NumPy
• Pandas
20
Unit 1 Introduction to Python

• Matplotlib
• SciPy
• StatsModels
• Seaborn
• Plotly
A library is a collection of code, usually related modules and packages. This
term is often used interchangeably with the "Python package". However, many
users think that a package is a collection of modules and a library is a
collection of packages. Developers create Python libraries to share code with
others. This way, instead of writing the code from scratch every time, the
specific function needed to be used can simply be called from the package or
library.
Some of the useful Python libraries are:
• Scikit-learn
• PyTorch
• TensorFlow
• Keras
Let us briefly discuss the first four packages defined in Python.
1. About NumPy
NumPy stands for Numerical Python. NumPy is a Python library used for
working with arrays. It is a general-purpose array-processing package. It
provides the functionality to create high-performance multidimensional
array objects and tools for working with these arrays. It is the
fundamental and most important package for scientific computing with
Python.
NumPy also consists of functions for working with matrices, linear
algebra, Fourier transform, etc. NumPy was created in 2005 by Travis
Oliphant. It is an open-source project that can be used with Python for
free. In Python, there are list objects that are similar to NumPy arrays
and serve the purpose of arrays, but data processing is slow with lists
compared to NumPy arrays. NumPy aims to provide an array object that
is up to 50 times faster than traditional Python lists.
The array object in NumPy is called 'ndarray', it provides a lot of
supporting functions that work with 'ndarray' very efficiently. Arrays are
a very frequently used data type in data science, where speed and
resources are very important.
The NumPy library can be used in a Python working environment by
using the following code:
import numpy
or
import numpy as np
21
Block 1 Getting Started with Python

In the second call, the 'numpy' library is imported into the working
environment with the alias name 'np' as discussed earlier.
However, it is not necessary to import the library using the alias, which
helps in writing less code every time a method or property is called.
2. About Pandas
Pandas is a powerful and open-source Python library which is also used
for working with data sets like NumPy. It has functions for exploring,
cleaning, manipulating and analyzing data. Pandas enables
programmers to analyze big data and make conclusions based on
statistical theories. Pandas consist of data structures and functions that
perform efficient operations on data. Pandas can work very well
with tabular data, such as spreadsheets, DataFrames, or SQL tables.
The Pandas library is generally used for data science. It is used in
conjunction with other libraries that are used for data science. It is built
on the NumPy library, which means that a lot of the structures of NumPy
are used or replicated in Pandas.
The data produced by Pandas is often used as input for plotting
functions in Matplotlib, statistical analysis in SciPy, and machine learning
algorithms in Scikit-learn.
The Pandas library can be used in a Python working environment by
using the following code:
import pandas
or
import pandas as pd
In the second call, the 'pandas' library is imported into the working
environment using the alias 'pd'.
3. About Matplotlib
Matplotlib is a powerful low-level library used for plotting graphs in
Python. Matplotlib was created by John D. Hunter in 2003. Matplotlib is
open source and, therefore, can be used for free. Matplotlib is mostly
written in Python, whereas a few segments are written in C, Objective-C
and Javascript for Platform compatibility.
Matplotlib has versatile plotting functions that can create a variety of
high-quality visualizations, like line plots, bar plots, scatter plots,
histograms, pie charts, etc. Additionally, it provides control to users for
every aspect of plots, for example, deciding the plot's colour, the marker
style, size, color, labels, annotations, etc.
Matplotlib is integrated with NumPy and, therefore, the NumPy data
arrays can be directly used for creating plots using Matplotlib.
An Example to create a simple line plot using Matplotlib:
In the following code, the 'pyplot' module from 'matplotlib' library is used
with alias name 'plt':

22 import [Link] as plt


Unit 1 Introduction to Python

x = [0, 1, 2, 3, 4]
y = [0, 1, 4, 9, 16]
[Link](x, y)
[Link]()
4. About SciPy
The 'Scipy' Package of Python is a high-level scientific computation.
Scipy contains various toolboxes for scientific computing. It has
submodules like interpolation, integration, optimization, image
processing, statistics, etc. Scipy is meant to operate on 'numpy' arrays.
A submodule can be imported by specifying the name of the submodule
preceded by the keyword 'scipy' followed by '.' Operator. For example,
submodules are defined in Scipy as:
[Link], [Link], [Link], [Link],
[Link], etc.
They all depend on 'numpy'. It has many user-friendly, efficient, and
easy-to-use functions that help to solve problems like numerical
integration, interpolation, optimization, linear algebra, and statistics. The
benefit of using the SciPy library in Python while making ML models is
that it makes a strong programming language available for developing
fewer complex programs and applications.
To import SciPy for the working environment, we can use:
import scipy

Now, you can answer the following Self Assessment Questions for practice.

SAQ6
1. List out some of the most used Python packages and libraries.
2. What is the importance of 'Numpy' in scientific computing?
3. What is the use of 'matplotlib' while coding in Python?

Let us now summarise what you have learnt in this unit.

1.8 SUMMARY
In this unit, we have discussed:
• Introductory idea of Python programming language.
• Installation and Setup of different Python IDEs to write Python code.
• Ananconda and Conda distribution.
• Use of built-in modules and creating new modules by users as per the
need; defining and using the functions defined in the modules.
• Introduction to packages and libraries in Python; basic idea about most
frequently used libraries like NumPy, Pandas, SciPy, and Matplotlib.

23
Block 1 Getting Started with Python

1.9 TERMINAL QUESTIONS


1. What is the latest release of Python?
2. Discuss the key features of Jupyter Notebook and compare it to other
Python IDEs.
3. How did the names Spyder and Jupyter arrive?
4. What is Conda? Write down the steps to install Anaconda.
5. What is the use of 'pip install'?
6. How can a user create his / her own module?
7. Differentiate between a module, package and library in Python.
8. What is the importance of 'pandas' and 'Scipy'in scientific computing?

1.10 SOLUTIONS/ ANSWERS


Self Assessment Questions (SAQs)
1.1. Refer to Section 1.2.1.
1.2. Refer to Section 1.2.1.
1.3. Refer to Sections 1.2.2 and 1.2.3.
2. Refer to Section 1.3.
3.1. Refer to Section 1.4.
3.2. Refer to Sections 1.4.1 and 1.4.2.
3.3. Refer to Section 1.4.3.
4. Refer to Section 1.5.
5. Refer to Section 1.6.
6.1. Refer to Section 1.7.
6.2. Refer to Section 1.7(1).
6.3. Refer to Section 1.7(3).

Terminal Questions (TQs)


1. Refer to Section 1.2.
2. Refer to Section 1.4.
3. Refer to Sections 1.4.3 and 1.4.4.
4. Refer to Sections 1.5.1 and 1.5.2.
5. Refer to Section 1.5.3.
6. Refer to Section 1.6.2.
7. Refer to Sections 1.6 and 1.7.
8. Refer to Sections 1.7(2) and 1.7(4).

24
UNIT 2
DATA TYPES AND OPERATORS
IN PYTHON
Structure
2.1 Introduction Values Input by users

Expected Learning Outcomes 2.5 Various Operators in Python


2.2 First Python Program 2.6 Summary
2.3 Data Types in Phthon 2.7 Terminal Questions
2.4 Statements and Expressions 2.8 Solutions/Answers
Assign values to variables

Expressions

2.1 INTRODUCTION
In the previous unit, we have studied how to install and set up Python. We
have also explained Python's Integrated Development Environments (IDE) as
well as various Python modules, packages, and libraries. In this unit, we focus
on some foundational building blocks of Python programming that will prepare
you to write simple programs. A clear understanding of these basics is
essential for writing effective and error-free code, which makes you ready to
write simple programs using these basic ideas.
Section 2.2 will introduce our first Python program and discuss data types in
Section 2.3. These data types determine the kind of data a variable can hold,
such as integers, floating-point numbers, strings, or Boolean values. Variables
are like containers that store data so we can use it later in our program. In
Section 2.3, we will learn statements and expressions, which are basically the
instructions we give to the computer to do something, like calculate a number
or show a message. Here, we will also explain how to assign values to
variables. It is a fundamental concept that allows programmers to store and
manipulate data efficiently throughout a program. Finally, in Section 2.5, we
will explore mathematical operations using different types of operators that
help us add numbers, compare values, or make decisions.
In the next unit, you will learn about data handling in Python.

Expected Learning Outcomes


After completing this unit, you should be able to: 1
Block 1 Getting Started with Python

❖ describe different types of data that can be used and created in Python;
❖ write a Python statement and expression;
❖ assign values to Python variables;
❖ explain how to input values as per user’s choice; and
❖ carry out various types of mathematical operations using the suits of
operators in Python.

2.2 FIRST PYTHON PROGRAM


In general, in any programming language, a program is a collection of what is
called the 'constructs', which includes input, output, sequential execution,
conditional execution, repeated execution, reuse, etc., because the purpose of
writing a program is basically: input the data, process the data and output the
results. Once the user has developed a program with some objective, it is only
required for the user to input the desired (new) data as and when it is required
to carry out the same task, and the program will generate the output (result)
for that desired (new) data.
In the subsequent discussions, we will understand the different constructs of
the Python language, which we call Python 'statements'. Like every language
we use in our routine communication has some rules and grammar, every
programming language also has its own rules and grammar, which is called
'syntax'. Let us now explain the Python syntax.
Python Syntax
Python syntax is like grammar for Python programming language. Syntax
refers to the set of rules that define how to write and organise code so that
the 'Python interpreter' can understand and execute it correctly. These rules
ensure that the code is structured, formatted, and error-free. We will learn the
syntax for different constructs when we get introduced to each of them.
We will first get introduced to the 'Output' statement. In Python, the
results/output is generated using the 'print' function. Note that a program is
also referred to as 'code' in technical terminology. Let us understand the print
statement by writing our first program:
The following program will simply output the text as it is, which the user wants
to print. The desired text will have to be enclosed using the quotation marks at
the beginning and end of the text to be displayed, but these quotation marks
will not appear in the result/output.
Example 1: The syntax for printing the text is as follows:
print ('Programming is Fun !!')
Upon executing the above code, the following output is generated:
Programming is Fun !!
The parentheses after the keyword 'print' indicates that 'print' is a function.
Thus, in general, any named object, which we refer to as an 'identifier', should
be followed by a parenthesis in Python if it is defined as a function (it can be a
2
Unit 2 Data Types and Operators in Phython

built-in function or a function created by the user, which will be discussed later
in Block 2).
In Python, identifiers are unique names that are assigned to variables,
functions, classes, and other entities. They are used to identify the entity
uniquely within the program. They should start with a letter (a-z, A-Z) or an
underscore "_" and can be followed by letters, numbers, or underscores.
For the naming of an identifier, the following rules need to be followed:
• Identifiers can be composed of alphabets (either uppercase or lowercase),
numbers (0-9), and the underscore character ( _ ). They should not include
any special characters or spaces.
• The starting character of an identifier must be an alphabet or an
underscore.
• Each identifier should have a distinct name to avoid conflicts within a
specific scope.
We should not use reserved words, known as keywords in Python, to name
objects/identifiers. These keywords are predefined and have a special
meaning and purpose for which they should be strictly used, as in the
grammar of any programming language. Some of these keywords are given as
follows:
False await else import pass None break
except in raise True class finally is
return and continue for lambda try As
def from nonlocal while assert del Global
not with async elif if or Yield

Comments in Python
Comments in Python are statements written within the code. They are meant
to explain, clarify, or contextualise specific parts of the code. The purpose of
comments is to explain the workings of a code, which does not impact the
execution or outcome of a program.
Python Single Line Comment
Single line comments are preceded by '#' symbol hash. Everything after this
symbol on the same line is considered a comment. Alternatively, the comment
can be enclosed in single (‘ ’) or double (“ ”) triple quotes (‘ ‘ ‘comment’ ’ ’ or “ “
“comment” ” ”).
Python Multi-line Comment
Python does not have a specific syntax for multi-line comments. However,
programmers often use multiple single-line comments, one after the other, by
putting ‘#’ symbol at the beginning of each line or enclosing the comment in
triple quotes (either ‘ ‘ ‘ or “ “ “).
Comments in Python are the lines in the code that are ignored by the
interpreter during the execution of the program.
Some of the advantages of writing comments in the code are:
• Comments enhance the readability of the code. 3
Block 1 Getting Started with Python

• Comments can be used to identify the functionality or structure of the


code.
• Comments can help understand unusual or tricky scenarios handled by
the code to prevent accidental removal or changes.
• Comments can be used to prevent executing any specific part of the
code while the code is under the testing phase and the programmer is
likely to have changes in the code.
Example 2: The first program which discussed earlier in Example 1 can be
written by including the comment as follows:
# This is our first Python program.
'''This program introduces the use of print function'''
print('Programming is Fun !!')
Executing the above code will generate the same output as earlier, as the
comments are non-executable statements, as mentioned earlier.
Now, let us answer the following Self Assessment Questions for practice.

SAQ 1
1. Define the term syntax in any programming language.
2. Write the complete syntax of the ‘print’ function and explain the
significance of each of the parameters.
3. Explain different ways of inserting comments in a Python program. Also,
discuss the pros and cons of each of the commenting styles.

2.3 DATA TYPES IN PYTHON


Variables in Python are named identifiers/objects pointing to objects in
memory. Unlike some other languages, it is not required to declare a variable's
type in Python explicitly. The Python interpreter will dynamically determine the
type based on the value assigned. Python includes a variety of data types,
which are essential for efficiently managing numbers, text, collections, and
logical operations. Let us now discuss some of the most commonly used data
types.
1. String Type
A string is also referred to as ‘str’. A string is a collection (sequence) of
characters used to store text. The string is to be enclosed in single or
double quotation marks. For example, x = "hello".

In the first program described in Section 2.2, “programming is Fun !!” is a


string, which could have also been written as ‘Programming is Fun !!’
instead of the earlier statement.
The Python interpreter will assign/consider/associate the ‘type’ with
each data the user provides in the code. If the user wants to check which
data type is assigned to the specific data provided by him/her, then it can
be done as follows:
4
Unit 2 Data Types and Operators in Phython

Example 3: Suppose we want to define a string ‘A string is a collection of


characters’ giving it a name ‘s’, then the type of ‘s’ can be checked with the
help of type() and print() functions by writing the following code:

s = 'A string is a collection of characters'


print('The string you have inputted is:', s)
print('The type of s is:')
print(type(s))

The output will be:

The string you have inputted is: A string is a collection of characters


The type of s is:
<class 'str'>
From the above code, some other important features of the ‘print()’ function
may also be noticed:
(i) By default, every ‘print’ statement prints the output in a newline.
(ii) We can print multiple components in a single ‘print’ statement by writing
commas.
(iii) After the comma, the next component will be printed, separated by a
space (also called whitespace).
If a user wants to understand/learn how a ‘print’ statement can be written in
Python, help can be asked from the interpreter by writing the following code:
help(print)
The output will display the syntax and its explanation as follows:

This output shows that the ‘print()’ function has five parameters, namely,
‘value’, ‘sep’, ‘end’, ‘file’ and ‘flush’. The ‘. . .’ symbol indicates that there
could be more than one value the user might wish to print. We will now
understand only the first three parameters of the ‘print()’ function.
(i) value: It specifies the object or string to be printed. If more than one
value needs to be printed, the user must make a comma-separated list
of all of them.
(ii) sep: The parameter ‘sep’ is specified as “sep = ‘ ’ ”, i.e., a blank space
or whitespace is a default value for the parameter ‘sep’, which means

5
Block 1 Getting Started with Python

after printing one value, a space will be printed before printing the next
value, by default. This feature can be noticed in the following statement:

print (' The string you have inputted is: ', s)

In our code in Example 3, where it can be observed in the output that


after printing 'The string you have inputted is: ', the string ‘A string is a
collection of characters’ is printed after a space character.
(iii) end: The parameter ‘end’ is specified as “end = \n”, i.e., ‘ \n ’ is the
default value for parameter ‘end’. Here, ‘ \n ’ is called a newline or a line
feed character, which will instruct the interpreter to display the output
mentioned in the ‘print’ statement in the next line. This is the reason why
the output intended by all three print statements in Example 3 has been
printed in three separate lines.
When we say some parameter in the syntax of a function is ‘default’, it means
if nothing is specified by the user as a value of that parameter, the default
value which is specified in the syntax will be used as a value of that parameter
when that function will execute. Otherwise, the user has a choice to specify a
different value for that parameter.
Example 4: Let us understand this feature of the ‘print()’ function by writing
the following code:
# The following two lines of code will print strings s1 and s2 in #
separate lines
s1 = "Hello"
s2 = "Everyone!!"
print(s1)
print(s2)
# The following two lines of code will print strings s1 and s2 in the #
same line but will separate them by a tab '\t'
print(s1, end = '\t')
print(s2)
# The following line of the code will print strings s1 and s2 in same # line
but separated by a space
print(s1, s2)
# The following line of the code will print strings s1 and s2 in same # line
but separated by a hyphen '-'
print(s1, s2, sep = '-')
The output, as explained in the code itself in comments, will be as follows:
Hello
Everyone!!
Hello Everyone!!
Hello Everyone!!
6
Unit 2 Data Types and Operators in Phython

Hello-Everyone!!
2. Numeric Type
There are following two numeric data types:
(i) integer: The integer value is referred to as ‘int’ or ‘fixed-point’ in
computer terminology. As it is clear from its name, integer values are
those values that store whole numbers (positive and negative integers
including zero) without a decimal point. For example,
x = 10.
print(x)
print(type(x))

10
<class 'int'>
(ii) floating-point
The ‘floating-point’ value is referred to as ‘float’. Floating-point values
store real numbers (values with fractions and also positive or negative,
i.e., numbers with decimal points). For example,
x = 3.14
print(x)
print(type(x))

3.14
<class 'float'>
3. Boolean Type
A Boolean type is referred to as Bool, which represents logical values:
True or False. This data type is often used to define conditions and is
essential for decision-making while writing programs. For example, x =
True.
Apart from this, another data type known as sequence types (list and
tuple) is also frequently used. They are ordered and used to store
multiple values in a single variable. Lists are changeable (mutable
collection) and allow duplicate elements, while tuples are similar to lists
but cannot be changed after creation (Immutable collection). For
example, list: x = [1, 2, 3] and tuple: x = (1, 2, 3). We will discuss lists
and tuples in the next unit in more detail.
Now, you can answer the following Self Assessment Questions for practice.

SAQ 2
1. Discuss the three basic data types in Python.
2. Explain the default parameters in a function definition.

7
Block 1 Getting Started with Python

2.4 STATEMENTS AND EXPRESSIONS


In general, a statement in Python is an instruction that an interpreter can
execute. There are different types of statements in Python, such as
assignment, conditional, looping, etc. These statements are used to develop
the code or program for the desired purpose that will produce the required
output. Here, we will discuss assignment statements. You will learn more
about the conditional and looping statements in Unit 4.
Any line of code in programming is called a ‘statement’. For example, we have
noticed ‘print’, ‘input, or simple assignment statements like ‘a = 2’, ‘b = 4.5’, ‘s
= “hello !” ’, etc.
Note that if you write the statements in Python console, they will appear with
the prompt ‘ >>> ’. Otherwise, they could be written using any other editor like
Spyder or Jupyter Notebook, as we considered in the previous sections of this
unit. As discussed, suppose it is required to create some variables and assign
them values in Python, then it can be done with the help of statements like:
x=1
y=2
These two statements are called assignment statements in which the variables
‘x’ and ‘y' are created, and specific values are assigned to them. Thus, a
general syntax for an assignment statement is:
Variable = Value
The mechanism used to assign a Value to the Variable is also known as
initialising the variables, i.e., the variables are assigned the values at the time
of their creation.
2.4.1 Assign Values to Variables
When values are fixed or known beforehand, we can assign the values to
variables using direct assignment statements. It helps store values in memory
using meaningful names (variables), making the code more readable and
easier to manage. These assignments are especially useful when values are
constant or known ahead of time (apriori), and we want to set initial
parameters or configuration values or define default values for use in a
program.
Example 5: In Python, we can assign a value to a variable using the
assignment operator (=) shown as follows:
name = "IGNOU" # Assign the string "IGNOU" to the variable name
x=4 # Assign the integer 4 to variable x
pi = 3.14 # Assign the float value 3.14 to variable pi
a, b = 10, 20 # Assign multiple variables in a line, i.e., 10 to a and 20 to b
x=y=z=0 # Assign same value to multiple variables, i.e. 0 to x, y and z
Note that you can also assign values dynamically from other data structures,
such as list and tuple.
8
Unit 2 Data Types and Operators in Phython

2.4.2 Expressions
We can assign values computed within a program based on mathematical
operations or expressions. An expression is a combination of operators and
operands executed to produce some other value. For example, x = 2 + 3, x = a
+ b, etc.
An expression in Python may be written as:
Variable = Expression
Where the variable is any named object/identifier.
We will elaborate on the operators and operands in Section 2.4.
2.4.3 Values Input by Users
Alternatively, the variable can be created first, and then the value can be
assigned. In this case, we need to assign values to variables while running the
program instead of assigning fixed values in advance. The variables may have
different values when we want to run some code for a different data set to do a
more generalised programming. Therefore, every programming language
needs to facilitate the user's input of the data as per requirement at a specific
instance. These values can be given or calculated by the user.
For this purpose, most of the programming languages have built-in functions
to facilitate this task. In Python, there is an ‘input’ function for this purpose. You
can ask the user to enter a value and assign it to a variable with the help of the
input() function. In Python, the ‘input()’ function enables users to input their
desired data values of any type. The program execution halts until the user
provides input and presses "Enter". The entered data is then returned as a
string, integer, or floating-point value, depending on the user's specifications.
Example 6: The following code allows the user to input the different types of
values of their choice and will output the values along with their types:
name = input("Enter your Programme Name: ")

print("Welcome to the Programme: ,", name)

The above statement will halt the program execution and allow the user to
input the data by giving a message on Python console:
Enter your Programme Name:
At this point, user will input the value which will be then assigned to variable
‘name’. The above code will produce the following output:
Enter your Programme Name: MSCAST
Welcome to the Programme: MSCAST
Note that we just need to write ‘input( )’ when we need to enter strings or
characters. It is a general practice to mention a kind of message in the
parentheses following the keyword ‘input’, which is called ‘prompt’ to
facilitate/guide the user in understanding what kind of data is expected to be
inputted at that stage. It is useful for the user to keep track of entering the
appropriate data values when many data values are to be entered for a code.

9
Block 1 Getting Started with Python

Suppose the user actually intended to enter the numeric data but forgot to
specify either ‘eval’ or ‘int’ or ‘float’ before ‘input’. Then, the numeric value
entered by the user will be treated as a ‘string’ by the interpreter, as shown in
the following code:
age = input("enter your age: ")
print("age = ", age, "and class of age: ", type(age))
The resulting output is shown as follows
enter your age: 25
age = 25 and class of age: <class 'str'>
By default, input() returns a string, and it is clear now that if you need another
type (like int or float), you should convert it first. When particularly an integer
value is to be entered, the keyword ‘int’ should precede the keyword ‘input’.
When particularly a floating-point value is to be entered, the keyword ‘float’
should precede the keyword ‘input’. From the following code and output, you
will understand these points:
age = int(input("enter your age: ")) #convert string to integer
#print age and its class to check
print("age = ", age, "class of age:", type(age))
weight = float(input("enter your weight: ")) #convert string to float
#print weight and its class to check
print("weight = ", weight, "class of weight: ", type(weight))
Output:
enter your age: 25
age = 10 class of age: <class 'int'>
enter your weight: 60.5
weight = 60.5 class of weight: <class 'float'>
The keyword ‘eval’ preceding ‘input’ may be specified when we input the
numeric values. The ‘eval’ is a common specification which allows the user to
input an integer of floating-point value. It automatically decides the data type
by the interpreter depending on the value entered. For examples,
age = eval(input("enter your age: "))
#print age and its class to check
print("age = ", age, "class of age: ", type(age))
weight = eval(input("enter your weight: "))
#print weight and its class to check
print("weight = ", weight, "class of weight: ", type(weight))
It will provide the same output as we obtained by int() and float() functions.

10
Unit 2 Data Types and Operators in Phython
If the user specifies ‘float’ with ‘input’, the data will be considered as floating -
point even if the user enters an integer value, as can be seen from the
following code:
age = float(input("enter your age: "))
print("age = ", age)
Output:
enter your age: 25
age = 25.0
However, if the user specifies the type as ‘int’ with ‘input’ but enters a floating-
point value, it will produce an error as shown in the following code:
a = int(input("enter a number:"))
print("a=", a)
Output:

Type Conversion / Type Casting


This feature in many high-level programming languages allows the user to
convert one type of data to another (depending on feasibility), or at times, the
compiler/interpreter converts the data of one type to another on its own.
For example, you have seen that we entered the numeric value ‘25’, but due to
no specification of ‘int’ or ‘float’ before ‘input()’, the interpreter has converted it
to string, which is conversion to lower type. We had also specified the type
‘float’ before ‘input()’ but entered the integer value ‘25’, so it was converted to
25.0 as a ‘floating-point’ value, which is a conversion to a higher type.
However, when we specified ‘int’ before the ‘input()’ function and entered a
floating-point value, the interpreter could not convert it to ‘int’ and produced an
error.
Now, you can answer the following Self Assessment Questions for practice.

SAQ 3
1. What is an assignment statement?
2. How would you input a string, an integer value and a real value in
Python?
3. Explain how you would specify a Python ‘statement’ and expression
while writing a code, giving an example.

2.5 VARIOUS OPERATORS IN PYTHON


11
Block 1 Getting Started with Python

Like any programming language, Python has numerous types of operators


used to perform operations on variables and values. Some commonly used
operators are as follows:
1. Assignment Operators
As discussed in the previous section, while defining an assignment
statement, e.g. x = 4, the variable ‘x’ is created, and a specific value 4 is
assigned to it. Here, ‘=’ is called the “assignment operator” as its role is
to assign the value specified on the right-hand side of operator ‘=’ to the
variable specified to the left-hand side of operator ‘=’.
2. Arithmetic operators
In Python there are several arithmetic operators used in Python, such as
the addition operator (+), subtraction operator (-), multiplication operator
(*), division (float division) operator (/), floor division (integer division)
operator (//), modulo operator (%), and exponentiation (power) operator
(**).
For example, we can define the addition operator as: add = a+ b. In the
expression “add = a + b”, ‘add’ is the name of a variable; ‘a + b’ is an
expression and ‘=’ is an assignment operator. When this statement is
executed first, the expression on the right hand is executed to evaluate a
value. Then, this value is assigned to the variable ‘add’ specified on the
left-hand side of the assignment operator. You can print these values
using the ‘print()’ function, as discussed in Section 2.2.
Let us consider an example to explain the use of arithmetic operators.
Example 7: The following program demonstrates the use of the arithmetic
operators:
a=7
b=5
add = a + b
print("sum of a and b is:", add)
diff = a - b
print("difference of a and b is:", diff)
prod = a * b
print("product of a and b is:", prod)
float_div = a / b
print("float division of a and b =", float_div)
floor_div = a // b
print("floor division of a and b =", floor_div)
remainder = a % b
print("remainder after dividing a by b =", remainder)
cube = a**3
12
Unit 2 Data Types and Operators in Phython

print("cube of a =", cube)


This code produces the following output:
sum of a and b is: 12
difference of a and b is: 2
product of a and b is: 35
float division of a and b = 1.4
floor division of a and b = 1
remainder after dividing a by b = 2
cube of a = 343
It can be noticed that the division ‘a / b’ = 7/5 = 1.4 is the usual division.
Whereas the floor division is ‘a // b’ = 7 // 5 = 1, that is, it produces the quotient
of operation ‘a / b’. Similarly, using a modulo operator in operation, i.e., ‘a%b’
will produce the remainder after dividing ‘a’ by ‘b’. For example, 7 % 5
produces the remainder 2.
Note that in the above statements, for example, ‘add = a + b’, the expression
is ‘a + b’. In the expression ‘a + b’, ‘a’ and ‘b’ are called ‘operands’ and ‘+’ is an
operator. All the arithmetic operators discussed above are also called ‘binary’
operators as they have two operands. However, there can also be an operator
which requires only one operand, for example, the negation (-) operator. Its
symbol is the same as the subtraction operator, but it is used to negate the
value. For example,
x=3
y = -x
Thus, the negation operator used in the statement ‘y = -x’ is a unary operator.
Use of + and * operators with strings
Unlike any other programming language, in Python, two of the arithmetic
operators, ‘+’ and ‘*’, can also be used with ‘string’ data. The ‘+’ operator
concatenates or joins two strings, and the ‘*’ operator repeats the string a
number of times.
Example 8: Let us consider an example to describe ‘+’ and ‘*’ operators
shown as follows:
stat1 = 'hello'
stat2 = 'everyone'
stat3 = stat1 + stat2
print('string stat3 =', stat3)
stat4 = stat1 + ' ' + stat2 + '!'
print('string stat4 =', stat4)
stat5 = stat1*3
print('string stat5 =', stat5)
print('Inserting space in-between:', 'Hello '*3) 13
Block 1 Getting Started with Python

The above code will give the following output:


string stat3 = helloeveryone
string stat4= hello everyone!
string stat5= hellohellohello
Inserting space in-between: Hello Hello Hello
3. Compound Assignment Operators
Many times, updating the value of variables while programming is
required. The compound assignment operators are used to combine
operations and assignments in one statement. For example, if we
want to update the value of variable x by 1 in Python, then it can be
done by writing a code as discussed earlier:
x=x+1
There is another operator called ‘compound addition operator’, denoted
as ‘+ =’, that can be used to carry out the above operation as follows:
x+=1
Similarly, we can use the ‘compound subtraction operator’, denoted as ‘-
=’, as:
y-=5
Which works in a similar manner as:
y=y–5
Likewise, ‘compound multiplication operator’:
a=a*b
is similar to
a*=b
Also, the ‘compound division operator’
n = n / 10
is the same as:
n / = 10
This also works with the ‘modulo operator’, so
x = x % 10
works similarly as:
x % = 10
4. Comparison (Relational) Operators
Another set of operators in Python is that of relational operators. There
are six relational operators. Suppose ‘a’ and ‘b’ are two variables or
expressions. Then, these operators can be used with ‘a’ and ‘b’ as
described in the following table:

14
Operator Use Explanation
Unit 2 Data Types and Operators in Phython
Check whether two variables or expressions have
= = (equal to) a==b
the same values.
Check whether one variable or expression has a
< (less than) a<b
value less than the other variable or expression.
< = (less Check whether one variable or expression has a
than or equal a<=b value less than or equal to the other variable or
to) expression.
Check whether one variable or expression has a
> (greater
a>b value greater than the other variable or
than)
expression.
> = (greater Check whether one variable or expression has a
than or equal a>=b value greater than or equal to the other variable
to) or expression.
Check whether one variable or expression does
! = (not equal
a!=b not have the same value as the other variable or
to)
expression.

When these operators are used, they will produce the result in terms of a
‘Boolean’ value. The ‘Boolean’ values are labelled as ‘True’ or ‘False’ in Python.
In general, ‘Boolean’ variables in any programming language are those that take
one of the two possible values, such as 0 or 1, True or False, etc.
Example 9: The following code demonstrates the use of relational operators
and their result as a Boolean value:
x = 5 ; y = 10 ; z = 15
r1 = ((x+y) == z)
print('r1:', r1)
r2 = x < y
print('r2:', r2)
r3 = y > z
print('r3:', r3)
r4 = ((z-y) < = x)
print('r4:', r4)
r5 = ((x+z) ! = y)
print('r5:', r5)
Output
r1: True
r2: True
r3: False
r4: True
r5: True
5. Logical operators
There are three logical operators in Python: ‘and’, ‘or’ and ‘not’. While
the relational operators are used to check conditions, the logical
operators are used to compound two or more conditions, that is, to 15
Block 1 Getting Started with Python

check whether multiple conditions are simultaneously satisfied or not.


Suppose ‘x’ and ‘y’ are two conditions. When we use logical operators
with two or more conditions, the result will be produced in terms of
Boolean values: ‘True’ or ‘False’. The use of logical operators is shown
in the following table:
Operator Use Explanation
The final result will be determined depending on
and x and y whether conditions ‘x’ and ‘y' are evaluated as ‘True’
or ‘False’.
The final result will be determined depending on
or x or y whether conditions ‘x’ or ‘y' are evaluated as ‘True’ or
‘False’.
It will produce the result as ‘True’, if condition ‘x’
not not x evaluates to ‘False’ and will produce the result as
‘False’, if condition ‘x’ evaluates to ‘True’.

Let ‘x’ and ‘y’ be two conditions. The result of checking compound conditions
using logical operators (and, or) can be understood from the following table,
also known as the ‘Truth Table’:
Table: Use of Operator ‘and’
Result of ‘x’ Result of ‘y’ Result of (x and y)
True True True
True False False
False True False
False False False

It indicates that while using the ‘and’ operator, the compound conditions will
only result in ‘True’ when all conditions result in ‘True’. Thus, the ‘and’ operator
works like an ‘intersection’ operator in the set theory.
Table: Use of Operator ‘or’
Result of ‘x’ Result of ‘y’ Result of (x and y)
True True True
True False True
False True True
False False False

Thus, while using the ‘or’ operator, the compound conditions will answer ‘True’
even if at least one of the conditions results in ‘True’. It will only answer ‘False’
when all the conditions are evaluated as ‘False’. Thus, the ‘or’ operator works
like a ‘union’ operator in the set theory.
Table: Use of Operator ‘not’
Result of ‘x’ Result of ‘not x’
True False
False True
Thus, while using the ‘not’ operator, the answer will be ‘False’ if condition ‘x’
results in ‘True’, and the answer will be ‘True’ if condition ‘x’ results in ‘False’.
That is, the ‘not’ operator works like the ‘complement’ operator in the set
16 theory.
Unit 2 Data Types and Operators in Phython

Example 10: Let us understand the use of logical operations from the
following code:
x = 5 ; y = 10 ; z = 15
r1 = (x < 10 and y < 10) # or you can write without parentheses
print('r1:', r1)
r2 = x >= 5 and y < 20
print('r2:', r2)
r3 = y > 10 or z > 10
print('r3:', r3)
r4 = x > 10 or y > 10
print('r4:', r4)
r5 = not x > 10
print('r5:', r5)
The output is:
r1: False
r2: True
r3: True
r4: False
r5: True
Now, you can answer the following Self Assessment Questions for practice.

SAQ 4
1. Explain the role of an ‘operator’ in any programming language.
2. Write a note on the arithmetic operators in Python.

Let us now summarise what you have learnt in this unit.

2.6 SUMMARY
In this unit, we have discussed:
• Various data types form the foundation of Python programming. Some
common data types include numeric types such as integers (int),
floating-point numbers (float), and string (str) for handling character data,
as well as Boolean values (bool) to represent logical truth values (True
and False).
• Python allows a wide range of mathematical operations to be performed
on numeric data. These include basic arithmetic like addition (+),
subtraction (-), multiplication (*), and division (/), along with advanced
operations such as floor division (//), modulus (%), and exponentiation
(**).

17
Block 1 Getting Started with Python

• A statement is an instruction that the interpreter can execute, such as


assigning a value to a variable or printing a result.
• We can assign values computed within a program based on
mathematical operations or expressions. Assigning values to variables is
straightforward using the = operator (e.g., x = 10).
• Python features a wide variety of operators used to perform operations
on variables and data. Arithmetic operators perform mathematical
functions. Assignment operators like =, +=, and -= are used to store or
update values in variables.
• While comparison operators such as ==, !=, >, and < compare two
values and return a Boolean result. Logical operators (and, or, not) are
used to combine multiple conditions, while Boolean operators specifically
deal with True and False values.

2.7 TERMINAL QUESTIONS


1. State the rules for naming an identifier in Python.
2. Write a short note on ‘keywords’ in a programming language.
3. Explain the use of ‘eval’, ‘int’ and ‘float’ specifications with an ‘input()’
function in Python.
4. Differentiate between the ‘/’ and ‘//’ operators while carrying out division
in Python.
5. Explain the use of ‘+’ and ‘*’ operators with string variables.

2.8 SOLUTIONS / ANSWERS


Self Assessment Questions (SAQs)
1.1. Refer to Section 2.2.
1.2. Refer to Section 2.2.
1.3. Refer to Section 2.2.
2.1. Refer to Section 2.3.
2.2. Refer to Section 2.3.
3.1. Refer to Section 2.4.
3.2. Refer to Section 2.4.
3.3. Refer to Section 2.4.
4.1. Refer to Section 2.5.
4.2. Refer to Section 2.5.

Terminal Questions (TQs)


1. Refer to Section 2.2.
2. Refer to Section 2.2.
3. Refer to Section 2.3.
18
Unit 2 Data Types and Operators in Phython

4. Refer to Section 2.4.


5. Refer to Section 2.4.

19

You might also like