Python 2
Python 2
INTRODUCTION TO PYTHON
Structure
1.1 Introduction Jupyter Notebook
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
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
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
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:
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
Now, you can answer the following Self Assessment Question for practice.
SAQ 2
Describe the stepwise Python installation process.
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
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
11
Block 1 Getting Started with Python
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
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
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
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
• 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.
SAQ4
Explain the following terms:
(i) Anaconda Distribution
(ii) Anaconda Navigator
(iii) Anaconda Prompt
18
Unit 1 Introduction to Python
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)
SAQ5
What is a Python module? How can a particular function from a specific
Python module be used in a current working environment?
• 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':
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?
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
24
UNIT 2
DATA TYPES AND OPERATORS
IN PYTHON
Structure
2.1 Introduction Values Input by users
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.
❖ 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.
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
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.
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:
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.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: ")
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:
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.
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
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.
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
19