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

Python Unit 1

This document provides an introduction to Python programming, including its history, features, and installation instructions. It discusses the versatility of Python in various applications, its syntax compared to other languages, and details on using the Python interpreter and Jupyter Notebook. The document also outlines the steps for installing Python on Windows and creating notebooks in Jupyter for coding and data visualization.

Uploaded by

muditadave.nagar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views69 pages

Python Unit 1

This document provides an introduction to Python programming, including its history, features, and installation instructions. It discusses the versatility of Python in various applications, its syntax compared to other languages, and details on using the Python interpreter and Jupyter Notebook. The document also outlines the steps for installing Python on Windows and creating notebooks in Jupyter for coding and data visualization.

Uploaded by

muditadave.nagar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Python Programming [CA3EL06] Unit#1

Introduction to python:

Python Tutorial | Python Programming Language

Python is a popular programming language. It was created by Guido van Rossum, and released
in 1991.

It is used for:

 web development (server-side),


 software development,
 mathematics,
 System scripting.

What can Python do?

 Python can be used on a server to create web applications.


 Python can be used alongside software to create workflows.
 Python can connect to database systems. It can also read and modify files.
 Python can be used to handle big data and perform complex mathematics.
 Python can be used for rapid prototyping, or for production-ready software development.

Why Python?

 Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
 Python has a simple syntax similar to the English language.
 Python has syntax that allows developers to write programs with fewer lines than some
other programming languages.
 Python runs on an interpreter system, meaning that code can be executed as soon as it is
written. This means that prototyping can be very quick.
 Python can be treated in a procedural way, an object-oriented way or a functional way.

Python Syntax compared to other programming languages

 Python was designed for readability, and has some similarities to the English language
with influence from mathematics.
 Python uses new lines to complete a command, as opposed to other programming
languages which often use semicolons or parentheses.
 Python relies on indentation, using whitespace, to define scope; such as the scope of
loops, functions and classes. Other programming languages often use curly-brackets for
this purpose.

Example:
print("Hello, World!")

Professor Mudita Dave Nagar Page 1


Python Programming [CA3EL06] Unit#1

Python History and Version:

o Python laid its foundation in the late 1980s.


o The implementation of Python was started in December 1989 by Guido Van Rossum at
CWI in Netherland.
o In February 1991, Guido Van Rossum published the code (labeled version 0.9.0) to
[Link].
o In 1994, Python 1.0 was released with new features like lambda, map, filter, and reduce.
o Python 2.0 added new features such as list comprehensions, garbage collection systems.
o On December 3, 2008, Python 3.0 (also called "Py3K") was released. It was designed to
rectify the fundamental flaw of the language.
o ABC programming language is said to be the predecessor of Python language, which was
capable of Exception Handling and interfacing with the Amoeba Operating System.
o The following programming languages influence Python:
o ABC language.
o Modula-3

Why the Name Python?

There is a fact behind choosing the name Python. Guido van Rossum was reading the script of a
popular BBC comedy series "Monty Python's Flying Circus". It was late on-air 1970s.

Van Rossum wanted to select a name which unique, sort, and little-bit mysterious. So he decided
to select naming Python after the "Monty Python's Flying Circus" for their newly created
programming language.

The comedy series was creative and well random. It talks about everything. Thus it is slow and
unpredictable, which made it very interesting Python is also versatile and widely used in every
technical field, such as Machine Learning, Artificial Intelligence, Web Development, Mobile
Application, Desktop Application, Scientific Calculation, etc. A list of Python versions with its
released date is given below

Python Version Released Date

Python 1.0 January 1994

Python 1.5 December 31, 1997

Professor Mudita Dave Nagar Page 2


Python Programming [CA3EL06] Unit#1

Python 1.6 September 5, 2000

Python 2.0 October 16, 2000

Python 2.1 April 17, 2001

Python 2.2 December 21, 2001

Python 2.3 July 29, 2003

Python 2.4 November 30, 2004

Python 2.5 September 19, 2006

Python 2.6 October 1, 2008

Python 2.7 July 3, 2010

Python 3.0 December 3, 2008

Python 3.1 June 27, 2009

Python 3.2 February 20, 2011

Python 3.3 September 29, 2012

Python 3.4 March 16, 2014

Python 3.5 September 13, 2015

Python 3.6 December 23, 2016

Python 3.7 June 27, 2018

Python 3.8 October 14, 2019

How to Install Python

Python is a popular high-level, general-use programming language. Python is a programming


language that enables rapid development as well as more effective system integration. Python
has two main different versions: Python 2 and Python 3. Both are really different.

Python develops new versions with changes periodically and releases them according to version
numbers. Python is currently at version 3.11.3.

Professor Mudita Dave Nagar Page 3


Python Programming [CA3EL06] Unit#1

Python is much simpler to learn and programme in. Any plain text editor, such as notepad or
notepad++, may be used to create Python programs. To make it easier to create these routines,
one may also utilise an online IDE for Python or even install one on their machine. IDEs offer a
variety of tools including a user-friendly code editor, the debugger, compiler, etc.

One has to have Python installed on their system in order to start creating Python code and
carrying out many fascinating and helpful procedures. The first step in learning how to
programming in Python is to install or update Python on your computer. There are several ways
to install Python: you may use a package manager, get official versions from [Link], or
install specialized versions for embedded devices, scientific computing, and the Internet of
Things.t

Installation on Windows

Visit the link [Link] to download the latest release of Python. In this process,
we will install Python 3.11.3 on our Windows operating system. When we click on the above
link, it will bring us the following page.

Step - 1: Select the Python's version to download.

Click on the download button to download the exe file of Python.

Professor Mudita Dave Nagar Page 4


Python Programming [CA3EL06] Unit#1

If in case you want to download the specific version of Python. Then, you can scroll down
further below to see different versions from 2 and 3 respectively. Click on download button right
next to the version number you want to download.

Step - 2: Click on the Install Now

ADVERTISEMENT

Double-click the executable file, which is downloaded.

Professor Mudita Dave Nagar Page 5


Python Programming [CA3EL06] Unit#1

The following window will open. Click on the Add Path check box, it will set the Python path
automatically.

Now, Select Customize installation and proceed. We can also click on the customize installation
to choose desired location and features. Other important thing is install launcher for the all user
must be checked.

Here, under the advanced options, click on the checkboxes of " Install Python 3.11 for all users ",
which is previously not checked in. This will checks the other option " Precompile standard
library " automatically. And the location of the installation will also be changed. We can change
it later, so we leave the install location default. Then, click on the install button to finally install.

Step - 3 Installations in Process

Professor Mudita Dave Nagar Page 6


Python Programming [CA3EL06] Unit#1

The set up is in progress. All the python libraries, packages, and other python default files will be
installed in our system. Once the installation is successful, the following page will appear saying
" Setup was successful ".

Step - 4: Verifying the Python Installation

o Go to "Start" button, and search " cmd ".


o Then type, " python - - version ".
o If python is successfully installed, then we can see the version of the python installed.
o If not installed, then it will print the error as " 'python' is not recognized as an internal
or external command, operable program or batch file. ".

Professor Mudita Dave Nagar Page 7


Python Programming [CA3EL06] Unit#1

Python Interpreter:

A python interpreter is a computer program that converts each high-level program


statement into machine code. An interpreter translates the command that you write out
into code that the computer can understand. However, to better understand this definition,
we must explain what high-level and low-level languages are.

What is the difference between a python interpreter and a compiler?

Let’s now discuss the differences between a Python interpreter and a Python compiler.

Computer programs are generally written in a high-level language also called source code. Since
machines don’t understand this type of language, the language needs to be transformed into
binary or machine code, which machines understand.

Compilers and interpreters make this transformation possible. However, while they both have the
primary function of changing source code into machine code, there are differences between
them.

These two remarkable tools significantly differ in how they translate the source code.

Interpreters translate source code one statement at a time. On the other hand, the compiler first
scans the entire program and then translates the whole program into machine code.

These two methods of translating code present unique opportunities and challenges. Let’s
consider these.

 Interpreters translate programs one statement at a time, unlike compilers that do “batch
translation.” Therefore, interpreters usually take less time to analyze the source code. However,
while they analyze code faster, compilers execute the code faster than interpreters.
 Secondly, because interpreters don’t generate any Object code, they are more memory efficient
than compilers.

Are compilers better than interpreters, then?

It depends on what you want. Programs with interpreters can run right away and be started faster.
Furthermore, interpreters make debugging your code easier since they identify line-by-line
errors.

Any changes made to the code written via a compiler will require it to be converted. Compilers
no longer use computing power, making them more efficient.

Professor Mudita Dave Nagar Page 8


Python Programming [CA3EL06] Unit#1

How does an interpreter work in python?

The Python interpreter is CPython and is written in the C programming language. So how does
CPython work? Let’s see.

Interpreters start with source code analysis.

First, the interpreter checks or analyzes the source code. By now, we assume you know what the
source code means. It’s the high-level language you write programs in.

So, CPython receives the source code and initializes several commands to do some vital things.

First, the interpreter ensures you follow Python’s syntax for writing code.

It also checks for incorrect lines of code. If it encounters any error in a line, it stops the program
from running and produces an error message.

This analysis divides the source code files into a list of tokens.

The interpreter then generates byte code.

After lexical analysis, which is the process described in the section above, the interpreter moves
to the second stage, byte code generation.

After receiving the tokens, the interpreter generates the Abstract Syntax Tree or AST. This tree is
converted to machine language (i.e., 1s and 0s). Because this is a Python interpreter, the code can
be saved in a file with the .pyc extension.
Next, the interpreter initializes a PVM.

The interpreter initializes the Python Virtual Machine (PVM) in the next step. PVM is crucial
because it’s what converts the byte code into binary code.

After conversion, the results are then printed. Python prints out the correct result if there are no
high-level language errors. Otherwise, it prints out an error message.

Now that we have a high-level view of how the compiler works, let’s now show you how to set
up and use a Python interpreter.

How To Use Jupyter Notebook


The Jupyter Notebook is an open-source web application that allows you to create and
share documents that contain live code, equations, visualizations, and narrative text.
Uses include data cleaning and transformation, numerical simulation, statistical
modeling, data visualization, machine learning, and much more. Jupyter has support for
over 40 different programming languages and Python is one of them. Python is a

Professor Mudita Dave Nagar Page 9


Python Programming [CA3EL06] Unit#1

requirement (Python 3.3 or greater, or Python 2.7) for installing the Jupyter Notebook
itself.

Installation
Install Python and Jupyter using the Anaconda Distribution, which includes Python, the
Jupyter Notebook, and other commonly used packages for scientific computing and data
science. You can download Anaconda’s latest Python3 version. Now, install the downloaded
version of Anaconda. Installing Jupyter Notebook using pip:
python3 -m pip install --upgrade pip
python3 -m pip install jupyter
Starting Jupyter Notebook
To start the jupyter notebook, type the below command in the terminal.
jupyter notebook
This will print some information about the notebook server in your terminal, including the
URL of the web application (by default, [Link] and then open your default web
browser to this URL.

Professor Mudita Dave Nagar Page 10


Python Programming [CA3EL06] Unit#1

After the notebook is opened, you’ll see the Notebook Dashboard, which will show a list of the
notebooks, files, and subdirectories in the directory where the notebook server was started.
Most of the time, you will wish to start a notebook server in the highest level directory
containing notebooks. Often this will be your home directory.

Professor Mudita Dave Nagar Page 11


Python Programming [CA3EL06] Unit#1

Creating a Notebook
To create a new notebook, click on the new button at the top right corner. Click it to open a
drop-down list and then if you’ll click on Python3, it will open a new notebook.

The web page should look like this:

Hello World in Jupyter Notebook


After successfully installing and creating a notebook in Jupyter Notebook, let’s see how to
write code in it. Jupyter notebook provides a cell for writing code in it. The type of code
depends on the type of notebook you created. For example, if you created a Python3 notebook
then you can write Python3 code in the cell. Now, let’s add the following code –

print("Hello World")

Professor Mudita Dave Nagar Page 12


Python Programming [CA3EL06] Unit#1

To run a cell either click the run button or press shift ⇧ + enter ⏎ after selecting the cell you
want to execute. After writing the above code in the jupyter notebook, the output was:

Note: When a cell has executed the label on the left i.e. ln[] changes to ln[1]. If the cell is still
under execution the label remains ln[*].

Cells in Jupyter Notebook


Cells can be considered as the body of the Jupyter. In the above screenshot, the box with the
green outline is a cell. There are 3 types of cell:
 Code
 Markup
 Raw NBConverter

This is where the code is typed and when executed the code will display the output below the
cell. The type of code depends on the type of the notebook you have created. For example, if
the notebook of Python3 is created then the code of Python3 can be added. Consider the below
example, where a simple code of the Fibonacci series is created and this code also takes input

Professor Mudita Dave Nagar Page 13


Python Programming [CA3EL06] Unit#1

from the user. Example:

The tex bar in the above code is prompted for taking input from the user. The output of the
above code is as follows: Output:

Professor Mudita Dave Nagar Page 14


Python Programming [CA3EL06] Unit#1

Markdown

Markdown is a popular markup language that is the superset of the HTML. Jupyter Notebook
also supports markdown. The cell type can be changed to markdown using the cell menu.

Adding Headers: Heading can be added by prefixing any line by single or multiple ‘#’
followed by space. Example:

Output:

Professor Mudita Dave Nagar Page 15


Python Programming [CA3EL06] Unit#1

Adding List: Adding List is really simple in Jupyter Notebook. The list can be added by using
‘*’ sign. And the Nested list can be created by using indentation. Example:

Output:

Adding Latex Equations: Latex expressions can be added by surrounding the latex code by
‘$’ and for writing the expressions in the middle, surrounds the latex code by ‘$$’. Example:

Professor Mudita Dave Nagar Page 16


Python Programming [CA3EL06] Unit#1

Output:

Professor Mudita Dave Nagar Page 17


Python Programming [CA3EL06] Unit#1

Adding Table: A table can be added by writing the content in the following format.

Output:

Note: The text can be made bold or italic by enclosing the text in ‘**’ and ‘*’ respectively.
Raw NBConverter
Raw cells are provided to write the output directly. This cell is not evaluated by Jupyter
notebook. After passing through nbconvert the raw cells arrives in the destination folder
without any modification. For example, one can write full Python into a raw cell that can only
be rendered by Python only after conversion by nb convert.
Kernel
A kernel runs behind every notebook. Whenever a cell is executed, the code inside the cell is
executed within the kernel and the output is returned back to the cell to be displayed. The
kernel continues to exist to the document as a whole and not for individual cells. For example,
if a module is imported in one cell then, that module will be available for the whole document.

Professor Mudita Dave Nagar Page 18


Python Programming [CA3EL06] Unit#1

See the below example for better understanding. Example:

Note: The order of execution of each cell is stated to the left of the cell. In the above example,
the cell with In[1] is executed first then the cell with In[2] is executed. Options for
kernels: Jupyter Notebook provides various options for kernels. This can be useful if you want
to reset things. The options are:
 Restart: This will restart the kernels i.e. clearing all the variables that were defined,
clearing the modules that were imported, etc.
 Restart and Clear Output: This will do the same as above but will also clear all the
output that was displayed below the cell.
 Restart and Run All: This is also the same as above but will also run all the cells in the
top-down order.
 Interrupt: This option will interrupt the kernel execution. It can be useful in the case
where the programs continue for execution or the kernel is stuck over some computation.

Naming the notebook


When the notebook is created, Jupyter Notebook names the notebook as Untitled as default.
However, the notebook can be renamed. To rename the notebook just click on the word
Untitled. This will prompt a dialogue box titled Rename Notebook. Enter the valid name for

Professor Mudita Dave Nagar Page 19


Python Programming [CA3EL06] Unit#1

your notebook in the text bar, then click ok.

Notebook Extensions
New functionality can be added to Jupyter through extensions. Extensions are javascript
module. You can even write your own extension that can access the page’s DOM and the
Jupyter Javascript API. Jupyter supports four types of extensions.
 Kernel
 IPyhton Kernel
 Notebook
 Notebook server
Installing Extensions
Most of the extensions can be installed using Python’s pip tool. If an extension can not be
installed using pip, then install the extension using the below command.
jupyter nbextension install extension_name
The above only installs the extension but does not enables it. To enable it type the below
command in the terminal.
jupyter nbextension enable extension_name

Top 10 Python Applications in Real World:

Python has been at the forefront of Machine learning, Data Science, and Artificial Intelligence
innovation. Further, Python applications offers provide ease in building a plethora of apps, web
development processes, and a lot more. In this blog, we will discuss the top 10 Python
applications in the real world in a detailed manner. So let’s get started:

Professor Mudita Dave Nagar Page 20


Python Programming [CA3EL06] Unit#1

1. Web Development
It is one of the most astonishing applications of Python. This is because Python comes up with
a wide range of frameworks like Django, Flask, Bottle, and a lot more that provide ease to
developers. Furthermore, Python has inbuilt libraries and tools which make the web
development process completely effortless. The use of Python for web development also
offers:
 Amazing visualization
 Convenience in development
 Enhanced security
 Fast development process
2. Machine Learning and Artificial Intelligence
Machine Learning and Artificial Intelligence are the hottest subjects right now. Python along
with its inbuilt libraries and tools facilitate the development of AI and ML algorithms. Further,
it offers simple, concise, and readable code which makes it easier for developers to write
complex algorithms and provide a versatile flow. Some of the inbuilt libraries and tools that
enhance AI and ML processes are:
 Numpy for complex data analysis
 Keras for Machine learning
 SciPy for technical computing
 Seaborn for data visualization
3. Data Science
Data science involves data collection, data sorting, data analysis, and data visualization.
Python provides amazing functionality to tackle statistics and complex mathematical
calculations. The presence of in-built libraries provides convenience to data science
professionals. Some of the popular libraries that provide ease in the data science process are
TensorFlow, Pandas, and Socket Learning. These libraries provide an ecosystem for fine-
tuning data models, data preprocessing, and performing complex data analysis.
4. Game Development
With the rapidly growing gaming industry, Python has proved to be an exceptional option for
game development. Popular games like Pirates of the Caribbean, Bridge Commander, and
Battlefield 2 use Python programming for a wide range of functionalities and add-ons. The
presence of popular 2D and 3D gaming libraries like pygame, panda3D, and Cocos2D makes
the game development process completely effortless.
5. Audio and Visual Applications:
Audio and video applications are undoubtedly the most amazing feature of Python. Python is
equipped with a lot of tools and libraries to accomplish your task flawlessly. Applications that
are coded in Python include popular ones like Netflix, Spotify, and YouTube. This can be
handled by libraries like
 Dejavu
 Pyo
 Mingus
 SciPy
 OpenCV
6. Software Development
Python is just the perfect option for software development. Popular applications like Google,
Netflix, and Reddit all use Python. This language offers amazing features like:
Professor Mudita Dave Nagar Page 21
Python Programming [CA3EL06] Unit#1

 Platform independence
 Inbuilt libraries and frameworks to provide ease of development.
 Enhanced code reusability and readability
 High compatibility
Apart from these Python offers enhanced features to work with rapidly growing technologies
like Machine learning and Artificial intelligence. All these embedded features make it a
popular choice for software development.
7. CAD Applications
CAD refers to computer-aided design; it is the process of creating 3D and 2D models digitally.
This application has replaced manual drift and is used by architects, product designers, and
construction managers to design products with extremely high consistency. Python is
embedded with amazing applications like Blender, Free CAD, open cascade, and a lot more to
efficiently design products. These provide enhanced features like technical drawing, dynamic
system development, recordings, file export, and import.
8. Business Applications
Python offers excellent security and scalability features that make it perfect for delivering
high-performance business applications. It has inbuilt libraries and tools like:
 Odoo is business management software that provides you with an automated solution for
your business process.
 Tryton is easy-to-use open-source business software. It has fully integrated features like
financial accounting, sales, CRM, purchasing, shipping, and the list goes on.
All these distinguishing features make it fit for creating business applications.
9. Desktop GUI
Python is an interactive programming language that helps developers to create GUIs easily and
efficiently. It has a huge list of inbuilt tools for Python usage are PyQT, kivy, wxWidgets, and
many other libraries like them to build a fully functional GUI in an extremely secure and
efficient manner.
10. Web Scraping Application
Web scraping is an automated process used to extract information from websites in an easier
and faster way. The information is used by researchers, organizations, and analysts for a wide
variety of tasks. Python has a wide range of features that make it suitable for web scraping
some of them are:
 A concise syntax enhances readability and saves you time.
 A wide range of libraries and tools like pandas, matplotlib, and Selenium makes the web
scraping process easy and efficient.
 Easy to use and understand
Some other real-world applications of Python are:
 Robotics and automation by the use of inbuilt libraries and tools like PyDy, Dart, PyRobot,
and Pyro.
 Image processing: some of the amazing libraries and tools for image processing are
Blender, OpenCV, Houdini, and PIL.
 Scientific applications are facilitated by popular libraries like Pandas, Matplotlib, SciPy,
and many more

Difference Between Python 2 and Python 3:

Professor Mudita Dave Nagar Page 22


Python Programming [CA3EL06] Unit#1

Feature Python 2 Python 3


Division In Python 2, the division operator In Python 3, the division operator always returns
Operator returns an integer if both operands a float.
are integers.
Print Statement In Python 2, the print statement is In Python 3, the print statement is used as
used as `print "Hello, World!"` `print("Hello, World!")` with parentheses.
Exception In Python 2, exception handling is In Python 3, exception handling is done using the
Handling done using the `except` keyword. `as` keyword.
Unicode In Python 2, Unicode support is In Python 3, Unicode is the default encoding and
Support optional and requires a separate requires no separate declaration.
declaration.
Range Function In Python 2, the `range` function In Python 3, the `range` function returns an object
returns a list. that generates values on the fly, making it more
memory-efficient.
xrange Function In Python 2, the `xrange` function In Python 3, the `xrange` function does not exist
generates a sequence of numbers, and is replaced by the `range` function.
similar to `range`.
Integer Division In Python 2, integer division can be In Python 3, integer division can be performed
performed using the `/` operator. using the `//` operator.
Syntax for In Python 2, the syntax for raising In Python 3, the syntax for raising exceptions is
raising exceptions is `raise Exception, `raise Exception("Error message")` with
exceptions "Error message"` parentheses.

Comparison of Python 2 and Python 3 with Example Code

Now that we know the differences between Python 2 and Python 3, let’s see examples of
code in both versions

Example 1: Print Statement

Python 2:
# Python 2

print "Hello, Python 2!"

Python 3:
# Python 3

print("Hello, Python 3!")

In Python 2, print is a statement and doesn’t require parentheses. In Python 3, print is a


function and needs parentheses.

Professor Mudita Dave Nagar Page 23


Python Programming [CA3EL06] Unit#1

Example 2: Division
Python 2:
# Python 2

result = 5 / 2

print(result) # Outputs 2

Python 3:

# Python 3

result = 5 / 2

print(result) # Outputs 2.5


In Python 2, division of integers results in floor division by default. Python 3 performs true
division by default.
Example 3: Input Function
Python 2:
# Python 2
user_input = raw_input("Enter something: ")
print("You entered: " + user_input)

Python 3:

# Python 3
user_input = input("Enter something: ")
print("You entered: " + user_input)
In Python 3, raw_input() is merged into the input() function.
These examples showcase some fundamental differences, and adapting code accordingly is
crucial when transitioning from Python 2 to Python 3.
Example 4: Unicode Handling
Python 2:
# Python 2
unicode_string = u"Hello, Unicode!"
print(unicode_string)

Python 3:
Professor Mudita Dave Nagar Page 24
Python Programming [CA3EL06] Unit#1

# Python 3
unicode_string = "Hello, Unicode!"
print(unicode_string)
In Python 2, Unicode strings require the u prefix, while in Python 3, strings are Unicode by
default.
Example 5: Range Function
Python 2:
# Python 2
for i in range(5):
print(i)

Python 3:

# Python 3
for i in range(5):
print(i)
In Python 3, range() behaves like xrange() in Python 2, providing an iterator instead of a
list.
[Link] 6: Error Handling Syntax
Python 2:
# Python 2
try:
# Some code that might raise an exception
result = 10 / 0
except Exception, e:
print("Error: " + str(e))

Python 3:

# Python 3
try:
# Some code that might raise an exception
result = 10 / 0
except Exception as e:
print("Error: " + str(e))
In Python 3, the syntax for handling exceptions has changed from except Exception, e: to
except Exception as e:.

Professor Mudita Dave Nagar Page 25


Python Programming [CA3EL06] Unit#1

WHAT IS INDENTATION IN PYTHON?


Indentation, a cornerstone of Python's syntax, refers to the spaces or tabs at the beginning of a line.
It stands out not just as a convention but as a requirement. In Python, indentation is not merely a
stylistic choice; it plays a pivotal role in determining the flow of the code. Its significance includes:

 Code Blocks Representation: Python takes a detour from the typical practice seen in languages
like C or Java that use curly braces { } to define code blocks. Instead, Python opts for
indentation, rendering a unique clarity to its code structure. This distinction makes it imperative
to manage indentation errors in Python, as they directly affect the code's logic and flow.

 Code Readability Enforcer: One of Python's standout traits is its emphasis on code readability.
Indentation plays a crucial role here. By ensuring consistent indentation, Python mandates that
code remains clean, organized, and easily understandable. This readability not only aids in better
programming practices but also facilitates smoother collaboration among teams.
Types of Indentation

 Space: In Python, spaces are the preferred indentation method. A standard convention and also
recommended by the official Python style guide (PEP 8) is the use of 4 spaces for each
indentation level.

 Tab: While tabs can technically be used for indentation, they aren't as universally accepted. The
main issue arises when code is shared or viewed in different editors, leading to inconsistent code
appearance. Thus, using tabs can inadvertently cause an indentation error in Python, especially in
collaborative environments.
ESSENTIAL INDENTATION RULES FOR PYTHON
Here are some basic indentation rules for Python:

 Use Spaces for Indentation: Python conventionally uses four spaces for each level of
indentation. While you can technically use tabs, it's recommended to use spaces for consistency
and to avoid issues with different editors and environments.

 Consistent Indentation: Maintain consistent indentation throughout your code. Mixing spaces
and tabs or using different numbers of spaces for indentation can lead to indentation errors.

 Indentation for Blocks: Indentation is used to define blocks of code, such as loops,
conditionals, and function bodies. All lines within the same block should have the same level of
indentation.

 Colon After Statements: In Python, a colon (:) is used to indicate the start of an indented block,
such as in if, for, while, and function definitions.
Here's an example of correctly indented Python code:

def print_numbers():
for i in range(5):

Professor Mudita Dave Nagar Page 26


Python Programming [CA3EL06] Unit#1

if i % 2 == 0:
print("Even:", i)
else:
print("Odd:", i)
print("Done")

print_numbers()

HOW DO INDENTATION ERRORS OCCUR IN PYTHON?


Proper indentation is not merely a cosmetic or stylistic preference; it's syntactically significant in
Python. However, this emphasis on indentation can sometimes lead to subtle pitfalls, particularly
for those new to the language or accustomed to different coding conventions. Misunderstandings or
neglect of Python's indentation rules can usher in a myriad of errors, hampering code execution.
Let's explore some of the prevalent causes behind these indentation errors and their explanations.
Common Cause Explanation Example

Mismatched Indentation Mixing spaces and tabs A code block that begins with
inconsistently causes issues. spaces but has lines indented
with tabs.

Incorrect Indent Levels Using the wrong number of Following if True: with a line
spaces/tabs results in errors. indented with 6 spaces instead
of the recommended 4.

Unexpected Indent Indenting when it’s not Having an indented line


required can break the code. without any control structure
like if, for, etc.
FIXING INDENTATION ERRORS IN PYTHON
Indentation errors are common in Python, especially for beginners, but they can be easily resolved
by carefully checking and adjusting the indentation of your code. To fix an indentation error in
Python, you'll need to adjust the spaces or tabs to ensure that the code adheres to the rules discussed
above.
Common indentation errors include:

 Inconsistent Indentation: Ensure that all lines within the same block have the same level of
indentation. If you mix spaces and tabs, convert them to spaces.

 Mismatched Indentation: If you encounter an error that mentions "indentation error" but you
can't see any obvious issues, check for invisible characters like trailing spaces or tabs at the
beginning of lines.

 Missing Colon: If you forget to include a colon after a statement that should introduce an
indented block (e.g., after if, for, while, or a function definition), Python will raise an indentation
error.
Here's an example of an indentation error and how to fix it:

Professor Mudita Dave Nagar Page 27


Python Programming [CA3EL06] Unit#1

Code with error:


def print_numbers():
for i in range(5): # Missing indentation
print(i)

print_numbers()
To fix this error, we need to simply add the required indentation before the for statement:
Code:
def print_numbers():
for i in range(5): # Correct indentation
print(i)

print_numbers()

ADVANTAGES OF INDENTATION IN PYTHON

1. Enhanced Readability: Python’s indentation style makes the structure of the code immediately
visible. By using indentation to demarcate code blocks, the language ensures that the hierarchy
and logic of the code stand out clearly. This inherent readability is vital, especially in
collaborative settings where multiple developers may interact with the same codebase.

2. Reduction in Errors: The absence of curly braces, commonly used in many programming
languages, means fewer chances of misplacing or mismatching them. This trait significantly
reduces certain syntax errors, ensuring smoother code execution.

3. Promotion of Best Practices: Indentation, by design, pushes developers towards writing well-
structured code. It's a silent enforcer, subtly ensuring that programmers think about code
hierarchy and organization as they write, leading to an intuitive flow in the code.

4. Code Length: By eschewing the need for additional characters like braces or end statements (as
seen in languages like Ruby), Python code tends to be concise. This brevity not only makes the
code look clean but also minimizes the time taken for code reviews and debugging.

5. Universal Style Consistency: With indentation being a syntactical requirement in Python, it


ensures a level of uniformity in coding styles across diverse projects. This consistency is
especially beneficial when transitioning between different Python projects or when integrating
code from various sources.

DISADVANTAGES OF INDENTATION IN PYTHON

1. Initial Learning Challenge: Programmers coming from non-indentation-based languages might


find Python's strict indentation rules a tad challenging initially. The shift in mindset from seeing
indentation as a cosmetic choice to a syntactic necessity can be steep.

Professor Mudita Dave Nagar Page 28


Python Programming [CA3EL06] Unit#1

2. Misreading Risks: Even a minor inconsistency, such as unintentionally mixing spaces with tabs,
can throw off the entire code logic. This sensitivity often leads to indentation error in Python
messages, which can be perplexing, especially for novices.

3. Portability Issues: Moving a Python script from one environment or editor to another can
sometimes introduce indentation issues. Different editors might interpret tabs differently or
might have varied default tab settings, leading to potential execution errors.

4. Perceived Rigidity: Some developers feel that the enforced indentation limits their coding style
freedom. They might prefer a more flexible approach where the code's structure isn't strictly tied
to whitespace.

5. Troubleshooting Challenges: In cases where indentation errors do creep in, they can be
notoriously tricky to debug. Since the errors might not always be evident at a cursory glance, it
demands a meticulous review to identify and rectify them.

CONCLUSION:
Indentation, while being a distinctive feature of Python, plays a pivotal role in reinforcing code
clarity and structure. While it does bring its set of challenges, especially for newcomers, the
advantages it offers are undeniable. As you continue your journey in Python, consider leveraging
platforms like upGrad to further sharpen your skills and embrace Python’s elegant philosophy.
FAQS
1. What is the role of indentation in Python class 11?
Indentation plays a foundational role in teaching Python to class 11 students. It introduces them to
the importance of structured coding in Python.
2. Is Python interpreted or compiled?
Python is an interpreted language. It means the Python interpreter reads and executes the code line-
by-line, instead of compiling it first.
3. What is the importance of being consistent with the indentation level in Python?
Maintaining a consistent indentation level ensures the logical structure of the code remains intact,
and it minimizes the risk of unexpected errors.
4. What is an indentation error in Python example?
Consider an if statement followed by a line with 3 spaces instead of 4. This would throw an
indentation error.
5. Indentation is not mandatory in Python true or false?
False. Indentation is a cornerstone of Python's syntax and is used to define code blocks.

Types of comments in Python


A comment can be written on a single line, next to the corresponding line of code, or in a block
of multiple lines. Here, we will try to understand examples of comment in Python one by one:
Single-line comment in Python
Python single-line comment starts with a hash symbol (#) with no white spaces and lasts till
the end of the line. If the comment exceeds one line then put a hashtag on the next line and

Professor Mudita Dave Nagar Page 29


Python Programming [CA3EL06] Unit#1

continue the comment. Python’s single-line comments are proved useful for supplying short
explanations for variables, function declarations, and expressions. See the following code
snippet demonstrating single line comment:
Example 1:
Python allows comments at the start of lines, and Python will ignore the whole line.
Python3

# This is a comment

# Print “WelcometoMedicaps” to console

print("WelcometoMedicaps")

Output

WelcometoMedicaps

Example 2:
Python also allows comments at the end of lines, ignoring the previous text.
Python3

a, b = 1, 3 # Declaring two integers

sum = a + b # adding two integers

print(sum) # displaying the output

Output

4
Multiline comment in Python
Use a hash (#) for each extra line to create a multiline comment. In fact, Python multiline
comments are not supported by Python’s syntax. Additionally, we can use Python multi-line
comments by using multiline strings. It is a piece of text enclosed in a delimiter (“””) on each
end of the comment. Again there should be no white space between delimiter (“””). They are
useful when the comment text does not fit into one line; therefore need to span across lines.

Professor Mudita Dave Nagar Page 30


Python Programming [CA3EL06] Unit#1

Python Multi-line comments or paragraphs serve as documentation for others reading your
code. See the following code snippet demonstrating a multi-line comment:
Example 1:
In this example, we are using an extra # for each extra line to create a Python multiline
comment.
Python3

# This is a comment

# This is second comment

# Print “WelcometoMedicaps” to console

print("WelcometoMedicaps ")

Output

WelcometoMedicaps

Example 2:
In this example, we are using three double quotes (“) at the start and end of the string without
any space to create a Python multiline comment.
Python3

"""

This would be a multiline comment in Python that

spans several lines and describes Medicaps.

A Computer Science portal for geeks. It contains

well written, well thought

and well-explained computer science

Professor Mudita Dave Nagar Page 31


Python Programming [CA3EL06] Unit#1

and programming articles,

quizzes and more.

"""

print("Medicaps")

Output

Medicaps

Example 3:
In this example, we are using three single quotes (‘) at the start and end of the string without
any space to create a Python multiline comment.
Python3

'''This article on Medicaps gives you a

perfect example of

multi-line comments'''

print("Medicaps ")

Output

Medicaps

Docstring in Python
Python Docstrings are a type of comment that is used to show how the program works.
Docstrings in Python are surrounded by Triple Quotes in Python (“”” “””). Docstrings are also
neglected by the interpreter.

Professor Mudita Dave Nagar Page 32


Python Programming [CA3EL06] Unit#1

Python3

# program illustrates the use of docstrings

def helloWorld():

# This is a docstring comment

""" This program prints out hello world """

print("Hello World")

helloWorld()

Output

Hello World

Difference Between ‘Docstrings’ and ‘Multi-line Comments

Docstrings and Multi-line comments may look the same but they aren’t.
 Docstrings are written in the functions and classes to show how to use the program.
 Multi-line comments are used to show how a block of code works.

Python Variables
Python Variable is containers that store values. Python is not “statically typed”. We do not
need to declare variables before using them or declare their type. A variable is created the
moment we first assign a value to it. A Python variable is a name given to a memory location.
It is the basic unit of storage in a program. In this article, we will see how to define a variable
in Python.
Example of Variable in Python
An Example of a Variable in Python is a representational name that serves as a pointer to an
object. Once an object is assigned to a variable, it can be referred to by that name. In layman’s
terms, we can say that Variable in Python is containers that store values.
Here we have stored “Medicaps” in a variable var, and when we call its name the stored
information will get printed.

Var = "Medicaps"
print(Var)

Professor Mudita Dave Nagar Page 33


Python Programming [CA3EL06] Unit#1

Output:
Medicaps

Example:
x=5
y = "John"
print(x)
print(y)

Variables do not need to be declared with any particular type, and can even change type after
they have been set.

Example
x=4 # x is of type int
x = "Sally" # x is now of type str
print(x)

Casting

If you want to specify the data type of a variable, this can be done with casting.

Example
x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0

Python Data Types



Python Data types are the classification or categorization of data items. It represents the kind of
value that tells what operations can be performed on a particular data. Since everything is an
object in Python programming, Python data types are classes and variables are instances
(objects) of these classes. The following are the standard or built-in data types in Python:
 Numeric
 Sequence Type
 Boolean
 Set
 Dictionary
 Binary Types( memoryview , bytearray , bytes )

Professor Mudita Dave Nagar Page 34


Python Programming [CA3EL06] Unit#1

What is Python Data Types?


To define the values of various data types of Python and check their data types we use the type()
function . Consider the following examples.
This code assigns variable ‘x’ different values of various Python data types. It
covers string , integer , float , complex , list , tuple , range , dictionary , set , frozenset , boole
an , bytes , bytearray , memoryview , and the special value ‘None’ successively. Each
assignment replaces the previous value, making ‘x’ take on the data type and value of the most
recent assignment.

x = "Hello World"
x = 50
x = 60.5
x = 3j
x = ["geeks", "for", "geeks"]
x = ("geeks", "for", "geeks")
x = range(10)
x = {"name": "Suraj", "age": 24}
x = {"geeks", "for", "geeks"}
x = frozenset({"geeks", "for", "geeks"})
x = True
x = b"Geeks"
x = bytearray(4)
x = memoryview(bytes(6))
x = None

Professor Mudita Dave Nagar Page 35


Python Programming [CA3EL06] Unit#1

1. Numeric Data Types in Python


The numeric data type in Python represents the data that has a numeric value. A numeric value
can be an integer, a floating number, or even a complex number. These values are defined
as Python int , Python float , and Python complex classes in Python .
 Integers – This value is represented by int class. It contains positive or negative whole
numbers (without fractions or decimals). In Python, there is no limit to how long an integer
value can be.
 Float – This value is represented by the float class. It is a real number with a floating-point
representation. It is specified by a decimal point. Optionally, the character e or E followed by
a positive or negative integer may be appended to specify scientific notation.
 Complex Numbers – A complex number is represented by a complex class. It is specified
as (real part) + (imaginary part)j . For example – 2+3j
Note – type() function is used to determine the type of Python data type.
Example: This code demonstrates how to determine the data type of variables in Python using
the type() function . It prints the data types of three variables : a (integer) , b (float) , and c
(complex) . The output shows the respective data type Python for each variable.
Python

a=5
print("Type of a: ", type(a))

b = 5.0
print("\nType of b: ", type(b))

c = 2 + 4j
print("\nType of c: ", type(c))
Output:
Type of a: <class 'int'>
Type of b: <class 'float'>
Type of c: <class 'complex'>
2. Sequence Data Types in Python
The sequence Data Type in Python is the ordered collection of similar or different Python data
types. Sequences allow storing of multiple values in an organized and efficient fashion. There are
several sequence data types of Python:
 Python String
 Python List
 Python Tuple
String Data Type
Strings in Python are arrays of bytes representing Unicode characters. A string is a collection of
one or more characters put in a single quote, double-quote, or triple-quote. In Python, there is no
character data type Python, a character is a string of length one. It is represented by str class.
Creating String
Strings in Python can be created using single quotes, double quotes, or even triple quotes.

Professor Mudita Dave Nagar Page 36


Python Programming [CA3EL06] Unit#1

Example: This Python code showcases various string creation methods. It uses single quotes,
double quotes, and triple quotes to create strings with different content and includes a multiline
string. The code also demonstrates printing the strings and checking their data types.
Python

String1 = 'Welcome to the Geeks World'


print("String with the use of Single Quotes: ")
print(String1)
String1 = "I'm a Geek"
print("\nString with the use of Double Quotes: ")
print(String1)
print(type(String1))
String1 = '''I'm a Geek and I live in a world of "Geeks"'''
print("\nString with the use of Triple Quotes: ")
print(String1)
print(type(String1))

String1 = '''Geeks
For
Life'''
print("\nCreating a multiline String: ")
print(String1)
Output:
String with the use of Single Quotes:
Welcome to the Geeks World
String with the use of Double Quotes:
I'm a Geek
<class 'str'>
String with the use of Triple Quotes:
I'm a Geek and I live in a world of "Geeks"
<class 'str'>
Creating a multiline String:
Geeks
For
Life
Accessing elements of String
In Python programming, individual characters of a String can be accessed by using the method of
Indexing. Negative Indexing allows negative address references to access characters from the
back of the String, e.g. -1 refers to the last character, -2 refers to the second last character, and so
on.
Example: This Python code demonstrates how to work with a string named ‘ String1′ . It
initializes the string with “GeeksForGeeks” and prints it. It then showcases how to access the
first character ( “G” ) using an index of 0 and the last character ( “s” ) using a negative index of
-1.
Python

String1 = "GeeksForGeeks"
Professor Mudita Dave Nagar Page 37
Python Programming [CA3EL06] Unit#1

print("Initial String: ")


print(String1)
print("\nFirst character of String is: ")
print(String1[0])
print("\nLast character of String is: ")
print(String1[-1])
Output:
Initial String:
GeeksForGeeks
First character of String is:
G
Last character of String is:
s
Note – To know more about strings, refer to Python String .
List Data Type
Lists are just like arrays, declared in other languages which is an ordered collection of data. It is
very flexible as the items in a list do not need to be of the same type.
Creating a List in Python
Lists in Python can be created by just placing the sequence inside the square brackets[].
Example: This Python code demonstrates list creation and manipulation. It starts with an empty
list and prints it. It creates a list containing a single string element and prints it. It creates a list
with multiple string elements and prints selected elements from the list. It creates a multi-
dimensional list (a list of lists) and prints it. The code showcases various ways to work with lists,
including single and multi-dimensional lists.
Python

List = []
print("Initial blank List: ")
print(List)
List = ['GeeksForGeeks']
print("\nList with the use of String: ")
print(List)
List = ["Geeks", "For", "Geeks"]
print("\nList containing multiple values: ")
print(List[0])
print(List[2])
List = [['Geeks', 'For'], ['Geeks']]
print("\nMulti-Dimensional List: ")
print(List)
Output:
Initial blank List:
[]
List with the use of String:
['GeeksForGeeks']
List containing multiple values:
Geeks

Professor Mudita Dave Nagar Page 38


Python Programming [CA3EL06] Unit#1

Geeks
Multi-Dimensional List:
[['Geeks', 'For'], ['Geeks']]

Python Access List Items


In order to access the list items refer to the index number. Use the index operator [ ] to access an
item in a list. In Python, negative sequence indexes represent positions from the end of the array.
Instead of having to compute the offset as in List[len(List)-3], it is enough to just write List[-3].
Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the
second-last item, etc.
Python

List = ["Geeks", "For", "Geeks"]


print("Accessing element from the list")
print(List[0])
print(List[2])
print("Accessing element using negative indexing")
print(List[-1])
print(List[-3])
Output:
Accessing element from the list
Geeks
Geeks
Accessing element using negative indexing
Geeks
Geeks
Note – To know more about Lists, refer to Python List.
Tuple Data Type
Just like a list, a tuple is also an ordered collection of Python objects. The only difference
between a tuple and a list is that tuples are immutable i.e. tuples cannot be modified after it is
created. It is represented by a tuple class.
Creating a Tuple in Python
In Python Data Types, tuples are created by placing a sequence of values separated by a
‘comma’ with or without the use of parentheses for grouping the data sequence. Tuples can
contain any number of elements and of any datatype (like strings, integers, lists,
etc.). Note: Tuples can also be created with a single element, but it is a bit tricky. Having one
element in the parentheses is not sufficient, there must be a trailing ‘comma’ to make it a tuple.
Example: This Python code demonstrates different methods of creating and working with tuples.
It starts with an empty tuple and prints it. It creates a tuple containing string elements and prints
it. It converts a list into a tuple and prints the result. It creates a tuple from a string using
the tuple() function. It forms a tuple with nested tuples and displays the result.
Python

Tuple1 = ()
print("Initial empty Tuple: ")
print(Tuple1)

Professor Mudita Dave Nagar Page 39


Python Programming [CA3EL06] Unit#1

Tuple1 = ('Geeks', 'For')


print("\nTuple with the use of String: ")
print(Tuple1)
list1 = [1, 2, 4, 5, 6]
print("\nTuple using List: ")
print(tuple(list1))
Tuple1 = tuple('Geeks')
print("\nTuple with the use of function: ")
print(Tuple1)
Tuple1 = (0, 1, 2, 3)
Tuple2 = ('python', 'geek')
Tuple3 = (Tuple1, Tuple2)
print("\nTuple with nested tuples: ")
print(Tuple3)
Output:
Initial empty Tuple:
()
Tuple with the use of String:
('Geeks', 'For')
Tuple using List:
(1, 2, 4, 5, 6)
Tuple with the use of function:
('G', 'e', 'e', 'k', 's')
Tuple with nested tuples:
((0, 1, 2, 3), ('python', 'geek'))
Note – The creation of a Python tuple without the use of parentheses is known as Tuple Packing.
Access Tuple Items
In order to access the tuple items refer to the index number. Use the index operator [ ] to access
an item in a tuple. The index must be an integer. Nested tuples are accessed using nested
indexing.
The code creates a tuple named ‘ tuple1′ with five elements: 1, 2, 3, 4, and 5 . Then it prints the
first, last, and third last elements of the tuple using indexing.
Python

tuple1 = tuple([1, 2, 3, 4, 5])


print("First element of tuple")
print(tuple1[0])
print("\nLast element of tuple")
print(tuple1[-1])

print("\nThird last element of tuple")


print(tuple1[-3])
Output:
First element of tuple
1
Last element of tuple

Professor Mudita Dave Nagar Page 40


Python Programming [CA3EL06] Unit#1

5
Third last element of tuple
3
Note – To know more about tuples, refer to Python Tuples .
3. Boolean Data Type in Python
Python Data type with one of the two built-in values, True or False. Boolean objects that are
equal to True are truthy (true), and those equal to False are falsy (false). However non-Boolean
objects can be evaluated in a Boolean context as well and determined to be true or false. It is
denoted by the class bool.
Note – True and False with capital ‘T’ and ‘F’ are valid booleans otherwise python will throw an
error.
Example: The first two lines will print the type of the boolean values True and False, which
is <class ‘bool’>. The third line will cause an error, because true is not a valid keyword in
Python. Python is case-sensitive, which means it distinguishes between uppercase and lowercase
letters. You need to capitalize the first letter of true to make it a boolean value.
Python

print(type(True))
print(type(False))
print(type(true))
Output:
<class 'bool'>
<class 'bool'>
Traceback (most recent call last):
File "/home/[Link]", line 8, in
print(type(true))
NameError: name 'true' is not defined
4. Set Data Type in Python
In Python Data Types, a Set is an unordered collection of data types that is iterable, mutable, and
has no duplicate elements. The order of elements in a set is undefined though it may consist of
various elements.
Create a Set in Python
Sets can be created by using the built-in set() function with an iterable object or a sequence by
placing the sequence inside curly braces, separated by a ‘comma’. The type of elements in a set
need not be the same, various mixed-up data type values can also be passed to the set.
Example: The code is an example of how to create sets using different types of values, such
as strings , lists , and mixed values
Python

set1 = set()
print("Initial blank Set: ")
print(set1)
set1 = set("GeeksForGeeks")
print("\nSet with the use of String: ")
print(set1)
set1 = set(["Geeks", "For", "Geeks"])

Professor Mudita Dave Nagar Page 41


Python Programming [CA3EL06] Unit#1

print("\nSet with the use of List: ")


print(set1)
set1 = set([1, 2, 'Geeks', 4, 'For', 6, 'Geeks'])
print("\nSet with the use of Mixed Values")
print(set1)

Output:
Initial blank Set:
set()
Set with the use of String:
{'F', 'o', 'G', 's', 'r', 'k', 'e'}
Set with the use of List:
{'Geeks', 'For'}
Set with the use of Mixed Values
{1, 2, 4, 6, 'Geeks', 'For'}

Access Set Items


Set items cannot be accessed by referring to an index, since sets are unordered the items have no
index. But you can loop through the set items using a for loop, or ask if a specified value is
present in a set, by using the in the keyword.
Example: This Python code creates a set named set1 with the
values “Geeks” , “For” and “Geeks” . The code then prints the initial set, the elements of the
set in a loop, and checks if the value “Geeks” is in the set using the ‘ in’ operator
Python

set1 = set(["Geeks", "For", "Geeks"])


print("\nInitial set")
print(set1)
print("\nElements of set: ")
for i in set1:
print(i, end=" ")
print("Geeks" in set1)

Output:
Initial set:
{'Geeks', 'For'}
Elements of set:
Geeks For
True
Note – To know more about sets, refer to Python Sets.
5. Dictionary Data Type in Python
A dictionary in Python is an unordered collection of data values, used to store data values like a
map, unlike other Python Data Types that hold only a single value as an element, a Dictionary
holds a key: value pair. Key-value is provided in the dictionary to make it more optimized. Each
key-value pair in a Dictionary is separated by a colon : , whereas each key is separated by a
‘comma’.

Professor Mudita Dave Nagar Page 42


Python Programming [CA3EL06] Unit#1

Create a Dictionary in Python


In Python, a Dictionary can be created by placing a sequence of elements within curly {} braces,
separated by ‘comma’. Values in a dictionary can be of any datatype and can be duplicated,
whereas keys can’t be repeated and must be immutable. The dictionary can also be created by the
built-in function dict(). An empty dictionary can be created by just placing it in curly
braces{}. Note – Dictionary keys are case sensitive, the same name but different cases of Key
will be treated distinctly.
Example: This code creates and prints a variety of dictionaries. The first dictionary is empty.
The second dictionary has integer keys and string values. The third dictionary has mixed keys,
with one string key and one integer key. The fourth dictionary is created using
the dict() function, and the fifth dictionary is created using the [(key, value)] syntax
Python

Dict = {}
print("Empty Dictionary: ")
print(Dict)
Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print("\nDictionary with the use of Integer Keys: ")
print(Dict)
Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]}
print("\nDictionary with the use of Mixed Keys: ")
print(Dict)
Dict = dict({1: 'Geeks', 2: 'For', 3: 'Geeks'})
print("\nDictionary with the use of dict(): ")
print(Dict)
Dict = dict([(1, 'Geeks'), (2, 'For')])
print("\nDictionary with each item as a pair: ")
print(Dict)
Output:
Empty Dictionary:
{}
Dictionary with the use of Integer Keys:
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
Dictionary with the use of Mixed Keys:
{1: [1, 2, 3, 4], 'Name': 'Geeks'}
Dictionary with the use of dict():
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
Dictionary with each item as a pair:
{1: 'Geeks', 2: 'For'}
Accessing Key-value in Dictionary
In order to access the items of a dictionary refer to its key name. Key can be used inside square
brackets. There is also a method called get() that will also help in accessing the element from a
dictionary.
Example: The code in Python is used to access elements in a dictionary. Here’s what it does, It
creates a dictionary Dict with keys and values as { 1: ‘Geeks’, ‘name’: ‘For’, 3: ‘Geeks’} . It

Professor Mudita Dave Nagar Page 43


Python Programming [CA3EL06] Unit#1

prints the value of the element with the key ‘name’ , which is ‘For’ . It prints the value of the
element with the key 3, which is ‘Geeks’ .
Python

Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}


print("Accessing a element using key:")
print(Dict['name'])
print("Accessing a element using get:")
print([Link](3))
Output:
Accessing a element using key:
For
Accessing a element using get:
Geeks
Python Data Type Exercise Questions
Below are two exercise questions on Python Data Types. We have covered list operation and
tuple operation in these exercise questions. For more exercises on Python data types visit the
page mentioned below.

Code to implement basic list operations

fruits = ["apple", "banana", "orange"]


print(fruits)
[Link]("grape")
print(fruits)
[Link]("orange")
print(fruits)
Output
['apple', 'banana', 'orange']
['apple', 'banana', 'orange', 'grape']
['apple', 'banana', 'grape']

Code to implement basic tuple operation

coordinates = (3, 5)
print(coordinates)
print("X-coordinate:", coordinates[0])
print("Y-coordinate:", coordinates[1])

Output
(3, 5)
X-coordinate: 3
Y-coordinate: 5

Logical operators
Professor Mudita Dave Nagar Page 44
Python Programming [CA3EL06] Unit#1

In Python, Logical operators are used on conditional statements (either True or False). They
perform Logical AND, Logical OR and Logical NOT operations.

OPERATOR DESCRIPTION SYNTAX

and Logical AND: True if both the operands are true x and y

or Logical OR: True if either of the operands is true x or y

not Logical NOT: True if operand is false not x

The truth table for all combinations of values of X and Y.

Logical AND operator


Logical operator returns True if both the operands are True else it returns.

Example #1:

# Python program to demonstrate logical and operator

a = 10

Professor Mudita Dave Nagar Page 45


Python Programming [CA3EL06] Unit#1

b = 10

c = -10

if a > 0 and b > 0:

print("The numbers are greater than 0")

if a > 0 and b > 0 and c > 0:

print("The numbers are greater than 0")

else:

print("Atleast one number is not greater than 0")

Output
The numbers are greater than 0
Atleast one number is not greater than 0

Example #2:

# Python program to demonstrate logical and operator

a = 10

b = 12

c=0

if a and b and c:

print("All the numbers have boolean value as True")

else:

print("Atleast one number has boolean value as False")

output:

Atleast one number has boolean value as False

Professor Mudita Dave Nagar Page 46


Python Programming [CA3EL06] Unit#1

Logical OR operator
Logical or operator returns True if either of the operands is True.

# Python program to demonstrate logical or operator

a = 10
b = -10
c=0
if a > 0 or b > 0:
print("Either of the number is greater than 0")
else:
print("No number is greater than 0")

if b > 0 or c > 0:
print("Either of the number is greater than 0")
else:
print("No number is greater than 0")

Output
Either of the number is greater than 0
No number is greater than 0

Professor Mudita Dave Nagar Page 47


Python Programming [CA3EL06] Unit#1

Example #2:
# Python program to demonstrate logical or operator

a = 10
b = 12
c=0
if a or b or c:
print("Atleast one number has boolean value as True")
else:
print("All the numbers have boolean value as False")

Output
Atleast one number has boolean value as True

Logical not operator


Logical not operator work with the single boolean value. If the boolean value is True it returns
False and vice-versa.

# Python program to demonstrate logical not operator

a = 10

if not a:

Professor Mudita Dave Nagar Page 48


Python Programming [CA3EL06] Unit#1

print("Boolean value of a is True")

if not (a%3 == 0 or a%5 == 0):

print("10 is not divisible by either 3 or 5")

else:

print("10 is divisible by either 3 or 5")

Output

10 is divisible by either 3 or 5

Order of evaluation of logical operators


In the case of multiple operators, Python always evaluates the expression from left to right.
This can be verified by the below example. Example:

# Python program to demonstrate order of evaluation of logical operators

def order(x):

print("Method called for value:", x)

return True if x > 0 else False

a = order

b = order

c = order

if a(-1) or b(5) or c(10):

print("Atleast one of the number is positive")

Output
Method called for value: -1
Method called for value: 5
Atleast one of the number is positive

Boolean Bitwise operator:

Professor Mudita Dave Nagar Page 49


Python Programming [CA3EL06] Unit#1

Bitwise AND operator Returns 1 if both the bits are 1 else 0.


Example:
a = 10 = 1010 (Binary)
b = 4 = 0100 (Binary)
a & b = 1010
&
0100
= 0000
= 0 (Decimal)

Bitwise or operator Returns 1 if either of the bit is 1 else 0.


Example:
a = 10 = 1010 (Binary)
b = 4 = 0100 (Binary)

a | b = 1010
|
0100
= 1110
= 14 (Decimal)

Bitwise not operator: Returns one’s complement of the number.


Example:
a = 10 = 1010 (Binary)
In computers we ususally represent numbers using 32 bits,
so binary representation of 10 is (....0000 1010)[32 bits]

~a is basically 1's complement of a


i.e ~a should be ~10 = ~(....0000 1010) = (....1111 0101) = intermediate-result

Since bitwise negation inverts the sign bit,


we now have a negative number. And we represent a negative number

Professor Mudita Dave Nagar Page 50


Python Programming [CA3EL06] Unit#1

using 2's complement.

2's complement of intermediate-result is:


intermediate-res = 0101 //....1111 0101

1010 //....0000 1010 -(1's complement)


+1
-----------
= 1011 //....0000 1011
-----------
= -11 (Decimal)

thus ~a = -11
Bitwise xor operator: Returns 1 if one of the bits is 1 and the other is 0 else returns false.

Example:
a = 10 = 1010 (Binary)
b = 4 = 0100 (Binary)

a ^ b = 1010
^
0100
= 1110
= 14 (Decimal)

Operator precedence in python:

The following table lists all operators from highest precedence to lowest.

Operator Description

** Exponentiation (raise to the power)

~+- Complement, unary plus and minus (method names for the
last two are +@ and -@)

* / % // Multiply, divide, modulo and floor division

+- Addition and subtraction

>> << Right and left bitwise shift

Professor Mudita Dave Nagar Page 51


Python Programming [CA3EL06] Unit#1

& Bitwise 'AND'td>

^| Bitwise exclusive `OR' and regular `OR'

<= < > >= Comparison operators

<> == != Equality operators

= %= /= //= -= += Assignment operators


*= **=

is is not Identity operators

in not in Membership operators

not or and Logical operators

Operator precedence affects how an expression is evaluated.


For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher
precedence than +, so it first multiplies 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest
appear at the bottom.
Example:
a = 20
b = 10
c = 15
d=5
e=0

e = (a + b) * c / d #( 30 * 15 ) / 5
print "Value of (a + b) * c / d is ", e

e = ((a + b) * c) / d # (30 * 15 ) / 5
print "Value of ((a + b) * c) / d is ", e

e = (a + b) * (c / d); # (30) * (15/5)


print "Value of (a + b) * (c / d) is ", e

e = a + (b * c) / d; # 20 + (150/5)
print "Value of a + (b * c) / d is ", e
When you execute the above program, it produces the following result −
Value of (a + b) * c / d is 90

Professor Mudita Dave Nagar Page 52


Python Programming [CA3EL06] Unit#1

Value of ((a + b) * c) / d is 90
Value of (a + b) * (c / d) is 90
Value of a + (b * c) / d is 50

Different Forms of Assignment Statements in Python

There are some important properties of assignment in Python:-


 Assignment creates object references instead of copying the objects.
 Python creates a variable name the first time when they are assigned a value.
 Names must be assigned before being referenced.
 There are some operations that perform assignments implicitly.

Assignment statement forms:-


1. Basic form:
student = 'Geeks'

print(student)

OUTPUT
Geeks

2. Tuple assignment:

# equivalent to: (x, y) = (50, 100)

x, y = 50, 100

print('x = ', x)

print('y = ', y)

OUTPUT
x = 50
y = 100
When we code a tuple on the left side of the =, Python pairs objects on the right side with
targets on the left by position and assigns them from left to right. Therefore, the values of x
and y are 50 and 100 respectively.
3. List assignment:
This works in the same way as the tuple assignment.
[x, y] = [2, 4]

Professor Mudita Dave Nagar Page 53


Python Programming [CA3EL06] Unit#1

print('x = ', x)

print('y = ', y)

OUTPUT
x=2
y=4

4. Sequence assignment:

In recent version of Python, tuple and list assignment have been generalized into instances of
what we now call sequence assignment – any sequence of names can be assigned to any
sequence of values, and Python assigns the items one at a time by position.

a, b, c = 'HEY'

print('a = ', a)

print('b = ', b)

print('c = ', c)

OUTPUT
a=H
b=E
c=Y

5. Extended Sequence unpacking:


It allows us to be more flexible in how we select portions of a sequence to assign.
p, *q = 'Hello'

print('p = ', p)

print('q = ', q)

Here, p is matched with the first character in the string on the right and q with the rest. The
starred name (*q) is assigned a list, which collects all items in the sequence not assigned to
other names.

OUTPUT

Professor Mudita Dave Nagar Page 54


Python Programming [CA3EL06] Unit#1

p=H
q = ['e', 'l', 'l', 'o']

This is especially handy for a common coding pattern such as splitting a sequence and
accessing its front and rest part.

ranks = ['A', 'B', 'C', 'D']

first, *rest = ranks

print("Winner: ", first)

print("Runner ups: ", ', '.join(rest))

OUTPUT
Winner: A
Runner ups: B, C, D

6. Multiple- target assignment:

x = y = 75

print(x, y)

In this form, Python assigns a reference to the same object (the object which is rightmost) to
the entire target on the left.
OUTPUT
75 75
7. Augmented assignment:
The augmented assignment is a shorthand assignment that combines an expression and an
assignment.
x=2

# equivalent to: x = x + 1

x += 1

print(x)

Professor Mudita Dave Nagar Page 55


Python Programming [CA3EL06] Unit#1

OUTPUT
3

Useful Python Shorthands

1. One-Liner If-Else

Sometimes when an if-else expression is simple enough, it might actually be cleaner to write it as

a one-liner:

2. One-Liner Functions

As with the previous example, sometimes you also might want to give the function definition in

one line:

Professor Mudita Dave Nagar Page 56


Python Programming [CA3EL06] Unit#1

3. Swap Two Variables without a Helper Variable

This is a classic interview question: How can you swap two variables without using a third helper

variable? The answer is simple:

4. Chain Comparisons

This one is pretty neat. Instead of doing this:


x > 0 and x < 200

Professor Mudita Dave Nagar Page 57


Python Programming [CA3EL06] Unit#1

You can write it down just like you would do in a math’s class:
0 < x < 200

5. One-Liner For-Loops

You can use what is called a list comprehension to loop through a list neatly with one line of

code. For example, let’s square each number in a list of numbers:


>>> numbers = [1, 2, 3, 4, 5]
>>> [num * num for num in numbers]
[1, 4, 9, 16, 25]

Using comprehensions is not restricted to lists only. You can use a similar syntax

with dictionaries, sets, and generators too. For instance, let’s use dictionary comprehension to

square values of a dictionary:


>>> dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
>>> { key: num * num for (key, num) in [Link]() }
{'a': 1, 'b': 4, 'c': 9, 'd': 16}

6. Lambda Expressions

In Python, a lambda function is just a nameless function. It can take any number of arguments but

can only have a single expression. For instance, here is a lambda that multiplies a number by

three:
>>> lambda x : x * 3

Lambdas are useful when you need the functionality for a short period of time. A practical

example is filtering a list. Python’s built-in filter method takes two parameters:

 A filtering function (this is a lambda function)

Professor Mudita Dave Nagar Page 58


Python Programming [CA3EL06] Unit#1

 A list to be filtered

As an example, let’s filter even numbers from a list by passing a lambda function into

the filter() method to check if a number is even:


>>> numbers = [1, 2, 3, 4, 5, 6]
>>> list(filter(lambda x : x % 2 == 0 , numbers))[2, 4, 6]

7. Repeat Strings without Using Loops

You can simply multiply a string by an integer to repeat it as many times as you prefer:
>>> "word" * 4
wordwordwordword

8. Reverse a String

>>> sentence = "This is just a test"


>>> sentence[::-1]
tset a tsuj si sihT

9. Simplify If-Statement Conditions

Would you agree that this looks pretty bad, even though there’s nothing wrong with it?
>>> if n == 0 or n == 1 or n == 2 or n == 3 or n == 4 or n == 5:

Instead of this mess, you can make it look better by doing this:
>>> if n in [0, 1, 2, 3, 4, 5]

10. Find the Most Frequent Element of a List

>>> nums = [2, 2, 6, 2, 2, 3, 4, 2, 113, 2, 1]


>>> max(set(nums), key = [Link])
2

Professor Mudita Dave Nagar Page 59


Python Programming [CA3EL06] Unit#1

11. Tear Values to Variables from a List

You can easily destructure list elements into separate variables. For example:
>>> arr = [1, 2, 3]
>>> a, b, c = arr
>>> print(a, b, c)
123

12. F-Strings

With Python 3.6 and later, you can use F-Strings to embed expressions inside strings. As an
example:

13. Simulate Coin Toss

You can use the choice() method of the random module to pick random elements from a list.
>>> import random
>>> [Link](['Head',"Tail"])
Head

14. Join a List of Strings to One String

Professor Mudita Dave Nagar Page 60


Python Programming [CA3EL06] Unit#1

You can neatly join a list of strings together using the join() method of a string.
>>> words = ["This", "is", "a", "Test"]
>>> " ".join(words)
This is a Test

15. Create an Enumeration

Often times it is bad practice to write hard-coded strings. For instance, here the direction is

compared to arbitrary strings that are not guaranteed to be spelled correctly:

Import math: Constants provided by the math module


Math module provides various the value of various constants like pi, tau. Having such
constants saves the time of writing the value of each constant every time we want to use it and
that too with great precision. Constants provided by the math module are –
 Euler’s Number
 Pi
 Tau
 Infinity
 Not a Number (NaN)
Euler’s Number
The math.e constant returns the Euler’s number: 2.71828182846.
Syntax:
math.e

Professor Mudita Dave Nagar Page 61


Python Programming [CA3EL06] Unit#1

Example:

# Import math Library


import math

# Print the value of Euler e


print (math.e)

Output:
2.718281828459045

Pi

You all must be familiar with pi. The pi is depicted as either 22/7 or 3.14. [Link] provides a
more precise value for the pi.
Syntax:
[Link]

Example:

# Import math Library


import math

# Print the value of pi


print ([Link])

Output:
3.141592653589793

Example 2:

# Import math Library

import math

# radius of the circle

r=4

# value of pie

Professor Mudita Dave Nagar Page 62


Python Programming [CA3EL06] Unit#1

pie = [Link]

# area of the circle

print(pie * r * r)

Output:
50.26548245743669

Tau

Tau is defined as the ratio of the circumference to the radius of a circle.


The [Link] constant returns the value tau: 6.283185307179586.

Syntax:
[Link]

# Import math Library

import math

# Print the value of tau

print ([Link])

Output:
6.283185307179586

Infinity

Infinity basically means something which is never-ending or boundless from both directions
i.e. negative and positive. It cannot be depicted by a number. The [Link] constant returns of
positive infinity. For negative infinity, use -[Link].

Syntax:
[Link]

# Import math Library

import math

# Print the positive infinity

print ([Link])
Professor Mudita Dave Nagar Page 63
Python Programming [CA3EL06] Unit#1

# Print the negative infinity

print (-[Link])

Output:
inf
-inf

Example 2: Comparing the values of infinity with the maximum floating point value

# Import math Library

import math

print ([Link] > 10e108)

print (-[Link] < -10e108)

Output:
True
True

NaN

The [Link] constant returns a floating-point nan (Not a Number) value. This value is not a
legal number. The nan constant is equivalent to float(“nan”).
Example:

# Import math Library

import math

# Print the value of nan

print ([Link])

Output:
nan

Professor Mudita Dave Nagar Page 64


Python Programming [CA3EL06] Unit#1

Import Random:

Python Random module is an in-built module of Python which is used to generate random
numbers. These are pseudo-random numbers means these are not truly random. This module
can be used to perform random actions such as generating random numbers, print random a
value for a list or string, etc.

Example 1:

import random

print([Link]())

Example 2:

# import random

import random

# prints a random value from the list

list1 = [1, 2, 3, 4, 5, 6]

print([Link](list1))

As stated above random module creates pseudo-random numbers. Random numbers depend on
the seeding value. For example, if the seeding value is 5 then the output of the below program
will always be the same.

Example: Creating random numbers with seeding value

import random

[Link](5)

print([Link]())

print([Link]())

Output:
0.6229016948897019
0.7417869892607294
The output of the above code will always be the same. Therefore, it must not be used for
encryption.

Professor Mudita Dave Nagar Page 65


Python Programming [CA3EL06] Unit#1

Python - Assert Statement

In Python, the assert statement is used to continue the execute if the given condition evaluates
to True. If the assert condition evaluates to False, then it raises the AssertionError exception
with the specified error message.

Syntax
assert condition [, Error Message]

The following example demonstrates a simple assert statement.

Example: assert

x = 10
assert x > 0
print('x is a positive number.')
Output
x is a positive number.

In the above example, the assert condition, x > 0 evalutes to be True, so it will continue to
execute the next statement without any error.

The assert statement can optionally include an error message string, which gets displayed
along with the AssertionError. Consider the following assert statement with the error message.

Example: Assert Statement with Error Message

x=0
assert x > 0, 'Only positive numbers are allowed'
print('x is a positive number.')

Output
Traceback (most recent call last):
assert x > 0, 'Only positive numbers are allowed'
AssertionError: Only positive numbers are allowed

Above, x=0, so the assert condition x > 0 becomes False, and so it will raise
the AssertionError with the specified message 'Only positive numbers are allowed'. It does not
execute print('x is a positive number.') statement.

The following example uses the assert statement in the function.

Professor Mudita Dave Nagar Page 66


Python Programming [CA3EL06] Unit#1

Example: assert

def square(x):
assert x>=0, 'Only positive numbers are allowed'
return x*x

n = square(2) # returns 4
n = square(-2) # raise an AssertionError

Output

Traceback (most recent call last):


assert x > 0, 'Only positive numbers are allowed'
AssertionError: Only positive numbers are allowed

Above, square(2) will return 4, whereas square(-2) will raise an AssertionError because we
passed -2.

The AssertionError is also a built-in exception that can be handled using try-except construct
as shown below:

Example: AssertionError

Copy

def square(x):
assert x>=0, 'Only positive numbers are allowed'
return x*x

try:
square(-2)
except AssertionError as msg:
print(msg)

Output

Only positive numbers are allowed

Above, calling square(-2) will raise an AssertionError, which will be handled by the except
block. The error message in the assert statement will be passed as an argument to the
exception argument msg, using as keyword.

Built in Functions in Python:

Professor Mudita Dave Nagar Page 67


Python Programming [CA3EL06] Unit#1

Print() Function:
Example 1: Print a string onto the screen:
print("ITM is the Largest Data Science Community over whole world")

Output:

ITM is the Largest Data Science Community over whole world

type( ) function:

The type() function returns the type of the specified object.

Example 1: Return the type of the following object:


list_of_fruits = ('apple', 'banana', 'cherry', 'mango')
print(type(list_of_fruits))

Output:

<class 'tuple'>

input( ) function

The input() function allows taking the input from the user.

Example: Use the prompt parameter to write the complete message after giving the input:
a = input('Enter your name:')
print('Hello, ' + a + ' to ITM University')

Output:

Enter your name:Chirag Goyal


Hello, Chirag Goyal to ITM University

abs( ) function

The abs() function returns the absolute value of the specified number.

Example 1: Return the absolute value of a negative number:


negative_number = -676
print(abs(negative_number))

Output:

676

Professor Mudita Dave Nagar Page 68


Python Programming [CA3EL06] Unit#1

pow( ) function

The pow() function returns the calculated value of x to the power of y i.e, xy.

If a third parameter is present in this function, then it returns x to the power of y, modulus z.

Example 1: Return the value of 3 to the power of 4:


x = pow(3, 4)
print(x)

Output:

81

Example 2: Return the value of 3 to the power of 4, modulus 5 (same as (3 * 3 * 3 * 3) % 5):


x = pow(3, 4, 5)
print(x)

---------------------------End Unit#1---------------------------

Professor Mudita Dave Nagar Page 69

You might also like