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

Python Programming

The document provides a comprehensive overview of Python programming, covering its introduction, features, and applications across various domains such as data science, web development, and machine learning. It outlines key concepts including object-oriented programming, data types, control structures, and the extensive libraries and frameworks available in Python. Additionally, it emphasizes Python's ease of use, versatility, and strong community support, making it a popular choice for developers.

Uploaded by

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

Python Programming

The document provides a comprehensive overview of Python programming, covering its introduction, features, and applications across various domains such as data science, web development, and machine learning. It outlines key concepts including object-oriented programming, data types, control structures, and the extensive libraries and frameworks available in Python. Additionally, it emphasizes Python's ease of use, versatility, and strong community support, making it a popular choice for developers.

Uploaded by

abhiabhi34999
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 150

Python Programming

Index

UNIT-I

 Python -Introducation
 Python-Features,History,Applications,Installation,Examples
 Variables,DataTyes,Keywords,Literals,Operators,Comments

UNIT-II

 Conditional & Control -If Else,Loops,For Loops,Break,Continue,Pass,Strings


 Python-Lists,Tuples,List Vs Tuple
 Python Sets,Dictionary,Functions,Built-in Functions
 Python Lambda functions,Files I/O
 Python Modules,Exceptions,Date,Regex

UNIT-III
 Python OOPS Concepts
 Python Constructors
 Python Object Class
 Python Inheritance
 Abstraction in Python

UNIT-IV
 Environment Setup
 Database Connection
 Creating New Database
 Creating Tables
 Insert Operation
 Read Operation
 Update Operation
 Join operation Performing Transactions

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


Python Programming

UNIT-I
Python is one of the most popular and widely used programming language in nowadays, because
of its simplicity, extensive features and support of libraries. Python also have clean and simple syntax
which makes it beginner-friendly, while it also provides powerful libraries and frameworks that makes it
perfect for the developers.

Our Python tutorial thoroughly explains Python basics and advanced concepts, starting
with installation, conditional statements, loops, built-in data structures, Object-Oriented
Programming, Generators, Exception Handling, Python RegEx, and many other concepts.

What is Python?
Python is a general-purpose, dynamically typed, high-level, compiled and interpreted, garbage-collected,
and purely object-oriented programming language that supports procedural, object-oriented, and
functional programming.

Simple Python Program

Hey, Compile and Run Python!

. print("Hello World!")
Compile and Run Python
In Python, it is one line of code. It requires simple syntax to print 'Hello World'

Why Should You Learn Python?


Python provides many useful features to the programmer. These features make it the most popular and
widely used language. We have listed below few-essential features of Python.

Ease to use and Learn:


Python has a simple and easy-to-understand syntax, unlike other languages such as C, C++, Java, etc.,
which makes it easier for the beginners to learn.

Object-Oriented Language:
It supports object-oriented programming, making writing reusable and modular code easy.

GUI Programming Support:


Python provides several GUI frameworks, such as Tkinter and PyQt, which allows developers to create
desktop application easily.

Dynamic Memory Allocation:


Python automatically manages memory allocation which makes it easier for developers to write complex
programs without worrying about memory management.

Wide Range of Libraries and Frameworks:


Python has a vast collection of libraries and frameworks, such as NumPy, Pandas, Django, and Flask, that
can be used to solve a wide range of problems.

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


Versatility:
Python is a universal language in various domains such as web development, machine learning, data
analysis, scientific computing, and more.

Where is Python Used?


Python is a general-purpose, popular programming language, and it is used in almost every technical field.
The various areas of Python use are given below.

Data Science: Data Science is a vast field, and Python is an important language for this field because of
its simplicity, ease of use, and availability of powerful data analysis and visualization libraries
like NumPy, Pandas, and Matplotlib.

Artificial Intelligence: AI is an emerging Technology, and python is a perfect language for the artificial
intelligence and machine learning because of the availability of powerful libraries such as TensorFlow,
Keras, and Pytorch.

Machine Learning: Python is also widely used for machine learning because of its simplicity, ease of
use and the availability of powerful machine learning libraries.

Data Analysis: Python is also used to create visualizations of data. It is also used to analyze the price
trends and market predictions and automate workflows across multiple data sources.

Web Development: Python is used to develop websites and web applications. There are several popular
frameworks like Django and Flask which are used to build web applications.

Python Popular Frameworks and Libraries


Python has wide range of libraries and frameworks widely used in various fields such as machine
learning, artificial intelligence, web applications, etc. We define some popular frameworks and libraries
of Python as follows.

o Web development (Server-side) - Django Flask, Pyramid, CherryPy


o GUIs based applications - Tkinter, PyGTK, PyQt, PyJs, etc.
o Machine Learning - TensorFlow, PyTorch, Scikit-learn, Matplotlib, Scipy, etc.
o Mathematics - NumPy, Pandas, etc.
o BeautifulSoup: a library for web scraping and parsing HTML and XML
o Requests: a library for making HTTP requests
o SQLAlchemy: a library for working with SQL databases
o Kivy: a framework for building multi-touch applications
o Pygame: a library for game development
o Pytest: a testing framework for Python Django
o REST framework: a toolkit for building RESTful APIs
o FastAPI: a modern, fast web framework for building APIs
o Streamlit: a library for building interactive web apps for machine learning and data science
o NLTK: a library for natural language processing

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


Features of Python
From the development of Ada Lovelace's machine algorithm in 1843 to the latest and popular high-level
programming languages like C++, Python, and Java, a wide range of programming languages have been
developed by programmers in order to solve real-world challenging problems. However, not every
programming language stands out in the limelight. Every programming language is dependent on their
core features like accessibility, flexibility, portability, responsibility, and a lot more. In simpler terms, the
utility of any programming language is considered using its essential features.

In the following tutorial, we are going to study how Python has become a popular language amongst
programmers. We will also discuss various features of Python that make it a preferred language for the
majority of programmers.

Python At a Glance

Python is a programming language developed by Guido van Rossum in the year 1991 for deploying easy
to complex operations and mathematical functions in less time. Python is an open-source, general-
purpose, dynamically typed, high-level, compiled and interpreted, garbage-collected, and purely object-
oriented programming language that supports procedural, object-oriented, and functional programming.
Python is a programming language that is used to build software, websites, and applications. It has a wide
range of libraries and modules that make it a suitable language for data analysis, machine learning, and
scientific computing.

Key Features of Python


We will now discuss various features in Python that make it a popular programming language in today's
time.

1. Free and Open Source


Python is a programming language freely available at the official website. One can download and install
it by clicking on the following link: Download Python. Python, being an open-source programming
language, allows users to access its source code available to the public. This source code can be
downloaded for usage as well as sharing purpose allowing users to contribute to the Python community
from around the world.

2. Easy to Learn and Code


Python is a high-level programming language that is quite easier to learn when compared to other
programming languages like C, Java, C#, JavaScript, etc. Python offers a clean and simple syntax, similar
to plain English making it easy for beginners to comprehend and write programs quickly.

Let us consider the following example.

Example:
print("Hello, World! Welcome to Tpoint Tech.")

Output:
Hello, World! Welcome to Tpoint Tech.

In the above example, we can observe that a simple line of code prints a message on the screen.

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


3. Easy to Read
As we discussed earlier, Python is an expressive language with quite straightforward syntax. The chunks
of code in Python are structured using the indentations making it exceptional programming language
when compared to other programming languages like C++ or Java.

Let us look at the following example to understand this statement.

Programming C++ Python


Language

#include
using namespace std;

void greet(string name) {


cout << "Hello, " << name << "!"
def greet(name):
<< endl;
print(f"Hello, {name}!")
Code Snippet }
greet("Kate")
int main() {
string name = "Kate";
greet(name);
return 0;
}

Output Hello, Kate! Hello, Kate!

Example:

In the above example, we can observe that the program to print "Hello, Kate!" is verbose in C++ when
compared to Python. Moreover, programming languages like C++ or Java often require more lines of
code to perform simple tasks, such as defining a class, handling exceptions, whereas Python provides
minimal boilerplate, leading to shorter and clearer code.

4. Object-Oriented Language
Python offers support for the object-oriented paradigm, a programming approach where software system
is designed and developed with the help of "objects", which are basically blueprints (known as classes)
that define data (known as attributes) and behaviors (known as methods) allowing developers to organize
code in a well-structured format. To understand the concept of object-oriented programming (OOP), let
us consider an example of a Car. A Car can be treated as an object where its color, brand, model, variant,
price, etc., would be its properties and acceleration, brake, and gear change would be its behaviors /or
functions. OOP supports various concepts like abstraction, inheritance, polymorphism, encapsulation,
and more, allowing users to write reusable code and develop applications efficiently and effectively.

5. Cross-Platform Compatibility
Python is also a portable language that can be run on different operating systems
(like Windows, MacOS, Linux, Unix) without any modification. This feature of Python allows
programmers to write and run any of its scripts on any platform without the need to change anything.

6. Interpreted Language:Python is an interpreted language as it runs code line by line, rather than
compiling the complete code into machine code before execution. At first, Python interpreter reads the

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


Python source code and converts it into an immediate form called bytecode. This bytecode is then
executed by the Python virtual machine. This process makes debugging much easier as the errors are
detected quickly.
For example, if there is an error in line 5 of the script, Python will stop there and display the error instead
of compiling the entire code first.

7. Dynamically Typed Language


Python is also a dynamically typed language allowing Python to figure out the variable types (int, double,
long, etc.) automatically at the run time, without the need of declaring them manually.

Let us consider the following example:

Example:

. # initializing some variables


. var_1 = 5
. var_2 = 4.7
. var_3 = "Welcome"
.
. # printing the results
. print("Value of var_1:", var_1)
. print("Type of var_1:", type(var_1))
.
. print("Value of var_2:", var_2)
. print("Type of var_2:", type(var_2))
.
. print("Value of var_3:", var_3)
. print("Type of var_3:", type(var_3))
Output:

Value of var_1: 5
Type of var_1:
Value of var_2: 4.7
Type of var_2:
Value of var_3: Welcome
Type of var_3:
Explanation:
In the above snippet of code, we have defined three different variables without declaring their types. We
have then printed their values along with their types. As a result, we can observe that their types have
been assigned automatically and correctly by Python itself.

8. High-Level Language
Python is a high-level language. This feature allows programmers to mainly focus on solving problems
rather than dealing with the hardware details like system architecture or memory allocation.

9. Integrated Language
Python is an integrated language because it can be readily connected with other programming languages
like C, C++, Java, and more. This feature allows programmers to use existing libraries of Python in other
language. Being an integrated language, Python also provides a comprehensive set of features and
utilities in order to support different aspects of software development.

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


10. GUI Programming Support
Python also provides an excellent support for the development of Graphical User Interfaces (GUIs)
through various libraries and frameworks. The following are some of the famous libraries and
frameworks in Python:

S. No. Python Library Description


or Framework

Tkinter is a built-in GUI library in Python which has easy


to use and simple syntax. Tkinter is great for small to
1 Tkinter
medium-sized applications and is supported in multiple
platforms like Windows, MacOS, Linux, and more.

PyQt is another powerful and feature-rich library of


Python. PyQt has a large community support, and an
extensive documentation is available for its users. It also
2 PyQt provides support for advanced features such as networking,
threading, and multimedia. PyQt also offers cross-platform
support for different operating systems like Windows,
MacOS, Linux and more.

wxPython is a native-looking GUI framework available for


multiple operating systems like Windows, MacOS and
3 wxPython Linux. The interface of wxPython is easy to use with a
simple yet intuitive API. wxPython provides great support
to build desktop applications.

Kivy is another open-source library that supports multi-


touch gestures along with hardware acceleration and more.
Kivy is an amazing Python library to build mobile and
4 Kivy
tablet applications. Kivy also provides support for multiple
operating systems like Windows, MacOS, Linux, iOS,
Android and a lot more.

PySide is another Python binding for the Qt framework


that provides support for advanced features such as
5 PySide
networking, threading, and multimedia. It can also be used
on multiple platforms like Windows, MacOS, and Linux.

PyGTK is a Python binding for the GTK+ library which is


great for building GNOME-based applications. PyGTK
6 PyGTK
also provides support for multiple platforms like Windows,
MacOS, and Linux.

PyGame is a cross-platform Python library designed for


7 PyGame developing video games, interactive applications, and
multimedia tools.
11. Multipurpose Programming
Python is a multi-purpose programming language that can be used for a wide range of applications,
including web development, data analysis, automation, machine learning, and scientific computing. This
makes it versatile for various types of projects due to its simple syntax and extensive libraries.

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


Python plays a significant role in web development. With the use of simple tags like <py-script>, <py-
env>, etc., can be used to write and run Python codes in HTML, allowing programmers to do front-end
development work in Python with JavaScript. Python provides multiple frameworks like Django and
Flask to do back-end development.

12. Strong Community Support


Python has gained popularity over the year making it one of the most favourable programming languages
for multi-purpose development. This leads Python to have a huge community around the world. There are
multiple forums, documentations, and tutorials available online in order to help user to learn and resolve
any problems while programming.

13. Extensive Libraries and Frameworks


Python has a huge collection of libraries and frameworks, making development faster, easier and more
efficient across different domains. This feature of Python allows developers to mainly focus on solving
problems and save their time from writing everything from scratch.

i. Standard Library
Python provides a built-in Standard Library support for the programmers. This library includes various
modules for:

S. No. Purpose Python Modules

1 File Handling os, shutil

2 Networking socket, http.server

3 Data Handling csv, json, sqlite3

4 Mathematics and Statistics math, statistics, random

5 Threading and Multiprocessing threading, multiprocessing

and a lot more.

This rich standard library reduces the requirement for any external dependencies.

ii. Third-Party Libraries


Python's ecosystem comprises of a wide range of third-party libraries available through Python Package
Index (also known as PyPI). The following are the list of some popular third-party libraries:

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


S. No. Purpose Third-party Libraries

Data Science and Artificial NumPy, Pandas, Matplotlib,


1
Intelligence TensorFlow, Scikit-learn

2 Web Development Django, Flask, FastAPI

Selenium, BeautifulSoup,
3 Automation and Scripting
requests

4 Game Development PyGame, Godot (Python API)

5 Networking & Security Scapy, Paramiko

and a lot more.

iii. Frameworks for Rapid Development


Python also provides extensive support to various frameworks to fulfil different needs. Some of these
frameworks are listed below:

S. No. Purpose Frameworks

1 Web Development Django, Flask, FastAPI

2 GUI Applications Tkinter, PyQt, Kivy

3 Machine Learning TensorFlow, PyTorch

4 Automation and Testing Selenium, pytest, unittest

and a lot more.

These extensive libraries and frameworks are mostly open source and serve as the readymade solutions to
various programming problems and saves a lot of time developing applications. Moreover, with a huge
community support for Python, these libraries constantly undergo updates and improvements for efficient
working. These libraries and frameworks are quite versatile and scalable allowing developers in
developing various applications.

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


14. Multiple Programming Paradigms Support
Python is a programming language that supports multiple programming paradigms, which makes it a
highly versatile and powerful language. The following are some key paradigms that Python supports:

i. Procedural Programming:
Python supports procedural programming where we make use of procedures (functions) in order to
operate on data.

Let us consider the following example:

Example:
. # defining a function to perform addition of two numbers
. def sum(a, b):
. # calculating the sum of two numbers and storing the result
. total = a + b
. # returning the result
. return total
.
. if __name__ == '__main__':
. # initializing the variables
. a=5
. b=7
. # calling the sum() function and printing the result
. print(a, "+", b, "=", sum(a, b))
Output:
5 + 7 = 12
Explanation:

In the above snippet of code, we have defined a function as sum() in order to calculate the sum of two
numbers. This function (procedure) is a set of instructions that is operated on the given data to return the
required result.

ii. Object-Oriented Programming (OOP)


Python also supports Object-Oriented Programming as we discussed earlier. In OOPs, we can organise
code into classes and objects and supports various concepts like encapsulation, inheritance, abstraction,
and polymorphism.

Let us consider the following example:

Example:

. # defining a class
. class Car:
. # constructor
. def __init__(self, make, model, year):
. # initializing variables
. self.make = make
. self.model = model

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


. self.year = year
.
. # defining a method to display information
. def display_info(self):
. print(f"Make: {self.make}")
. print(f"Model: {self.model}")
. print(f"Year: {self.year}")
.
. # Creating an object of the Car class
. my_car = Car("Nissan", "GT-R Skyline", 1999)
.
. # Accessing object attributes and calling methods
. my_car.display_info()
Output:

Make: Nissan
Model: GT-R Skyline
Year: 1999
Explanation:

In the above snippet of code, we have defined a class as Car. Within this class, we have created a
constructor to initialize some variables such as make, model, and year. We have then defined a method to
display the information of the car. We then created an object of the class and accessed the different
attributes and methods of the class. Here, we can observe that the code has been organized in classes and
objects.

iii. Functional Programming


Python also supports functional programming that allow programmers to treat computation as the
evaluation of the mathematical functions and avoid changing state or mutable data. Python is not a purely
functional language like Haskell; however, it offers many features of the functional programming. For
example, map, filter and reduce.

Let us consider the following example:

Example:

. # importing the reduce method from the functools module


. from functools import reduce
.
. # given data
. numList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
.
. # Map: Doubling each number
. doubledNumbers = list(map(lambda x: x * 2, numList))
. print("Doubled numbers:", doubledNumbers)
.
. # Filter: Keeping only even numbers
. evenNumbers = list(filter(lambda x: x % 2 == 0, numList))
. print("Even numbers:", evenNumbers)

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


.
. # Reduce: Calculating the sum of all numbers
. sumOfNumbers = reduce(lambda x, y: x + y, numList)
. print("Sum of numbers:", sumOfNumbers)
Output:

Doubled numbers: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24]
Even numbers: [2, 4, 6, 8, 10, 12]
Sum of numbers: 78
Explanation:

In the above snippet of code, we have performed different operations using the map, filter, and reduce
functions. With the use of these function, we can apply operations on iterables efficiently. As we can
observe, we have doubled the numbers in the given list using the map() function, which allow us to apply
the doubling operation to all the elements in the given iterable. Similarly, the filter() function is used to
filter the elements on the basis of the function. Here, we have filtered out the even numbers from the
given list. At last, we have reduce() function that aggregates the elements using the applied function. In
the above case, we have used the reduce() function to add all the elements of the iterable and return the
sum.

15. Automatic Memory Management


Python offers automatic memory management, which means developers do not require to allocate or
deallocate memory manually. The memory manager of Python handles object creation, memory
allocation, garbage collection, and memory optimization automatically. Let us take an example where we
can see Python's automatic memory management in act. Suppose that we have a Python program that
manages user accounts. Each time a user logs in, an object is created, and when they log out, the object is
automatically removed. In this case, Python will perform the following steps:

a. Object Creation: Python allocates memory when a new user logs in.
b. Reference Counting: Python tracks the number of references exist to each object.
c. Garbage Collection: When a user logs out and no references remain, Python automatically frees
memory.

16. Multi-threading and Multiprocessing


Python allows multiple tasks to run at once. This process is known as concurrency, and it can be achieved
by the multi-threading and multiprocessing features of Python.

a. Multi-threading: This feature allows programmers to run multiple threads within the same
process. It is useful for networking, UI applications, and I/O-heavy tasks.
b. Multiprocessing: This feature allows programmers to run multiple processes with separate
memory spaces. It is useful for CPU-heavy tasks like data processing, image processing and
machine learning.

History of Python Programming Language


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 alt.sources.
o In 1994, Python 1.0 was released with new features like lambda, map, filter, and reduce.

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


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.

Python Version List

Python programming language is being updated regularly with new features and supports. There are lots
of update in Python versions, started from 1994 to current release.

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

Python 1.6 September 5, 2000

Python 2.0 October 16, 2000

Python 2.1 April 17, 2001

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


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

Tips to Keep in Mind While Learning Python

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


The most common question asked by the beginners - "What is the best way to learn Python"? It is the
initial and relevant question because first step in learning any programming language is to know how to
learn.

The proper way of learning will help us to learn fast and become a good Python developer.

1. Make it Clear Why We Want to Learn

2. Learn the Basic Syntax

3. Write Code by Own

4. Keep Practicing

5. Make Notes as Needed

6. Discuss Concepts with Other

7. Do small Projects

8. Teach Others

9. Explore Libraries and Frameworks

10. Contribute to Open Source

Usage of Python
Python is a general purpose, open source, high-level programming language and also provides number of
libraries and frameworks. Python has gained popularity because of its simplicity, easy syntax and user-
friendly environment.

o Desktop Applications
o Web Applications
o Data Science
o Artificial Intelligence
o Machine Learning
o Scientific Computing
o Robotics
o Internet of Things (IoT)
o Gaming
o Mobile Apps
o Data Analysis and Preprocessing

Top 10 Applications of Python Programming


Python is known for its general-purpose nature that makes it applicable in almost every domain of
software development. Python makes its presence in every emerging field. It is the fastest-growing
programming language and can develop any application.

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


Here, we are specifying application areas where Python can be applied.

How to Install Python?


Introduction:
Python is among the most widely used programming languages. Due to its user-friendliness, readability,
and extensive library ecosystem, whether you are a novice or an expert developer, the first step to
accomplish this is to install Python on Windows if you wish to write and execute Python programs.

To install Python on a Mac, CentOS or Ubuntu, go to the following links:

o Mac: how-to-install-python-on-mac
o CentOS: how-to-install-python-on-centos
o Ubuntu: how-to-install-python-in-ubuntu
This guide describes in detail how to install Python on a Windows system step-by-step.

Step 1: Downloading the Installer for Python

To install Python on Windows, you first have to take the Python installer from the internet.

Visit the official website of Python:

o Open your favourite web browser, be it Google Chrome, Edge, or Firefox.


o Go to the official site for downloading Python at: http://www.python.org/downloads/
o The website will automatically check what operating system you are using and provide the most
recent stable version of Python fo

r
Windows users

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


Choose the Correct Version

Selecting the appropriate version

o Latest stable releases, such as Python 3.13.2, are recommended for all users.

o To view the older version, scroll down the page and click on "View all Python releases."
1.3 Installer Download

o To begin, click on the button that has the "Download Python 3.13.2" text.

o An exe file indicative of an executable will be downloaded (for example, python-3.13.2.exe).

Step 2: Running of the Python Installer

After downloading the installer file, you have to run it.

2.1 Finding the Installer

o Go to the directory of the downloaded folder (usually, it is in the Downloads folder).


o To start the installation process, double-click on the exe file.

o
2.2 Selecting Installation Preferences

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


Upon the appearance of the setup window of Python, these options will be available: You have to do
these things:

1. There is "Add Python to PATH," which you will be required to check the box next to it.

This step must be done with utmost care as it is very critical.

o Checking this box will ensure that using the command prompt, you can control the use of Python
at any given location or position.
2. Decide from the given options:

o (default) "Install Now" Installs with the default options selected.


o "Customize installation" where you get the freedom to set different options for the installation.
o From options 1 and 2, if you are a starter, it is best that you click on "Install Now" to install
with the pre-set options.
2.3 Commencing Installation

o To begin the installation, select "Install now."

o At this point, your system will have Python files copied into it.

Step 3: Installation Completion Duration

The whole process might take a few minutes.

o After completing the process, the statement "Setup was successful" will appear.
o To exit the installer, click on the "Close" button.

Step 4: Verify Python Installation

To successfully confirm that Python was installed, kindly follow the procedure listed below:

4.1 Open Command Prompt

o Open the Command Prompt window by pressing Win + R, followed by typing cmd and pressing
Enter.
4.2 Check Python Version

o To check if the application was successfully installed, type the following command and press
enter:

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


. $ python --version

o In the event Python was installed properly, it will show the following:

3.9.7 (where the number following 3 is the version number)

In the situation that the command yields an error, it may indicate that Python is not added to the system
PATH.

Step 5: Verify pip Installation

Pip is known as a package manager, which enables the installation and management of Python libraries.

5.1 Check if pip is Installed

o Command Prompt can be opened by typing:

. $ pip --version

Step 6: Test Python with the Command Prompt

In an effort to test if Python is working correctly, attempt to run basic Python scripts.

1. Command Prompt (cmd) can be opened.

2. Type:

. $ python
A Python interactive shell page will open, revealing the Python version with ">>>" following it.

3. Type the following statement:

. print("Hello World!")
4. Assuming that Python was installed properly, it will show:

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


. Hello, World!

5. To close Python, the following command can be used:

. exit()

First Python Program


In this Section, we will discuss the basic syntax of Python, we will run a simple program to print Hello
World on the console.

Python provides us the two ways to run a program:

o Using Interactive interpreter prompt


o Using a script file
Let's discuss each one of them in detail.

Interactive interpreter prompt

Python provides us the feature to execute the Python statement one by one at the interactive prompt. It is
preferable in the case where we are concerned about the output of each line of our Python program.

To open the interactive mode, open the terminal (or command prompt) and type python (python3 in case
if you have Python2 and Python3 both installed on your system).
It will open the following prompt where we can execute the Python statement and check their impact on
the console.

After writing the print statement, press the Enter key.

Here, we get the message "Hello World !" printed on the console.

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


Using a script file (Script Mode Programming)

The interpreter prompt is best to run the single-line statements of the code. However, we cannot write the
code every-time on the terminal. It is not suitable to write multiple lines of code.

Using the script mode, we can write multiple lines code into a file which can be executed later. For this
purpose, we need to open an editor like notepad, create a file named and save it with .py extension, which
stands for "Python". Now, we will implement the above example using the script mode.

. print ("hello world"); #here, we have used print() function to print the message on the console.

To run this file named as first.py, we need to run the following command on the terminal.

Step - 1: Open the Python interactive shell, and click "File" then choose "New", it will open a new
blank script in which we can write our code.

Step -2: Now, write the code and press "Ctrl+S" to save the file.

Step - 3: After saving the code, we can run it by clicking "Run" or "Run Module". It will display the
output to the shell.

The output will be shown as follows.

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


Step - 4: Apart from that, we can also run the file using the operating system terminal. But, we should be
aware of the path of the directory where we have saved our file.

o Open the command line prompt and navigate to the directory.

o We need to type the python keyword, followed by the file name and hit enter to run the Python
file.

Multi-line Statements

Multi-line statements are written into the notepad like an editor and saved it with .py extension. In the
following example, we have defined the execution of the multiple code lines using the Python script.

Code:

. name = "Andrew Venis"


. branch = "Computer Science"
. age = "25"
. print("My name is: ", name, )
. print("My age is: ", age)
Script File:

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


Pros and Cons of Script Mode

The script mode has few advantages and disadvantages as well. Let's understand the following
advantages of running code in script mode.

o We can run multiple lines of code.


o Debugging is easy in script mode.
o It is appropriate for beginners and also for experts.
Let's see the disadvantages of the script mode.

o We have to save the code every time if we make any change in the code.
o It can be tedious when we run a single or a few lines of code.

Get Started with PyCharm


In our first program, we have used gedit on our CentOS as an editor. On Windows, we have an
alternative like notepad or notepad++ to edit the code. However, these editors are not used as IDE for
python since they are unable to show the syntax related suggestions.

JetBrains provides the most popular and a widely used cross-platform IDE PyCharm to run the python
programs.

PyCharm installation

As we have already stated, PyCharm is a cross-platform IDE, and hence it can be installed on a variety of
the operating systems. In this section of the tutorial, we will cover the installation process of PyCharm on
Windows, MacOS, CentOS, and Ubuntu.

Windows

Installing PyCharm on Windows is very simple. To install PyCharm on Windows operating system, visit
the link https://www.jetbrains.com/pycharm/download/download-thanks.html?platform=windows to
download the executable installer. Double click the installer (.exe) file and install PyCharm by clicking
next at each step.

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


To create a first program to Pycharm follows the following step.

Step - 1. Open Pycharm editor. Click on "Create New Project" option to create new project.

Step - 2. Select a location to save the project.

a. We can save the newly created project at desired memory location or can keep file location as it
is but atleast change the project default name untitled to "FirstProject" or something
meaningful.
b. Pycharm automatically found the installed Python interpreter.
c. After change the name click on the "Create" Button.

Step - 3. Click on "File" menu and select "New". By clicking "New" option it will show various file
formats. Select the "Python File".

Step - 4. Now type the name of the Python file and click on "OK". We have written the "FirstProgram".

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


Step - 5. Now type the first program - print("Hello World") then click on the "Run" menu to run program.

Step - 6. The output will appear at the bottom of the screen.

Basic Syntax of Python


Indentation and Comment in Python

Indentation is the most significant concept of the Python programming language. Improper use of
indentation will end up "IndentationError" in our code.

Indentation is nothing but adding whitespaces before the statement when it is needed. Without
indentation Python doesn't know which statement to be executed to next. Indentation also defines which
statements belong to which block. If there is no indentation or improper indentation, it will display
"IndentationError" and interrupt our code.

Python indentation defines the particular group of statements belongs to the particular block. The
programming languages such as C, C++, java use the curly braces {} to define code blocks.

In Python, statements that are the same level to the right belong to the same block. We can use four
whitespaces to define indentation. Let's see the following lines of code.

Example -

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


. list1 = [1, 2, 3, 4, 5]
. for i in list1:
. print(i)
. if i==4:
. break
. print("End of for loop")
Output:

1
2
3
4
End of for loop
Explanation:

In the above code, for loop has a code blocks and if the statement has its code block inside for loop. Both
indented with four whitespaces. The last print() statement is not indented; that's means it doesn't belong
to for loop.

Comments in Python
Comments are essential for defining the code and help us and other to understand the code. By looking
the comment, we can easily understand the intention of every line that we have written in code. We can
also find the error very easily, fix them, and use in other applications.

In Python, we can apply comments using the # hash character. The Python interpreter entirely ignores the
lines followed by a hash character. A good programmer always uses the comments to make code under
stable. Let's see the following example of a comment.

. name = "Thomas" # Assigning string value to the name variable


We can add comment in each line of the Python code

. Fees = 10000 # defining course fees is 10000


. Fees = 20000 # defining course fees is 20000
It is good idea to add code in any line of the code section of code whose purpose is not obvious. This is a
best practice to learn while doing the coding.

Types of Comment

Python provides the facility to write comments in two ways- single line comment and multi-line
comment

Single-Line Comment - Single-Line comment starts with the hash # character followed by text for
further explanation.

. # defining the marks of a student


. Marks = 90
We can also write a comment next to a code statement. Consider the following example.

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


. Name = "James" # the name of a student is James
. Marks = 90 # defining student's marks
. Branch = "Computer Science" # defining student branch
Multi-Line Comments - Python doesn't have explicit support for multi-line comments but we can use
hash # character to the multiple lines. For example -

. # we are defining for loop


. # To iterate the given list.
. # run this code.
We can also use another way.

. """
. This is an example
. Of multi-line comment
. Using triple-quotes
. """
This is the basic introduction of the comments. Visit our Python Comment tutorial to learn it in detail.

Python Identifiers
Python identifiers refer to a name used to identify a variable, function, module, class, module or other
objects. There are few rules to follow while naming the Python Variable.

o A variable name must start with either an English letter or underscore (_).
o A variable name cannot start with the number.
o Special characters are not allowed in the variable name.
o The variable's name is case sensitive.
Let's understand the following example.

Example -

. number = 10
. print(num)
.
. _a = 100
. print(_a)
.
. x_y = 1000
. print(x_y)
Output:

10
100
1000
We have defined the basic syntax of the Python programming language. We must be familiar with the
core concept of any programming languages. Once we memorize the concepts as mentioned above. The
journey of learning Python will become easier.

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


CentOS
To install PyCharm on CentOS, visit the link https://www.javatpoint.com/how-to-install-pycharm-on-
centos. The link will guide you to install PyCharm on the CentOS.

MacOS
To install PyCharm on MacOS, visit the link https://www.javatpoint.com/how-to-install-pycharm-on-mac.
The link will guide you to install PyCharm on the MacOS.

Ubuntu
To install PyCharm on Ubuntu, visit the link https://www.javatpoint.com/how-to-install-pycharm-in-
ubuntu. The link will guide you to install PyCharm on Ubuntu.

Python Keywords
Every scripting language has designated words or keywords, with particular definitions and usage
guidelines. Python is no exception. The fundamental constituent elements of any Python program are
Python keywords.

Introducing Python Keywords

Python keywords are unique words reserved with defined meanings and functions that we can only apply
for those functions. You'll never need to import any keyword into your program because they're
permanently present.

Python's built-in methods and classes are not the same as the keywords. Built-in methods and classes are
constantly present; however, they are not as limited in their application as keywords.

Assigning a particular meaning to Python keywords means you can't use them for other purposes in our
code. You'll get a message of SyntaxError if you attempt to do the same. If you attempt to assign
anything to a built-in method or type, you will not receive a SyntaxError message; however, it is still not
a smart idea.

Python contains thirty-five keywords in the most recent version, i.e., Python 3.8. Here we have shown a
complete list of Python keywords for the reader's reference.

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

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


assert del global not with

async elif if or yield

In distinct versions of Python, the preceding keywords might be changed. Some extras may be introduced,
while others may be deleted. By writing the following statement into the coding window, you can
anytime retrieve the collection of keywords in the version you are working on.

Code

. # Python program to demonstrate the application of iskeyword()


. # importing keyword library which has lists
. import keyword
.
. # displaying the complete list using "kwlist()."
. print("The set of keywords in this version is: ")
. print( keyword.kwlist )
Output:

The set of keywords in this version is :


['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else',
'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise',
'return', 'try', 'while', 'with', 'yield']
By calling help(), you can retrieve a list of currently offered keywords:

Code

. help("keywords")
How to Identify Python Keywords
Python's keyword collection has evolved as new versions were introduced. The await and async
keywords, for instance, were not introduced till Python 3.7. Also, in Python 2.7, the words print and exec
constituted keywords; however, in Python 3+, they were changed into built-in methods and are no longer
part of the set of keywords. In the paragraphs below, you'll discover numerous methods for determining
whether a particular word in Python is a keyword or not.

Write Code on a Syntax Highlighting IDE


There are plenty of excellent Python IDEs available. They'll all highlight keywords to set them apart from
the rest of the terms in the code. This facility will assist you in immediately identifying Python keywords
during coding so that you do not misuse them.

Verify Keywords with Script in a REPL


There are several ways to detect acceptable Python keywords plus know further regarding them in the
Python REPL.

Look for a SyntaxError


Lastly, if you receive a SyntaxError when attempting to allocate to it, name a method with it, or do
anything else with that, and it isn't permitted, it's probably a keyword. This one is somewhat more
difficult to see, but it is still a technique for Python to tell you if you're misusing a keyword.

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


Python Keywords and Their Usage
The following sections categorize Python keywords under the headings based on their frequency of use.
The first category, for instance, includes all keywords utilized as values, whereas the next group includes
keywords employed as operators. These classifications will aid in understanding how keywords are
employed and will assist you in arranging the huge collection of Python keywords.

o A few terms mentioned in the segment following may be unfamiliar to you. They're explained
here, and you must understand what they mean before moving on:
o The Boolean assessment of a variable is referred to as truthfulness. A value's truthfulness reveals
if the value of the variable is true or false.
In the Boolean paradigm, truth refers to any variable that evaluates to true. Pass an item as an input to
bool() to see if it is true. If True is returned, the value of the item is true. Strings and lists which are not
empty, non-zero numbers, and many other objects are illustrations of true values.

False refers to any item in a Boolean expression that returns false. Pass an item as an input to bool() to
see if it is false. If False is returned, the value of the item is false. Examples of false values are " ", 0, { },
and [ ].

Value Keywords: True, False, None


Three Python keywords are employed as values in this example. These are singular values, which we can
reuse indefinitely and every time correspond to the same entity. These values will most probably be seen
and used frequently.

The Keywords True and False


These keywords are typed in lowercase in conventional computer languages (true and false); however,
they are typed in uppercase in Python every time. In Python script, the True Python keyword represents
the Boolean true state. False is a keyword equivalent to True, except it has the negative Boolean state of
false.

True and False are those keywords that can be allocated to variables or parameters and are compared
directly.

Code

. print( 4 == 4 )
. print( 6 > 9 )
. print( True or False )
. print( 9 <= 28 )
. print( 6 > 9 )
. print( True and False )
Output:

True
False
True
True
False
False

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


Because the first, third, and fourth statements are true, the interpreter gives True for those and False for
other statements. True and False are the equivalent in Python as 1 & 0. We can use the accompanying
illustration to support this claim:

Code

print( True == 3 )
. print( False == 0 )
. print( True + True + True)
Output:

False
True
3
The None Keyword
None is a Python keyword that means "nothing." None is known as nil, null, or undefined in different
computer languages.

If a function does not have a return clause, it will give None as the default output:

Code

. print( None == 0 )
. print( None == " " )
. print( None == False )
. A = None
. B = None
. print( A == B )
Output:

False
False
False
True
If a no_return_function returns nothing, it will simply return a None value. None is delivered by
functions that do not meet a return expression in the program flow. Consider the following scenario:

Code

. def no_return_function():
. num1 = 10
. num2 = 20
. addition = num1 + num2
.
. number = no_return_function()
. print( number )
Output:

None

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


This program has a function with_return that performs multiple operations and contains a return
expression. As a result, if we display a number, we get None, which is given by default when there is no
return statement. Here's an example showing this:

Code

. def with_return( num ):


. if num % 4 == 0:
. return False
.
. number = with_return( 67 )
. print( number )
Output:

None

Operator Keywords: and, or, not, in, is

Several Python keywords are employed as operators to perform mathematical operations. In many other
computer languages, these operators are represented by characters such as &, |, and!. All of these are
keyword operations in Python:

Mathematical Operations Operations in Other Languages Python Keyword

AND, ∧ && and

OR, ∨ || or

NOT, ¬ ! not

CONTAINS, ∈ in

IDENTITY === is
Writers created Python programming with clarity in mind. As a result, many operators in other computer
languages that employ characters in Python are English words called keywords.

The and Keyword

The Python keyword and determines whether both the left-hand side and right-hand side operands and
are true or false. The outcome will be True if both components are true. If one is false, the outcome will
also be False:

Truth table for and

X Y X and Y

True True True

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


False True False

True False False

False False False

. <component1> and <component2>


It's worth noting that the outcomes of an and statement aren't always True or False. Due to and's peculiar
behavior, this is the case. Instead of processing the inputs to corresponding Boolean values, it just gives
<component1> if it is false or <component2> if it is true. The outputs of a and expression could be
utilized with a conditional if clause or provided to bool() to acquire an obvious True or False answer.

The or Keyword

The or keyword in Python is utilized to check if, at minimum, 1 of the inputs is true. If the first argument
is true, the or operation yields it; otherwise, the second argument is returned:

. <component1> or <component2>
Similarly to the and keyword, the or keyword does not change its inputs to corresponding Boolean values.
Instead, the outcomes are determined based on whether they are true or false.

Truth table for or

X Y X or Y

True True True

True False True

False True True

False False False

The not Keyword

The not keyword in Python is utilized to acquire a variable's contrary Boolean value:

The not keyword is employed to switch the Boolean interpretation or outcome in conditional sentences or
other Boolean equations. Not, unlike and, and or, determines the specific Boolean state, True or False,
afterward returns the inverse.

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


Truth Table for not

X not X

True False

False True
Code

. False and True


. False or True
. not True
Output:

False
True
False
The in Keyword

The in keyword of Python is a robust confinement checker, also known as a membership operator. If you
provide it an element to seek and a container or series to seek into, it will give True or False, depending
on if that given element was located in the given container:

. <an_element> in <a_container>
Testing for a certain character in a string is a nice illustration of how to use the in keyword:

Code
. container = "Javatpoint"
. print( "p" in container )
. print( "P" in container )
Output:

True
False
Lists, dictionaries, tuples, strings, or any data type with the method __contains__(), or we can iterate over
it will work with the in keyword.

The is Keyword
In Python, it's used to check the identification of objects. The == operation is used to determine whether
two arguments are identical. It also determines whether two arguments relate to the unique object.

When the objects are the same, it gives True; otherwise, it gives False.

Code
. print( True is True )
. print( False is True )
. print( None is not None )
. print( (9 + 5) is (7 * 2) )
Output:

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


True
False
False
True
True, False, and None are all the same in Python since there is just one version.

Code
. print( [] == [] )
. print( [] is [] )
. print( {} == {} )
. print( {} is {} )
Output:

True
False
True
False
A blank dictionary or list is the same as another blank one. However, they aren't identical entities because
they are stored independently in memory. This is because both the list and the dictionary are changeable.

Code
. print( '' == '' )
. print( '' is '' )
Output:

True
True
Strings and tuples, unlike lists and dictionaries, are unchangeable. As a result, two equal strings or tuples
are also identical. They're both referring to the unique memory region.

The nonlocal Keyword


Nonlocal keyword usage is fairly analogous to global keyword usage. The keyword nonlocal is designed
to indicate that a variable within a function that is inside a function, i.e., a nested function is just not local
to it, implying that it is located in the outer function. We must define a non-local parameter with nonlocal
if we ever need to change its value under a nested function. Otherwise, the nested function creates a local
variable using that title. The example below will assist us in clarifying this.

Code
. def the_outer_function():
. var = 10
. def the_inner_function():
. nonlocal var
. var = 14
. print("The value inside the inner function: ", var)
. the_inner_function()
. print("The value inside the outer function: ", var)
.
. the_outer_function()
Output:

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


The value inside the inner function: 14
The value inside the outer function: 14
the_inner_function() is placed inside the_outer_function in this case.

The the_outer_function has a variable named var. Var is not a global variable, as you may have noticed.
As a result, if we wish to change it inside the the_inner_function(), we should declare it using nonlocal.

As a result, the variable was effectively updated within the nested the_inner_function, as evidenced by
the results. The following is what happens if you don't use the nonlocal keyword:

Code
. def the_outer_function():
. var = 10
. def the_inner_function():
. var = 14
. print("Value inside the inner function: ", var)
. the_inner_function()
. print("Value inside the outer function: ", var)
.
. the_outer_function()
Output:

Value inside the inner function: 14


Value inside the outer function: 10
Iteration Keywords: for, while, break, continue
The iterative process and looping are essential programming fundamentals. To generate and operate with
loops, Python has multiple keywords. These would be utilized and observed in almost every Python
program. Knowing how to use them correctly can assist you in becoming a better Python developer.

The for Keyword


The for loop is by far the most popular loop in Python. It's built by blending two Python keywords. They
are for and in, as previously explained.

The while Keyword


Python's while loop employs the term while and functions similarly to other computer languages' while
loops. The block after the while phrase will be repeated repeatedly until the condition following the while
keyword is false.

The break Keyword


If you want to quickly break out of a loop, employ the break keyword. We can use this keyword in both
for and while loops.

The continue Keyword


You can use the continue Python keyword if you wish to jump to the subsequent loop iteration. The
continue keyword, as in many other computer languages, enables you to quit performing the present loop
iteration and go on to the subsequent one.

Code

. # Program to show the use of keywords for, while, break, continue

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


. for i in range(15):
.
. print( i + 4, end = " ")
.
. # breaking the loop when i = 9
. if i == 9:
. break
. print()
.
. # looping from 1 to 15
. i = 0 # initial condition
. while i < 15:
.
. # When i has value 9, loop will jump to next iteration using continue. It will not print
. if i == 9:
. i += 3
. continue
. else:
. # when i is not equal to 9, adding 2 and printing the value
. print( i + 2, end = " ")
.
. i += 1
Output:

4 5 6 7 8 9 10 11 12 13
2 3 4 5 6 7 8 9 10 14 15 16

Exception Handling Keywords - try, except, raise, finally, and assert


try: This keyword is designed to handle exceptions and is used in conjunction with the keyword except
to handle problems in the program. When there is some kind of error, the program inside the "try" block
is verified, but the code in that block is not executed.

except: As previously stated, this operates in conjunction with "try" to handle exceptions.

finally: Whatever the outcome of the "try" section, the "finally" box is implemented every time.

raise: The raise keyword could be used to specifically raise an exception.

assert: This method is used to help in troubleshooting. Often used to ensure that code is correct. Nothing
occurs if an expression is interpreted as true; however, if it is false, "AssertionError" is raised. An output
with the error, followed by a comma, can also be printed.

Code
. # initializing the numbers
. var1 = 4
. var2 = 0
.
. # Exception raised in the try section

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


. try:
. d = var1 // var2 # this will raise a "divide by zero" exception.
. print( d )
. # this section will handle exception raised in try block
. except ZeroDivisionError:
. print("We cannot divide by zero")
. finally:
. # If exception is raised or not, this block will be executed every time
. print("This is inside finally block")
. # by using assert keyword we will check if var2 is 0
. print ("The value of var1 / var2 is : ")
. assert var2 != 0, "Divide by 0 error"
. print (var1 / var2)
Output:

We cannot divide by zero


This is inside finally block
The value of var1 / var2 is :
---------------------------------------------------------------------------
AssertionError Traceback (most recent call last)
Input In [44], in ()
15 # by using assert keyword we will check if var2 is 0
16 print ("The value of var1 / var2 is : ")
---> 17 assert var2 != 0, "Divide by 0 error"
18 print (var1 / var2)

AssertionError: Divide by 0 error

The pass Keyword

In Python, a null sentence is called a pass. It serves as a stand-in for something else. When it is run,
nothing occurs.

Let's say we possess a function that has not been coded yet however we wish to do so in the long term. If
we write just this in the middle of code,

Code

. def function_pass( arguments ):


Output:

def function_pass( arguments ):


^
IndentationError: expected an indented block after function definition on line 1
as shown, IndentationError will be thrown. Rather, we use the pass command to create a blank container.

Code

. def function_pass( arguments ):


. pass

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


We can use the pass keyword to create an empty class too.

Code
. class passed_class:
. pass

The return Keyword

The return expression is used to leave a function and generate a result.

The None keyword is returned by default if we don't specifically return a value. The accompanying
example demonstrates this.

Code
. def func_with_return():
. var = 13
. return var
.
. def func_with_no_return():
. var = 10
.
. print( func_with_return() )
. print( func_with_no_return() )
Output:

13
None

The del Keyword

The del keyword is used to remove any reference to an object. In Python, every entity is an object. We
can use the del command to remove a variable reference.

Code

. var1 = var2 = 5
. del var1
. print( var2 )
. print( var1 )
Output:

5
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Input In [42], in ()
2 del var1
3 print( var2 )
----> 4 print( var1 )

NameError: name 'var1' is not defined

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


We can notice that the variable var1's reference has been removed. As a result, it's no longer recognized.
However, var2 still exists.

Deleting entries from a collection like a list or a dictionary is also possible with del:

Code
. list_ = ['A','B','C']
. del list_[2]
. print(list_)
Output:

['A', 'B']

Python Literals
Python Literals can be defined as data that is given in a variable or constant.

Python supports the following literals:

1. String literals:

String literals can be formed by enclosing a text in the quotes. We can use both single as well as double
quotes to create a string.

Example:

. "Aman" , '12345'
Types of Strings:

There are two types of Strings supported in Python:

a) Single-line String- Strings that are terminated within a single-line are known as Single line Strings.

Example:

. text1='hello'
b) Multi-line String - A piece of text that is written in multiple lines is known as multiple lines string.

There are two ways to create multiline strings:

1) Adding black slash at the end of each line.

Example:

. text1='hello\
. user'

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


. print(text1)
'hellouser'
2) Using triple quotation marks:-

Example:

. str2='''''welcome
. to
. SSSIT'''
. print str2
Output:

welcome
to
SSSIT

II. Numeric literals:

Numeric Literals are immutable. Numeric literals can belong to following four different numerical types.

Int(signed integers) Long(long integers) float(floating point) Complex(complex)

In the form of a+bj where


Numbers( can be both Integers of unlimited size
Real numbers with both a forms the real part and b
positive and negative) followed by lowercase or
integer and fractional part forms the imaginary part
with no fractional part.eg: uppercase L eg:
eg: -26.2 of the complex number.
100 87032845L
eg: 3.14j

Example - Numeric Literals

. x = 0b10100 #Binary Literals


. y = 100 #Decimal Literal
. z = 0o215 #Octal Literal
. u = 0x12d #Hexadecimal Literal
.
. #Float Literal
. float_1 = 100.5
. float_2 = 1.5e2
.
. #Complex Literal
. a = 5+3.14j
.
. print(x, y, z, u)
. print(float_1, float_2)
. print(a, a.imag, a.real)
Output:

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


20 100 141 301
100.5 150.0
(5+3.14j) 3.14 5.0

III. Boolean literals:

A Boolean literal can have any of the two values: True or False.

Example - Boolean Literals

. x = (1 == True)
. y = (2 == False)
. z = (3 == True)
. a = True + 10
. b = False + 10
.
. print("x is", x)
. print("y is", y)
. print("z is", z)
. print("a:", a)
. print("b:", b)
Output:

x is True
y is False
z is False
a: 11
b: 10

IV. Special literals.

Python contains one special literal i.e., None.

None is used to specify to that field that is not created. It is also used for the end of lists in Python.

Example - Special Literals

. val1=10
. val2=None
. print(val1)
. print(val2)
Output:

10
None

V. Literal Collections.

Python provides the four types of literal collection such as List literals, Tuple literals, Dict literals, and
Set literals.

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


List:

o List contains items of different data types. Lists are mutable i.e., modifiable.
o The values stored in List are separated by comma(,) and enclosed within square brackets([]). We
can store different types of data in a List.
Example - List literals

. list=['John',678,20.4,'Peter']
. list1=[456,'Andrew']
. print(list)
. print(list + list1)
Output:

['John', 678, 20.4, 'Peter']


['John', 678, 20.4, 'Peter', 456, 'Andrew']
Dictionary:

o Python dictionary stores the data in the key-value pair.


o It is enclosed by curly-braces {} and each pair is separated by the commas(,).
Example

. dict = {'name': 'Pater', 'Age':18,'Roll_nu':101}


. print(dict)
Output:

{'name': 'Pater', 'Age': 18, 'Roll_nu': 101}


Tuple:

o Python tuple is a collection of different data-type. It is immutable which means it cannot be


modified after creation.
o It is enclosed by the parentheses () and each element is separated by the comma(,).
Example

. tup = (10,20,"Dev",[2,3,4])
. print(tup)
Output:

(10, 20, 'Dev', [2, 3, 4])


Set:

o Python set is the collection of the unordered dataset.


o It is enclosed by the {} and each element is separated by the comma(,).
Example: - Set Literals

. set = {'apple','grapes','guava','papaya'}
. print(set)
Output:

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


{'guava', 'apple', 'papaya', 'grapes'}

Python Operators
In the following tutorial, we will discuss about the operators used in the Python programming language.

An Introduction to Operators in Python


In general, Operators are the symbols used to perform a specific operation on different values and
variables. These values and variables are considered as the Operands, on which the operator is applied.
Operators serve as the foundation upon which logic is constructed in a program in a particular
programming language. In every programming language, some operators perform several tasks.

Different Types of Operators in Python


Same as other languages, Python also has some operators, and these are given below -

1. Arithmetic Operators
2. Comparison Operators
3. Assignment Operators
4. Logical Operators
5. Bitwise Operators
6. Membership Operators
7. Identity Operators

Let us now discuss these operators used in Python in the following sections.

Arithmetic Operators
Python Arithmetic Operators are used on two operands to perform basic mathematical operators like
addition, subtraction, multiplication, and division. There are different types of arithmetic operators
available in Python including the '+' operator for addition, '-' operator for subtraction, '*' for
multiplication, '/' for division, '%' for modulus, '**' for exponent and '//' for floor division.

Let us consider the following table of arithmetic operators for a detailed explanation.

S. No. Operator Syntax Description

This operator is used to


add two operands. For
1 + (Addition) r=a+b
example, if a = 15, b = 10
=> a + b = 15 + 10 = 25

This operator is used to


subtract the second
operand from the first
operand. If the first
2 - (Subtraction) r=a-b
operand is less than the
second operand, the value
results negative. For
example, if a = 20, b = 5

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


=> a - b = 20 – 5 = 15

This operator returns the


quotient after dividing the
first operand by the
3 / (divide) r=a/b
second operand. For
example, if a = 15, b = 4
=> a / b = 15 / 4 = 3.75

This operator is used to


multiply one operand with
4 * (Multiplication) r=a*b the other. For example, if
a = 20, b = 4 => a * b = 20
* 4 = 80

This operator returns the


reminder after dividing the
first operand by the
5 % (reminder) r=a%b
second operand. For
example, if a = 20, b = 10
=> a % b = 20 % 10 = 0

As this operator calculates


the first operand's power
to the second operand, it is
6 ** (Exponent) r = a ** b an exponent operator. For
example, if a = 2, b = 3 =>
a**b = 2**3 = 2^3 =
2*2*2 = 8

This operator provides the


quotient's floor value,
which is obtained by
7 // (Floor division) r = a // b
dividing the two operands.
For example, if a = 15, b =
4 => a // b = 15 // 4 = 3
Program Code:

Now we give code examples of arithmetic operators in Python. The code is given below -

. a = 46 # Initializing the value of a


. b = 4 # Initializing the value of b
.
. print("For a =", a, "and b =", b,"\nCalculate the following:")
.
. # printing different results
. print('1. Addition of two numbers: a + b =', a + b)
. print('2. Subtraction of two numbers: a - b =', a - b)
. print('3. Multiplication of two numbers: a * b =', a * b)
. print('4. Division of two numbers: a / b =', a / b)

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


. print('5. Floor division of two numbers: a // b =',a // b)
. print('6. Reminder of two numbers: a mod b =', a % b)
. print('7. Exponent of two numbers: a ^ b =',a ** b)
Output:

Now we compile the above code in Python, and after successful compilation, we run it. Then the output
is given below -

For a = 46 and b = 4
Calculate the following:
1. Addition of two numbers: a + b = 50
2. Subtraction of two numbers: a - b = 42
3. Multiplication of two numbers: a * b = 184
4. Division of two numbers: a / b = 11.5
5. Floor division of two numbers: a // b = 11
6. Reminder of two numbers: a mod b = 2
7. Exponent of two numbers: a ^ b = 4477456
Comparison Operators
Python Comparison operators are mainly used for the purpose of comparing two values or variables
(operands) and return a Boolean value as either True or False accordingly. There are various types of
comparison operators available in Python including the '==', '!=', '<=', '>=', '<', and '>'.

Let us consider the following table of comparison operators for a detailed explanation.

S. No. Operator Syntax Description

Equal to: If the value of


two operands is equal,
1 == a == b
then the condition
becomes true.

Not Equal to: If the value


of two operands is not
2 != a != b
equal, then the condition
becomes true.

Less than or Equal to: The


condition is met if the first
3 <= a <= b operand is smaller than or
equal to the second
operand.

Greater than or Equal to:


The condition is met if the
4 >= a >= b first operand is greater
than or equal to the second
operand.

5 > a>b Greater than: If the first

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


operand is greater than the
second operand, then the
condition becomes true.

Less than: If the first


operand is less than the
6 < a<b
second operand, then the
condition becomes true.
Program Code:

Now we give code examples of Comparison operators in Python. The code is given below -

. a = 46 # Initializing the value of a


. b = 4 # Initializing the value of b
.
. print("For a =", a, "and b =", b,"\nCheck the following:")
.
. # printing different results
. print('1. Two numbers are equal or not:', a == b)
. print('2. Two numbers are not equal or not:', a != b)
. print('3. a is less than or equal to b:', a <= b)
. print('4. a is greater than or equal to b:', a >= b)
. print('5. a is greater b:', a > b)
. print('6. a is less than b:', a < b)
Output:

Now we compile the above code in Python, and after successful compilation, we run it. Then the output
is given below -

For a = 46 and b = 4
Check the following:
1. Two numbers are equal or not: False
2. Two numbers are not equal or not: True
3. a is less than or equal to b: False
4. a is greater than or equal to b: True
5. a is greater b: True
6. a is less than b: False
Assignment Operators
Using the assignment operators, the right expression's value is assigned to the left operand. Python offers
different assignment operators to assign values to the variable. These assignment operators include '=',
'+=', '-=', '*=', '/=', '%=', '//=', '**=', '&=', '|=', '^=', '>>=', and '<<='.

Let us consider the following table of some commonly used assignment operators for a detailed
explanation.

S. No. Operator Syntax Description

This operator assigns the


1 = a=b+c
value of the right

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


expression to the left
operand.

Add AND: This operator


adds the operand on the
right side to the operand
on the left side and assigns
the resultant value to the
2 += a += b => a = a + b
left operand. For example,
if a = 15, b = 20 => a += b
will be equal to a = a + b
and therefore, a = 15 + 20
=> a = 35

Subtract AND: This


operator subtracts the
operand on the right side
from the operand on the
left side and assigns the
3 -= a -= b => a = a - b resultant value to the left
operand. For example, if a
= 47, b = 32 => a -= b will
be equal to a = a - b and
therefore, a = 47 - 32 => a
= 15

Multiply AND: This


operator multiplies the
operand on the right side
with the operand on the
left side and assigns the
4 *= a *= b => a = a * b resultant value to the left
operand. For example, if a
= 12, b = 4 => a *= b will
be equal to a = a * b and
therefore, a = 12 * 4 => a
= 48

Divide AND: This


operator divides the
operand on the left side
with the operand on the
right side and assign the
5 /= a /= b => a = a / b resultant value to the left
operand. For example, if a
= 15, b = 2 => a /= b will
be equal to a = a / b and
therefore, a = 15 / 2 => a =
7.5

6 %= a %= b => a = a % b Modulus AND: This

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


operator calculates the
modulus of using the left-
side and right-side
operands and assigns the
resultant value to the left
operand. For example, if a
= 20, b = 10 => a %= b
will be equal to a = a % b
and therefore, a = 20 % 10
=> a = 0

Exponent AND: This


operator calculates the
exponent value using the
operands on both side and
assign the resultant value
7 **= a **= b => a = a ** b
to the left operand. For
example, if a = 2, b = 3 =>
a **= b will be equal to a
= a ** b and therefore, a =
2 ** 3 = 8

Divide (floor) AND: This


operator divides the
operand on the left side
with the operand on the
right side and assign the
8 //= a //= b => a = a // b resultant floor value to the
left operand. For example,
if a = 15, b = 2 => a //= b
will be equal to a = a // b
and therefore, a = 15 // 2
=> a = 7
Program Code:

Now we give code examples of Assignment operators in Python. The code is given below -

. a = 34 # Initialize the value of a


. b=6 # Initialize the value of b
.
. # printing the different results
. print('a += b:', a + b)
. print('a -= b:', a - b)
. print('a *= b:', a * b)
. print('a /= b:', a / b)
. print('a %= b:', a % b)
. print('a **= b:', a ** b)
. print('a //= b:', a // b)
Output:

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


Now we compile the above code in Python, and after successful compilation, we run it. Then the output
is given below -

a += b: 40
a -= b: 28
a *= b: 204
a /= b: 5.666666666666667
a %= b: 4
a **= b: 1544804416
a //= b: 5
Bitwise Operators
The two operands' values are processed bit by bit by the bitwise operators. There are various Bitwise
operators used in Python, such as bitwise OR (|), bitwise AND (&), bitwise XOR (^), negation (~), Left
shift (<<), and Right shift (>>). Consider the case below.

For example,

. if a = 7
. b=6
. then, binary (a) = 0111
. binary (b) = 0110
.
. hence, a & b = 0011
. a | b = 0111
. a ^ b = 0100
. ~ a = 1000
. Let, Binary of x = 0101
. Binary of y = 1000
. Bitwise OR = 1101
. 8421
. 1 1 0 1 = 8 + 4 + 1 = 13
.
. Bitwise AND = 0000
. 0000 = 0
.
. Bitwise XOR = 1101
. 8421
. 1 1 0 1 = 8 + 4 + 1 = 13
. Negation of x = ~x = (-x) - 1 = (-5) - 1 = -6
. ~x = -6
Let us consider the following table of bitwise operators for a detailed explanation.

S. No. Operator Syntax Description

Bitwise AND: 1 is copied


1 & a&b to the result if both bits in
two operands at the same

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


location are 1. If not, 0 is
copied.

Bitwise OR: The resulting


bit will be 0 if both the
2 | a|b
bits are zero; otherwise,
the resulting bit will be 1.

Bitwise XOR: If the two


bits are different, the
3 ^ a^b
outcome bit will be 1, else
it will be 0.

Bitwise NOT: The


operand's bits are
calculated as their
4 ~ ~a
negations, so if one bit is
0, the next bit will be 1,
and vice versa.

Bitwise Left Shift: The


number of bits in the right
5 << a << operand is multiplied by
the leftward shift of the
value of the left operand.

Bitwise Right Shift: The


left operand is moved
6 >> a >> right by the number of bits
present in the right
operand.
Program Code:

Now we give code examples of Bitwise operators in Python. The code is given below -

. a=7 # initializing the value of a


. b=8 # initializing the value of b
.
. # printing different results
. print('a & b :', a & b)
. print('a | b :', a | b)
. print('a ^ b :', a ^ b)
. print('~a :', ~a)
. print('a << b :', a << b)
. print('a >> b :', a >> b)
Output:

Now we compile the above code in Python, and after successful compilation, we run it. Then the output
is given below -

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


a &b :0
a | b : 15
a ^ b : 15
~a : -8
a << b : 1792
a >> b : 0
Logical Operators
The assessment of expressions to make decisions typically uses logical operators. Python offers different
types of logical operators such as and, or, and not. In the case of the logical AND, if the first one is 0, it
does not depend upon the second one. In the case of the logical OR, if the first one is 1, it does not
depend on the second one.

Let us consider the following table of the logical operators used in Python for a detailed explanation.

S. No. Operator Syntax Description

Logical AND: The


condition will also be true
if the expression is true. If
1 and a and b
the two expressions a and
b are the same, then a and
b both must be true.

Logical OR: The


condition will be true if
one of the phrases is true.
2 or a or b If a and b are the two
expressions, then either a
or b must be true to make
the condition true.

Logical NOT: If an
expression a is true, then
3 not not a
not (a) will be false and
vice versa.
Program Code:

Now we give code examples of Logical operators in Python. The code is given below -

. a=7 # initializing the value of a


.
. # printing different results
. print("For a = 7, checking whether the following conditions are True or False:")
. print('\"a > 5 and a < 7\" =>', a > 5 and a < 7)
. print('\"a > 5 or a < 7\" =>', a > 5 or a < 7)
. print('\"not (a > 5 and a < 7)\" =>', not(a > 5 and a < 7))
Output:

Now we compile the above code in Python, and after successful compilation, we run it. Then the output
is given below -

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


For a = 7, checking whether the following conditions are True or False:
"a > 5 and a < 7" => False
"a > 5 or a < 7" => True
"not (a > 5 and a < 7)" => True
Membership Operators
We can verify the membership of a value inside a Python data structure using the Python membership
operators. The result is said to be true if the value or variable is in the sequence (list, tuple, or dictionary);
otherwise, it returns false.

S. No. Operator Description

If the first operand (value or


variable) is present in the second
1 in operand (sequence), it is evaluated
to be true. Sequence can either be a
list, tuple, or dictionary

If the first operand (value or


variable) is not present in the second
2 not in operand (sequence), the evaluation
is true. Sequence can either be a list,
tuple, or dictionary
Program Code:

Now we give code examples of Membership operators in Python. The code is given below -

. # initializing a list
. myList = [12, 22, 28, 35, 42, 49, 54, 65, 92, 103, 245, 874]
.
. # initializing x and y with some values
. x = 31
. y = 28
.
. # printing the given list
. print("Given List:", myList)
.
. # checking if x is present in the list or not
. if (x not in myList):
. print("x =", x,"is NOT present in the given list.")
. else:
. print("x =", x,"is present in the given list.")
.
. # checking if y is present in the list or not
. if (y in myList):
. print("y =", y,"is present in the given list.")
. else:
. print("y =", y,"is NOT present in the given list.")
Output:

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


Now we compile the above code in Python, and after successful compilation, we run it. Then the output
is given below -

Given List: [12, 22, 28, 35, 42, 49, 54, 65, 92, 103, 245, 874]
x = 31 is NOT present in the given list.
y = 28 is present in the given list.
Identity Operators
Python offers two identity operators as is and is not, that are used to check if two values are located on
the same part of the memory. Two variables that are equal do not imply that they are identical.

S. No. Operator Description

If the references on both sides point


1 is to the same object, it is determined
to be true.

If the references on both sides do


2 is not not point at the same object, it is
determined to be true.
Program Code:

Now we give code examples of Identity operators in Python. The code is given below -

. # initializing two variables a and b


. a = ["Rose", "Lotus"]
. b = ["Rose", "Lotus"]
.
. # initializing a variable c and storing the value of a in c
. c=a
.
. # printing the different results
. print("a is c => ", a is c)
. print("a is not c => ", a is not c)
. print("a is b => ", a is b)
. print("a is not b => ", a is not b)
. print("a == b => ", a == b)
. print("a != b => ", a != b)
Output:

Now we compile the above code in python, and after successful compilation, we run it. Then the output is
given below -

a is c => True
a is not c => False
a is b => False
a is not b => True
a == b => True
a != b => False

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


Operator Precedence

The order in which the operators are examined is crucial to understand since it tells us which operator
needs to be considered first. Below is a list of the Python operators' precedence tables.

S. No. perator Description

Overall other operators


employed in the expression,
1 **
the exponent operator is
given precedence.

the minus, unary plus, and


2 ~, +, -
negation.

the division of the floor, the


3 *, /, %, // modules, the division, and
the multiplication.

4 +, - Binary plus, and minus

5 >>, << Left shift. and right shift

6 & Binary and.

7 ^, | Binary xor, and or

Comparison operators (less


than, less than equal to,
8 <=, <, >, >=
greater than, greater then
equal to).

9 <>, ==, != Equality operators.

=, %=, /=, //=, -=, +=,


10 Assignment operators
*=, **=

11 is, is not Identity operators

12 in, not in Membership operators

13 not, or, and Logical operators


Python Comments
We'll study how to write comments in our program in this article. We'll also learn about single-line
comments, multi-line comments, documentation strings, and other Python comments.

Introduction to Python Comments


We may wish to describe the code we develop. We might wish to take notes of why a section of script
functions, for instance. We leverage the remarks to accomplish this. Formulas, procedures, and
sophisticated business logic are typically explained with comments. The Python interpreter overlooks the

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


remarks and solely interprets the script when running a program. Single-line comments, multi-line
comments, and documentation strings are the 3 types of comments in Python.

Advantages of Using Comments


Our code is more comprehensible when we use comments in it. It assists us in recalling why specific
sections of code were created by making the program more understandable.

Aside from that, we can leverage comments to overlook specific code while evaluating other code
sections. This simple technique stops some lines from running or creates a fast pseudo-code for the
program.

Below are some of the most common uses for comments:

o Readability of the Code


o Restrict code execution
o Provide an overview of the program or project metadata
o To add resources to the code
Types of Comments in Python
In Python, there are 3 types of comments. They are described below:

Single-Line Comments

Single-line remarks in Python have shown to be effective for providing quick descriptions for parameters,
function definitions, and expressions. A single-line comment of Python is the one that has a hashtag # at
the beginning of it and continues until the finish of the line. If the comment continues to the next line,
add a hashtag to the subsequent line and resume the conversation. Consider the accompanying code
snippet, which shows how to use a single line comment:

Code

. # This code is to show an example of a single-line comment


. print( 'This statement does not have a hashtag before it' )
Output:

This statement does not have a hashtag before it


The following is the comment:

. # This code is to show an example of a single-line comment


The Python compiler ignores this line.

Everything following the # is omitted. As a result, we may put the program mentioned above in one line
as follows:

Code

. print( 'This is not a comment' ) # this code is to show an example of a single-line comment
Output:

This is not a comment

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


This program's output will be identical to the example above. The computer overlooks all content
following #.

Multi-Line Comments
Python does not provide the facility for multi-line comments. However, there are indeed many ways to
create multi-line comments.

With Multiple Hashtags (#)

In Python, we may use hashtags (#) multiple times to construct multiple lines of comments. Every line
with a (#) before it will be regarded as a single-line comment.

Code

. # it is a
. # comment
. # extending to multiple lines
In this case, each line is considered a comment, and they are all omitted.

Using String Literals

Because Python overlooks string expressions that aren't allocated to a variable, we can utilize them as
comments.

Code

. 'it is a comment extending to multiple lines'


We can observe that on running this code, there will be no output; thus, we utilize the strings inside triple
quotes(""") as multi-line comments.

Python Docstring

The strings enclosed in triple quotes that come immediately after the defined function are called Python
docstring. It's designed to link documentation developed for Python modules, methods, classes, and
functions together. It's placed just beneath the function, module, or class to explain what they perform.
The docstring is then readily accessible in Python using the __doc__ attribute.

Code

. # Code to show how we use docstrings in Python


.
. def add(x, y):
. """This function adds the values of x and y"""
. return x + y
.
. # Displaying the docstring of the add function
. print( add.__doc__ )
Output:

This function adds the values of x and y

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


Python Variables
A variable is the name given to a memory location. A value-holding Python variable is also known as an
identifier.

Since Python is an infer language that is smart enough to determine the type of a variable, we do not need
to specify its type in Python.

Variable names must begin with a letter or an underscore, but they can be a group of both letters and
digits.

The name of the variable should be written in lowercase. Both Rahul and rahul are distinct variables.

Identifier Naming
Identifiers are things like variables. An Identifier is utilized to recognize the literals utilized in the
program. The standards to name an identifier are given underneath.

o The variable's first character must be an underscore or alphabet (_).


o Every one of the characters with the exception of the main person might be a letter set of lower-
case(a-z), capitalized (A-Z), highlight, or digit (0-9).
o White space and special characters (!, @, #, %, etc.) are not allowed in the identifier name. ^, &,
*).
o Identifier name should not be like any watchword characterized in the language.
o Names of identifiers are case-sensitive; for instance, my name, and MyName isn't something
very similar.
o Examples of valid identifiers: a123, _n, n_9, etc.
o Examples of invalid identifiers: 1a, n%4, n 9, etc.
Declaring Variable and Assigning Values

o Python doesn't tie us to pronounce a variable prior to involving it in the application. It permits us
to make a variable at the necessary time.
o In Python, we don't have to explicitly declare variables. The variable is declared automatically
whenever a value is added to it.
o The equal (=) operator is utilized to assign worth to a variable.
Object References
When we declare a variable, it is necessary to comprehend how the Python interpreter works. Compared
to a lot of other programming languages, the procedure for dealing with variables is a little different.

Python is the exceptionally object-arranged programming language; Because of this, every data item is a
part of a particular class. Think about the accompanying model.

. print("John")
Output:

John
The Python object makes a integer object and shows it to the control center. We have created a string
object in the print statement above. Make use of the built-in type() function in Python to determine its
type.

. type("John")
Output:

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


<class 'str'>
In Python, factors are an symbolic name that is a reference or pointer to an item. The factors are utilized
to indicate objects by that name.

Let's understand the following example

. a = 50

In the above image, the variable a refers to an integer object.

Suppose we assign the integer value 50 to a new variable b.

. a = 50
. b=a

The variable b refers to the same object that a points to because Python does not create another object.

Let's assign the new value to b. Now both variables will refer to the different objects.

. a = 50
. b =100
.

Python manages memory efficiently if we assign the same variable to two different values.

Object Identity
Every object created in Python has a unique identifier. Python gives the dependable that no two items
will have a similar identifier. The object identifier is identified using the built-in id() function. consider
about the accompanying model.

. a = 50
. b=a
. print(id(a))
. print(id(b))

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


. # Reassigned variable a
. a = 500
. print(id(a))
Output:

140734982691168
140734982691168
2822056960944
We assigned the b = a, an and b both highlight a similar item. The id() function that we used to check
returned the same number. We reassign a to 500; The new object identifier was then mentioned.

Variable Names
The process for declaring the valid variable has already been discussed. Variable names can be any
length can have capitalized, lowercase (start to finish, a to z), the digit (0-9), and highlight character(_).
Take a look at the names of valid variables in the following example.

. name = "Devansh"
. age = 20
. marks = 80.50
.
. print(name)
. print(age)
. print(marks)
Output:

Devansh
20
80.5
Consider the following valid variables name.

. name = "A"
. Name = "B"
. naMe = "C"
. NAME = "D"
. n_a_m_e = "E"
. _name = "F"
. name_ = "G"
. _name_ = "H"
. na56me = "I"
.
. print(name,Name,naMe,NAME,n_a_m_e, NAME, n_a_m_e, _name, name_,_name, na56me)
Output:

ABCDEDEFGFI
We have declared a few valid variable names in the preceding example, such as name, _name_, and so on.
However, this is not recommended because it may cause confusion when we attempt to read code. To
make the code easier to read, the name of the variable ought to be descriptive.

The multi-word keywords can be created by the following method.

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


o Camel Case - In the camel case, each word or abbreviation in the middle of begins with a capital
letter. There is no intervention of whitespace. For example - nameOfStudent, valueOfVaraible,
etc.
o Pascal Case - It is the same as the Camel Case, but here the first word is also capital. For
example - NameOfStudent, etc.
o Snake Case - In the snake case, Words are separated by the underscore. For example -
name_of_student, etc.
Multiple Assignment
Multiple assignments, also known as assigning values to multiple variables in a single statement, is a
feature of Python.

We can apply different tasks in two ways, either by relegating a solitary worth to various factors or
doling out numerous qualities to different factors. Take a look at the following example.

1. Assigning single value to multiple variables

Eg:

. x=y=z=50
. print(x)
. print(y)
. print(z)
Output:

50
50
50
2. Assigning multiple values to multiple variables:

Eg:

. a,b,c=5,10,15
. print a
. print b
. print c
Output:

5
10
15
The values will be assigned in the order in which variables appear.

Python Variable Types


There are two types of variables in Python - Local variable and Global variable. Let's understand the
following variables.

Local Variable
The variables that are declared within the function and have scope within the function are known as local
variables. Let's examine the following illustration.

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


Example -

. # Declaring a function
. def add():
. # Defining local variables. They has scope only within a function
. a = 20
. b = 30
. c=a+b
. print("The sum is:", c)
.
. # Calling a function
. add()
Output:

The sum is: 50


Explanation:

We declared the function add() and assigned a few variables to it in the code above. These factors will be
alluded to as the neighborhood factors which have scope just inside the capability. We get the error that
follows if we attempt to use them outside of the function.

. add()
. # Accessing local variable outside the function
. print(a)
Output:

The sum is: 50


print(a)
NameError: name 'a' is not defined
We tried to use local variable outside their scope; it threw the NameError.

Global Variables
Global variables can be utilized all through the program, and its extension is in the whole program.
Global variables can be used inside or outside the function.

By default, a variable declared outside of the function serves as the global variable. Python gives the
worldwide catchphrase to utilize worldwide variable inside the capability. The function treats it as a local
variable if we don't use the global keyword. Let's examine the following illustration.

Example -

. # Declare a variable and initialize it


. x = 101
.
. # Global variable in function
. def mainFunction():
. # printing a global variable
. global x

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


. print(x)
. # modifying a global variable
. x = 'Welcome To Javatpoint'
. print(x)
.
. mainFunction()
. print(x)
Output:

101
Welcome To Javatpoint
Welcome To Javatpoint
Explanation:

In the above code, we declare a global variable x and give out a value to it. We then created a function
and used the global keyword to access the declared variable within the function. We can now alter its
value. After that, we gave the variable x a new string value and then called the function and printed x,
which displayed the new value.

Delete a variable

We can delete the variable using the del keyword. The syntax is given below.

Syntax -

. del <variable_name>
In the following example, we create a variable x and assign value to it. We deleted variable x, and print it,
we get the error "variable x is not defined". The variable x will no longer use in future.

Example -

. # Assigning a value to x
. x=6
. print(x)
. # deleting a variable.
. del x
. print(x)
Output:

6
Traceback (most recent call last):
File "C:/Users/DEVANSH SHARMA/PycharmProjects/Hello/multiprocessing.py", line 389, in
print(x)
NameError: name 'x' is not defined
Maximum Possible Value of an Integer in Python
Python, to the other programming languages, does not support long int or float data types. It uses the int
data type to handle all integer values. The query arises here. In Python, what is the maximum value that
the variable can hold? Take a look at the following example.

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


Example -

. # A Python program to display that we can store


. # large numbers in Python
.
. a = 10000000000000000000000000000000000000000000
. a=a+1
. print(type(a))
. print (a)
Output:

<class 'int'>
10000000000000000000000000000000000000000001
As we can find in the above model, we assigned a large whole number worth to variable x and really look
at its sort. It printed class <int> not long int. As a result, the number of bits is not limited, and we are free
to use all of our memory.

There is no special data type for storing larger numbers in Python.

Print Single and Numerous Factors in Python

We can print numerous factors inside the single print explanation. The examples of single and multiple
printing values are provided below.

Example - 1 (Printing Single Variable

. # printing single value


. a=5
. print(a)
. print((a))
Output:

5
5
Example - 2 (Printing Multiple Variables)

. a=5
. b=6
. # printing multiple variables
. print(a,b)
. # separate the variables by the comma
. Print(1, 2, 3, 4, 5, 6, 7, 8)
Output:

56
12345678
Basic Fundamentals:
This section contains the fundamentals of Python, such as:

i)Tokens and their types.

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


ii) Comments

a)Tokens:

o The tokens can be defined as a punctuator mark, reserved words, and each word in a statement.
o The token is the smallest unit inside the given program.
There are following tokens in Python:

o Keywords.
o Identifiers.
o Literals.
o Operators.

Python Data Types


Every value has a datatype, and variables can hold values. Python is a powerfully composed language;
consequently, we don't have to characterize the sort of variable while announcing it. The interpreter binds
the value implicitly to its type.

. a=5
We did not specify the type of the variable a, which has the value five from an integer. The Python
interpreter will automatically interpret the variable as an integer.

We can verify the type of the program-used variable thanks to Python. The type() function in Python
returns the type of the passed variable.

Consider the following illustration when defining and verifying the values of various data types.

. a=10
. b="Hi Python"
. c = 10.5
. print(type(a))
. print(type(b))
. print(type(c))
Output:

<type 'int'>
<type 'str'>
<type 'float'>
Standard data types
A variable can contain a variety of values. On the other hand, a person's id must be stored as an integer,
while their name must be stored as a string.

The storage method for each of the standard data types that Python provides is specified by Python. The
following is a list of the Python-defined data types.

1. Numbers
2. Sequence Type
3. Boolean

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


4. Set
5. Dictionary

The data types will be briefly discussed in this tutorial section. We will talk about every single one of
them exhaustively later in this instructional exercise.

Numbers

Numeric values are stored in numbers. The whole number, float, and complex qualities have a place with
a Python Numbers datatype. Python offers the type() function to determine a variable's data type. The
instance () capability is utilized to check whether an item has a place with a specific class.

When a number is assigned to a variable, Python generates Number objects. For instance,

. a=5
. print("The type of a", type(a))
.
. b = 40.5
. print("The type of b", type(b))
.
. c = 1+3j
. print("The type of c", type(c))
. print(" c is a complex number", isinstance(1+3j,complex))
Output:

The type of a <class 'int'>


The type of b <class 'float'>
The type of c <class 'complex'>
c is complex number: True
Python supports three kinds of numerical data.

o Int: Whole number worth can be any length, like numbers 10, 2, 29, - 20, - 150, and so on. An
integer can be any length you want in Python. Its worth has a place with int.
o Float: Float stores drifting point numbers like 1.9, 9.902, 15.2, etc. It can be accurate to within
15 decimal places.
o Complex: An intricate number contains an arranged pair, i.e., x + iy, where x and y signify the
genuine and non-existent parts separately. The complex numbers like 2.14j, 2.0 + 2.3j, etc.
Sequence Type

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


String

The sequence of characters in the quotation marks can be used to describe the string. A string can be
defined in Python using single, double, or triple quotes.

String dealing with Python is a direct undertaking since Python gives worked-in capabilities and
administrators to perform tasks in the string.

When dealing with strings, the operation "hello"+" python" returns "hello python," and the operator + is
used to combine two strings.

Because the operation "Python" *2 returns "Python," the operator * is referred to as a repetition operator.

The Python string is demonstrated in the following example.

Example - 1

. str = "string using double quotes"


. print(str)
. s = '''''A multiline
. string'''
. print(s)
Output:

string using double quotes


A multiline
string
Look at the following illustration of string handling.

Example - 2

. str1 = 'hello javatpoint' #string str1


. str2 = ' how are you' #string str2
. print (str1[0:2]) #printing first two character using slice operator
. print (str1[4]) #printing 4th character of the string
. print (str1*2) #printing the string twice
. print (str1 + str2) #printing the concatenation of str1 and str2
Output:

he
o
hello javatpointhello javatpoint
hello javatpoint how are you

List

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


Lists in Python are like arrays in C, but lists can contain data of different types. The things put away in
the rundown are isolated with a comma (,) and encased inside square sections [].

To gain access to the list's data, we can use slice [:] operators. Like how they worked with strings, the list
is handled by the concatenation operator (+) and the repetition operator (*).

Look at the following example.

Example:

. list1 = [1, "hi", "Python", 2]


. #Checking type of given list
. print(type(list1))
.
. #Printing the list1
. print (list1)
.
. # List slicing
. print (list1[3:])
.
. # List slicing
. print (list1[0:2])
.
. # List Concatenation using + operator
. print (list1 + list1)
.
. # List repetation using * operator
. print (list1 * 3)
Output:

[1, 'hi', 'Python', 2]


[2]
[1, 'hi']
[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]
[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]

Tuple

In many ways, a tuple is like a list. Tuples, like lists, also contain a collection of items from various data
types. A parenthetical space () separates the tuple's components from one another.

Because we cannot alter the size or value of the items in a tuple, it is a read-only data structure.

Let's look at a straightforward tuple in action.

Example:

. tup = ("hi", "Python", 2)

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


. # Checking type of tup
. print (type(tup))
.
. #Printing the tuple
. print (tup)
.
. # Tuple slicing
. print (tup[1:])
. print (tup[0:1])
.
. # Tuple concatenation using + operator
. print (tup + tup)
.
. # Tuple repatation using * operator
. print (tup * 3)
.
. # Adding value to tup. It will throw an error.
. t[2] = "hi"
Output:

<class 'tuple'>
('hi', 'Python', 2)
('Python', 2)
('hi',)
('hi', 'Python', 2, 'hi', 'Python', 2)
('hi', 'Python', 2, 'hi', 'Python', 2, 'hi', 'Python', 2)

Traceback (most recent call last):


File "main.py", line 14, in <module>
t[2] = "hi";
TypeError: 'tuple' object does not support item assignment
Dictionary
A dictionary is a key-value pair set arranged in any order. It stores a specific value for each key, like an
associative array or a hash table. Value is any Python object, while the key can hold any primitive data
type.

The comma (,) and the curly braces are used to separate the items in the dictionary.

Look at the following example.

. d = {1:'Jimmy', 2:'Alex', 3:'john', 4:'mike'}


.
. # Printing dictionary
. print (d)
.
. # Accesing value using keys
. print("1st name is "+d[1])
. print("2nd name is "+ d[4])
.
. print (d.keys())

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


. print (d.values())
Output:

1st name is Jimmy


2nd name is mike
{1: 'Jimmy', 2: 'Alex', 3: 'john', 4: 'mike'}
dict_keys([1, 2, 3, 4])
dict_values(['Jimmy', 'Alex', 'john', 'mike'])
Boolean
True and False are the two default values for the Boolean type. These qualities are utilized to decide the
given assertion valid or misleading. The class book indicates this. False can be represented by the 0 or the
letter "F," while true can be represented by any value that is not zero.

Look at the following example.

. # Python program to check the boolean type


. print(type(True))
. print(type(False))
. print(false)
Output:

<class 'bool'>
<class 'bool'>
NameError: name 'false' is not defined
Set
The data type's unordered collection is Python Set. It is iterable, mutable(can change after creation), and
has remarkable components. The elements of a set have no set order; It might return the element's altered
sequence. Either a sequence of elements is passed through the curly braces and separated by a comma to
create the set or the built-in function set() is used to create the set. It can contain different kinds of values.

Look at the following example

. # Creating Empty set


. set1 = set()
.
. set2 = {'James', 2, 3,'Python'}
.
. #Printing Set value
. print(set2)
.
. # Adding element to the set
.
. set2.add(10)
. print(set2)
.
. #Removing element from the set
. set2.remove(2)
. print(set2)

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


Output:

{3, 'Python', 'James', 2}


{'Python', 'James', 3, 2, 10}
Python Numbers
The number data types are used to store the numeric values inside the variables. Number objects are
created when some value is assigned to a variable. For example, a = 5 will create a number object a with
value 5.

Python also allows us to delete the reference of a number by using the del keyword. For example, del a
will delete the object a declared above.

In Python, there are four types of numbers that can be assigned to a variable given as follows.

o Int (signed Integer object) : they are the negative or non-negative numbers with no decimal
point. There is no limit on an integer in python. However, the size of the integer is constrained by
the amount of the memory our system has.
Python also provides the support for various number systems like binary, hexadecimal, and octal
values. To store values in different number systems, consider the following pattern.

Prefix Interpretation Base Example

0b10 = 2 (decimal)
0b
Binary 2 0b1010 = 10 (decimal)
0B
0B101 = 5 (decimal)

0o10 = 8
0o
Octal 8 0o12 = 10
0O
0O132 =decimal

0xA = 10
0x
Hexadecimal 16 0xB = 11
0X
0XBE = 190

o float (floating point numbers) :


The float type is used to store the decimal point (floating point) numbers. In python, float may
also be written in scientific notation representing the power of 10. for example, 2.5e2 represents
the value 250.0.
o Complex (complex numbers)
Complex numbers are of the form a+bj where a is the real part of the number and bj is the
imaginary part of the number. The imaginary i is nothing but the square root of -1. It is not as
much used in the programming.
Number type conversion
The various types of numbers like int, float, complex are also as the functions in python. It is similar to
the wrapper classes of Java which is mostly used for typecasting. However, python internally perform
type casting in the expression evaluation and binds the values to their actual types but there are some
cases where we may have to define the data type of a value explicitly.

For example, while accepting the value from the user using the input() function, we have to convert the
entered string by the user to integer explicitly if we need an integer value.

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


There are the following functions which are used to perform type conversion.

o int (a) converts a to integer.


o float(a) converts a to float.
o complex(a) converts a to complex.
o complex (a,b) converts a and b to complex numbers with real part a and imaginary part b.

Example

. i="123456"
. print(type(i))
. num = int(i)
. print(num)
. print(type(num))
. j = 190.98
. print(int(j));
Output:

<class 'str'>
123456
<class 'int'>
190
Type Casting in Python (Implicit and Explicit) with Examples

Introduction

In the domain of Python programming, the capacity to control information flawlessly is critical. Integral
to this capacity is type casting, likewise alluded to as type change. Type casting includes changing the
information kind of a variable starting with one structure then onto the next. In Python, this change can
happen either verifiably, where the translator consequently plays out the transformation, or expressly,
where the developer determines the transformation.

Fundamentals of Type Casting

Definition of Type Casting

Type casting, on a very basic level, is the method involved with changing the information kind of a
variable. It empowers Python designers to explore the powerful idea of the language by working with
changes between divergent information types. This change guarantees that information can be used
properly inside the setting of a program.

Significance of Type Casting in Python

Type giving serves a role as a key part in Python programming, empowering consistent information
control. Its importance lies in its capacity to adjust information to the necessities of a program,
subsequently upgrading adaptability and usefulness. By working with the change between various
information types, type casting enables designers to handle different programming difficulties effortlessly.

Understanding Python's Dynamic Typing System

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


Python embraces a powerful composing framework, recognizing it from statically-composed dialects. In
Python, factors are not bound to a particular information type during statement. All things being equal,
the translator powerfully relegates an information type in light of the worth doled out to the variable. This
powerful nature bears the cost of Python unmatched adaptability, considering the control of information
without the limitations forced by static composing.

Built-in Data Types in Python:


In Python, information types are the orders of information things that demonstrate the tasks that can be
performed on the information and the strategies for putting away it. Python offers a rich assortment of
inherent information types, each filling explicit needs and giving interesting functionalities.
Understanding these information types is key for powerful programming. We should dig into the implicit
information types in Python:

Numeric Types:

o int: Addresses numbers, entire numbers without a fragmentary part.


o float: Addresses drifting point numbers, genuine numbers with a decimal point.
o complex: Addresses complex numbers in the structure a + bj, where an and b are genuine
numbers, and j is the nonexistent unit.
Sequence Types:

o str: Addresses strings, successions of Unicode characters encased inside single, twofold, or triple
statements.
o list: Addresses records, requested assortments of things encased inside square sections [ ].
Records are variable, meaning their components can be adjusted after creation.
o tuple: Addresses tuples, requested assortments of things encased inside brackets ( ). Tuples are
changeless, meaning their components can't be altered after creation.
o range: Addresses a succession of numbers produced by the reach() capability.
Mapping Type:

o dict: Addresses word references, unordered assortments of key-esteem matches encased inside
wavy supports { }. Word references are changeable and permit quick recovery of values in light
of keys.
Set Types:

o set: Addresses sets, unordered assortments of one of a kind components encased inside wavy
supports { }. Sets don't permit copy components.
o frozenset: Addresses frozensets, unchanging sets whose components can't be changed after
creation.
Boolean Sort:

o bool: Addresses boolean qualities, Valid or Misleading, utilized for sensible tasks and
correlations.
Binary Types:

o bytes: Addresses successions of bytes, unchanging arrangements of whole numbers in the reach 0
to 255.
o bytearray: Addresses variable groupings of bytes, like bytes protests however changeable.

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


o memoryview: Addresses memory sees, protests that permit Python code to get to the interior
information of an article that upholds the support convention.

Implicit Type Casting:

Implicit type casting, otherwise called programmed type change, is a cycle where the Python translator
consequently changes over one information type to one more without the requirement for express
directions from the developer. This transformation happens consistently during activities including
operands of various information types.

Automatic Conversion by Python Interpreter:

While performing activities, like number-crunching tasks or examinations, with operands of various
information types, Python's mediator insightfully deals with the change cycle to guarantee similarity. The
mediator switches the operands over completely to a typical information type in view of specific
principles characterized inside the language.

Significance:

Understood type casting assumes a critical part in improving on code and upgrading adaptability.

By permitting programmed change between information types, Python empowers software engineers to
zero in on the rationale of their code without agonizing over the complexities of type similarity.

Explicit type casting

Explicit type casting, otherwise called manual sort change, alludes to the most common way of changing
over a worth starting with one information type then onto the next unequivocally utilizing predefined
capabilities or techniques given by the programming language. In Python, express sort casting permits
designers to exactly control how information is changed over between various kinds, guaranteeing
similarity and rightness in tasks.

Manual Conversion by the Programmer

In express sort casting, the software engineer determines the ideal transformation utilizing worked in
capabilities or constructors given by Python. This approach offers clearness and straightforwardness in
code, making it express to different designers or perusers how information types are being controlled.

Using Built-in Functions for Type Casting

Python gives a bunch of implicit capabilities explicitly intended for type casting. These capabilities
permit software engineers to change over values between different information types consistently. A
portion of the generally involved capabilities for unequivocal sort casting include:

int(): Converts a worth to a whole number.

float(): Converts a worth to a drifting point number.

str(): Converts a worth to a string.

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


bool(): Converts a worth to a boolean.

Differences Between Implicit and Explicit Type Casting:

Comparison of Automatic vs. Manual Conversion:

Implicit Type Casting:

o Automatic: Happens flawlessly without unequivocal directions from the software engineer.
o Handled by Interpreter: The Python translator deals with the change cycle during activities
including operands of various information types.
o Convenience: Improves on code via naturally changing over information types depending on the
situation, diminishing the requirement for express sort transformation proclamations.
Explicit Type Casting:

o Manual: Requires express guidelines from the software engineer utilizing predefined capabilities
or strategies.
o Programmer Control: Designers have exact command over the change interaction, determining
the ideal information type transformation.
o Clarity and Precision: Offers straightforwardness and lucidity in code, making it unequivocal
how information types are being controlled.

Python String
Till now, we have discussed numbers as the standard data-types in Python. In this section of the tutorial,
we will discuss the most popular data type in Python, i.e., string.

Python string is the collection of the characters surrounded by single quotes, double quotes, or triple
quotes. The computer does not understand the characters; internally, it stores manipulated character as
the combination of the 0's and 1's.

Each character is encoded in the ASCII or Unicode character. So we can say that Python strings are also
called the collection of Unicode characters.

In Python, strings can be created by enclosing the character or the sequence of characters in the quotes.
Python allows us to use single quotes, double quotes, or triple quotes to create the string.

Consider the following example in Python to create a string.

Syntax:

. str = "Hi Python !"


Here, if we check the type of the variable str using a Python script

. print(type(str)), then it will print a string (str).


In Python, strings are treated as the sequence of characters, which means that Python doesn't support the
character data-type; instead, a single character written as 'p' is treated as the string of length 1.

Creating String in Python

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


We can create a string by enclosing the characters in single-quotes or double- quotes. Python also
provides triple-quotes to represent the string, but it is generally used for multiline string or docstrings.

. #Using single quotes


. str1 = 'Hello Python'
. print(str1)
. #Using double quotes
. str2 = "Hello Python"
. print(str2)
.
. #Using triple quotes
. str3 = '''''Triple quotes are generally used for
. represent the multiline or
. docstring'''
. print(str3)
Output:

Hello Python
Hello Python
Triple quotes are generally used for
represent the multiline or
docstring
Python Boolean
Python includes a built-in data type called Boolean, which can be either True or False. This type is
commonly used to represent the outcome of logical comparisons or conditions.

Examples:

. Input: 19 == 19
. Output: True
. Input: 24 < 19
. Output: False
Python Boolean Type
A Boolean type can only have two possible values: True or False. The variable's data type is shown as
Boolean by the output <class 'bool'>.

# defining and initializing the variables


. p = True
. q = False
. # printing the data type of the variables
. print(type(p))
. print(type(q))
Program Explanation:

This Python program shows how to find the data type of variables using the type() method. The data type,
'bool' (Boolean), is returned by type(p), and an is assigned the Boolean value True in the code. Similar to
this, type(q) yields 'bool,' and b is given the Boolean value False.

Output:

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


<class 'bool'>
<class 'bool'>
Assess Expressions and Variables
The Python bool() function enables us to assess values and variables. This method checks if a value is
true or false based on common rules for determining truthiness. It converts or evaluates the value to
return either True or False.

Syntax:

. bool([x])
Python bool() Function
You can also check if something is true or false without using the bool() function. Following a
comparison, the Boolean values will be given back. When the equality comparison is performed in the
example below, the Boolean value False will be present in the variable res.

.
. # a Python program demonstrating the
. # working of the built-in bool() method
. p = 18
. q = 40
. print(bool(p == q)) # Returns False since p and q are not equal.
. p = None
. print(bool(p)) # Returns False as p is None
. p = ()
. print(bool(p)) # Returns False as the sequence p is empty.
. p = {}
. print(bool(p)) # Returns False as the sequence p is mapping
. p = 0.0
. print(bool(p)) # Returns False as p is 0
. p = 'JavaTpoint'
. print(bool(p)) # Since p is a non-empty string, it returns True.
Program Explanation:

This Python program shows how to use the built-in bool() method to determine whether or not various
values are true. Since 18 and 40 are not equal, it checks if p is equal to q in the first case, which returns
False. The subsequent case checks the Boolean value of p when it is set to None, which returns False.
Since the tuple p in the third case is empty, the outcome is False. Likewise, the fourth case looks at a
vacant word, map p, returning False. The fifth case assesses the Boolean value of p when it is set to 0.0,
resulting in False. The program concludes by evaluating the Boolean value of the non-empty string p
('JavaTpoint'), which is True. This program demonstrates how the Python bool() method can be used to
evaluate the truthiness of various data types and expressions.

Output:

False
False
False
False
False
True

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


UNIT -II
Python If-else statements
Decision making is the most important aspect of almost all the programming languages. As the name
implies, decision making allows us to run a particular block of code for a particular decision. Here, the
decisions are made on the validity of the particular conditions. Condition checking is the backbone of
decision making.

In python, decision making is performed by the following statements.

Statement Description

The if statement is used to test a specific condition. If


If Statement the condition is true, a block of code (if-block) will be
executed.

The if-else statement is similar to if statement except the


fact that, it also provides the block of the code for the
If - else Statement false case of the condition to be checked. If the condition
provided in the if statement is false, then the else
statement will be executed.

Nested if statements enable us to use if ? else statement


Nested if Statement
inside an outer if statement.
Indentation in Python
For the ease of programming and to achieve simplicity, python doesn't allow the use of parentheses for
the block level code. In Python, indentation is used to declare a block. If two statements are at the same
indentation level, then they are the part of the same block.

Generally, four spaces are given to indent the statements which are a typical amount of indentation in
python.
Indentation is the most used part of the python language since it declares the block of code. All the
statements of one block are intended at the same level indentation. We will see how the actual
indentation takes place in decision making and other stuff in python.
The if statement
The if statement is used to test a particular condition and if the condition is true, it executes a block of
code known as if-block. The condition of if statement can be any valid logical expression which can be

either evaluated to tru e or false.

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


The syntax of the if-statement is given below.

. if expression:
. statement
Example 1
. # Simple Python program to understand the if statement
. num = int(input("enter the number:"))
. # Here, we are taking an integer num and taking input dynamically
. if num%2 == 0:
. # Here, we are checking the condition. If the condition is true, we will enter the block
. print("The Given number is an even number")
Output:

enter the number: 10


The Given number is an even number
The if-else statement
The if-else statement provides an else block combined with the if statement which is executed in the false
case of the condition.

If the condition is true, then the if-block is executed. Otherwise, the else-block is executed.

The syntax of the if-else statement is given below.

. if condition:
. #block of statements
. else:
. #another block of statements (else-block)

Example 1 : Program to check whether a person is eligible to vote or not.

. # Simple Python Program to check whether a person is eligible to vote or not.


. age = int (input("Enter your age: "))
. # Here, we are taking an integer num and taking input dynamically
. if age>=18:
. # Here, we are checking the condition. If the condition is true, we will enter the block
. print("You are eligible to vote !!");
. else:

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


. print("Sorry! you have to wait !!");
Output:

Enter your age: 90


You are eligible to vote !!

he elif statement

The elif statement enables us to check multiple conditions and execute the specific block of statements
depending upon the true condition among them. We can have any number of elif statements in our
program depending upon our need. However, using elif is optional.

The elif statement works like an if-else-if ladder statement in C. It must be succeeded by an if statement.

The syntax of the elif statement is given below.

. if expression 1:
. # block of statements
.
. elif expression 2:
. # block of statements
.
. elif expression 3:
. # block of statements
.
. else:
. # block of statements

Example 1

. # Simple Python program to understand elif statement


. number = int(input("Enter the number?"))
. # Here, we are taking an integer number and taking input dynamically
. if number==10:
. # Here, we are checking the condition. If the condition is true, we will enter the block
. print("The given number is equals to 10")
. elif number==50:
. # Here, we are checking the condition. If the condition is true, we will enter the block

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


. print("The given number is equal to 50");
. elif number==100:
. # Here, we are checking the condition. If the condition is true, we will enter the block
. print("The given number is equal to 100");
. else:
. print("The given number is not equal to 10, 50 or 100");
Output:

Enter the number?15


The given number is not equal to 10, 50 or 100

he elif statement

The elif statement enables us to check multiple conditions and execute the specific block of statements
depending upon the true condition among them. We can have any number of elif statements in our
program depending upon our need. However, using elif is optional.

The elif statement works like an if-else-if ladder statement in C. It must be succeeded by an if statement.

The syntax of the elif statement is given below.

. if expression 1:
. # block of statements
.
. elif expression 2:
. # block of statements
.
. elif expression 3:
. # block of statements
.
. else:
. # block of statements
.

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


Example 1

. # Simple Python program to understand elif statement


. number = int(input("Enter the number?"))
. # Here, we are taking an integer number and taking input dynamically
. if number==10:
. # Here, we are checking the condition. If the condition is true, we will enter the block
. print("The given number is equals to 10")
. elif number==50:
. # Here, we are checking the condition. If the condition is true, we will enter the block
. print("The given number is equal to 50");
. elif number==100:
. # Here, we are checking the condition. If the condition is true, we will enter the block
. print("The given number is equal to 100");
. else:
. print("The given number is not equal to 10, 50 or 100");
Output:

Enter the number?15


The given number is not equal to 10, 50 or 100

Python Loops
The following loops are available in Python to fulfil the looping needs. Python offers 3 choices for
running the loops. The basic functionality of all the techniques is the same, although the syntax and the
amount of time required for checking the condition differ.

We can run a single statement or set of statements repeatedly using a loop command.

The following sorts of loops are available in the Python programming language.

Sr.No. Name of the loop Loop Type & Description

Repeats a statement or group of


statements while a given condition
1 While loop
is TRUE. It tests the condition
before executing the loop body.

This type of loop executes a code


block multiple times and abbreviates
2 For loop
the code that manages the loop
variable.

We can iterate a loop inside another


3 Nested loops
loop.

Loop Control Statements

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


Statements used to control loops and change the course of iteration are called control statements. All the
objects produced within the local scope of the loop are deleted when execution is completed.

Python provides the following control statements. We will discuss them later in detail.

Let us quickly go over the definitions of these loop control statements.

Sr.No. Name of the control Description


statement

This command terminates the loop's execution and


1 Break statement transfers the program's control to the statement next
to the loop.

This command skips the current iteration of the loop.


The statements following the continue statement are
2 Continue statement
not executed once the Python interpreter reaches the
continue statement.

The pass statement is used when a statement is


3 Pass statement
syntactically necessary, but no code is to be executed.
The for Loop
Python's for loop is designed to repeatedly execute a code block while iterating through a list, tuple,
dictionary, or other iterable objects of Python. The process of traversing a sequence is known as iteration.

Syntax of the for Loop

. for value in sequence:


. { code block }
In this case, the variable value is used to hold the value of every item present in the sequence before the
iteration begins until this particular iteration is completed.

Loop iterates until the final item of the sequence are reached.

Code

. # Python program to show how the for loop works


.
. # Creating a sequence which is a tuple of numbers
. numbers = [4, 2, 6, 7, 3, 5, 8, 10, 6, 1, 9, 2]
.
. # variable to store the square of the number
. square = 0
.
. # Creating an empty list
. squares = []
.
. # Creating a for loop
. for value in numbers:

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


. square = value ** 2
. squares.append(square)
. print("The list of squares is", squares)
Output:

The list of squares is [16, 4, 36, 49, 9, 25, 64, 100, 36, 1, 81, 4]

Using else Statement with for Loop

As already said, a for loop executes the code block until the sequence element is reached. The statement
is written right after the for loop is executed after the execution of the for loop is complete.

Only if the execution is complete does the else statement comes into play. It won't be executed if we exit
the loop or if an error is thrown.

Here is a code to better understand if-else statements.

Code

. # Python program to show how if-else statements work


.
. string = "Python Loop"
.
. # Initiating a loop
. for s in a string:
. # giving a condition in if block
. if s == "o":
. print("If block")
. # if condition is not satisfied then else block will be executed
. else:
. print(s)
Output:

P
y
t
h
If block
n

L
If block
If block
p
Now similarly, using else with for loop.

Syntax:

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


. for value in sequence:
. # executes the statements until sequences are exhausted
. else:
. # executes these statements when for loop is completed
Code

. # Python program to show how to use else statement with for loop
.
. # Creating a sequence
. tuple_ = (3, 4, 6, 8, 9, 2, 3, 8, 9, 7)
.
. # Initiating the loop
. for value in tuple_:
. if value % 2 != 0:
. print(value)
. # giving an else statement
. else:
. print("These are the odd numbers present in the tuple")
Output:

3
9
3
9
7
These are the odd numbers present in the tuple

The range() Function

With the help of the range() function, we may produce a series of numbers. range(10) will produce values
between 0 and 9. (10 numbers).

We can give specific start, stop, and step size values in the manner range(start, stop, step size). If the step
size is not specified, it defaults to 1.

Since it doesn't create every value it "contains" after we construct it, the range object can be characterized
as being "slow." It does provide in, len, and __getitem__ actions, but it is not an iterator.

The example that follows will make this clear.

Code

. # Python program to show the working of range() function


.
. print(range(15))
.
. print(list(range(15)))
.
. print(list(range(4, 9)))

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


.
. print(list(range(5, 25, 4)))
Output:

range(0, 15)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
[4, 5, 6, 7, 8]
[5, 9, 13, 17, 21]
To iterate through a sequence of items, we can apply the range() method in for loops. We can use
indexing to iterate through the given sequence by combining it with an iterable's len() function. Here's an
illustration.

Code

. # Python program to iterate over a sequence with the help of indexing


.
. tuple_ = ("Python", "Loops", "Sequence", "Condition", "Range")
.
. # iterating over tuple_ using range() function
. for iterator in range(len(tuple_)):
. print(tuple_[iterator].upper())
Output:

PYTHON
LOOPS
SEQUENCE
CONDITION
RANGE

While Loop

While loops are used in Python to iterate until a specified condition is met. However, the statement in the
program that follows the while loop is executed once the condition changes to false.

Syntax of the while loop is:

. while <condition>:
. { code block }
All the coding statements that follow a structural command define a code block. These statements are
intended with the same number of spaces. Python groups statements together with indentation.
Code

. # Python program to show how to use a while loop


. counter = 0
. # Initiating the loop
. while counter < 10: # giving the condition
. counter = counter + 3
. print("Python Loops")
Output:

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


Python Loops
Python Loops
Python Loops
Python Loops

Using else Statement with while Loops

As discussed earlier in the for loop section, we can use the else statement with the while loop also. It has
the same syntax.

Code

. #Python program to show how to use else statement with the while loop
. counter = 0
.
. # Iterating through the while loop
. while (counter < 10):
. counter = counter + 3
. print("Python Loops") # Executed untile condition is met
. # Once the condition of while loop gives False this statement will be executed
. else:
. print("Code block inside the else statement")
Output:

Python Loops
Python Loops
Python Loops
Python Loops
Code block inside the else statement

Single statement while Block

The loop can be declared in a single statement, as seen below. This is similar to the if-else block, where
we can write the code block in a single line.

Code

. # Python program to show how to write a single statement while loop


. counter = 0
. while (count < 3): print("Python Loops")

Loop Control Statements

Now we will discuss the loop control statements in detail. We will see an example of each control
statement.

Continue Statement

It returns the control to the beginning of the loop.

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


Code

. # Python program to show how the continue statement works


.
. # Initiating the loop
. for string in "Python Loops":
. if string == "o" or string == "p" or string == "t":
. continue
. print('Current Letter:', string)
Output:

Current Letter: P
Current Letter: y
Current Letter: h
Current Letter: n
Current Letter:
Current Letter: L
Current Letter: s

Break Statement

It stops the execution of the loop when the break statement is reached.

Code

. # Python program to show how the break statement works


.
. # Initiating the loop
. for string in "Python Loops":
. if string == 'L':
. break
. print('Current Letter: ', string)
Output:

Current Letter: P
Current Letter: y
Current Letter: t
Current Letter: h
Current Letter: o
Current Letter: n
Current Letter:

Pass Statement

Pass statements are used to create empty loops. Pass statement is also employed for classes, functions,
and empty control statements.

Code

. # Python program to show how the pass statement works

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


. for a string in "Python Loops":
. pass
. print( 'Last Letter:', string)
Output:

Last Letter: s

Python for loop

Python is a strong, universally applicable prearranging language planned to be easy to comprehend and
carry out. It is allowed to get to because it is open-source. In this tutorial, we will learn how to use
Python for loops, one of the most fundamental looping instructions in Python programming.

Syntax of for Loop

. for value in sequence:


. {loop body}

Python While Loops

In coding, loops are designed to execute a specified code block repeatedly. We'll learn how to construct a
while loop in Python, the syntax of a while loop, loop controls like break and continue

. Statement
. while Condition:
. Statement

Python List
In Python, the sequence of various data types is stored in a list. A list is a collection of different kinds of
values or items. Since Python lists are mutable, we can change their elements after forming. The comma
(,) and the square brackets [enclose the List's items] serve as separators.

Although six Python data types can hold sequences, the List is the most common and reliable form. A list,
a type of sequence data, is used to store the collection of data. Tuples and Strings are two similar data
formats for sequences.

Lists written in Python are identical to dynamically scaled arrays defined in other languages, such as
Array List in Java and Vector in C++. A list is a collection of items separated by commas and denoted by
the symbol [].

List Declaration

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


Code
. # a simple list
. list1 = [1, 2, "Python", "Program", 15.9]
. list2 = ["Amy", "Ryan", "Henry", "Emma"]
.
. # printing the list
. print(list1)
. print(list2)
.
. # printing the type of list
. print(type(list1))
. print(type(list2))
Output:

[1, 2, 'Python', 'Program', 15.9]


['Amy', 'Ryan', 'Henry', 'Emma']
< class ' list ' >
< class ' list ' >
Characteristics of Lists
The characteristics of the List are as follows:

o The lists are in order.


o The list element can be accessed via the index.
o The mutable type of List is
o The rundowns are changeable sorts.
o The number of various elements can be stored in a list.
Ordered List Checking
Code

. # example
. a = [ 1, 2, "Ram", 3.50, "Rahul", 5, 6 ]
. b = [ 1, 2, 5, "Ram", 3.50, "Rahul", 6 ]
. a == b
Output:

False
The indistinguishable components were remembered for the two records; however, the subsequent
rundown changed the file position of the fifth component, which is against the rundowns' planned request.
False is returned when the two lists are compared.

Code

. # example
. a = [ 1, 2, "Ram", 3.50, "Rahul", 5, 6]
. b = [ 1, 2, "Ram", 3.50, "Rahul", 5, 6]
. a == b
Output:

True
Records forever protect the component's structure. Because of this, it is an arranged collection of things.

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


Let's take a closer look at the list example.

Code

. # list example in detail


. emp = [ "John", 102, "USA"]
. Dep1 = [ "CS",10]
. Dep2 = [ "IT",11]
. HOD_CS = [ 10,"Mr. Holding"]
. HOD_IT = [11, "Mr. Bewon"]
. print("printing employee data ...")
. print(" Name : %s, ID: %d, Country: %s" %(emp[0], emp[1], emp[2]))
. print("printing departments ...")
. print("Department 1:\nName: %s, ID: %d\n Department 2:\n Name: %s, ID: %s"%( Dep1[0], De
p2[1], Dep2[0], Dep2[1]))
. print("HOD Details ....")
. print("CS HOD Name: %s, Id: %d" %(HOD_CS[1], HOD_CS[0]))
. print("IT HOD Name: %s, Id: %d" %(HOD_IT[1], HOD_IT[0]))
. print(type(emp), type(Dep1), type(Dep2), type(HOD_CS), type(HOD_IT))
Output:

printing employee data...


Name : John, ID: 102, Country: USA
printing departments...
Department 1:
Name: CS, ID: 11
Department 2:
Name: IT, ID: 11
HOD Details ....
CS HOD Name: Mr. Holding, Id: 10
IT HOD Name: Mr. Bewon, Id: 11
<class ' list '> <class ' list '> <class ' list '> <class ' list '> <class ' list '>
In the preceding illustration, we printed the employee and department-specific details from lists that we
had created. To better comprehend the List's concept, look at the code above.

List Indexing and Splitting


The indexing procedure is carried out similarly to string processing. The slice operator [] can be used to
get to the List's components.

The index ranges from 0 to length -1. The 0th index is where the List's first element is stored; the 1st
index is where the second element is stored, and so on.

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


We can get the sub-list of the list using the following syntax.

. list_varible(start:stop:step)

o The beginning indicates the beginning record position of the rundown.


o The stop signifies the last record position of the rundown.
o Within a start, the step is used to skip the nth element: stop.
The start parameter is the initial index, the step is the ending index, and the value of the end parameter is
the number of elements that are "stepped" through. The default value for the step is one without a specific
value. Inside the resultant Sub List, the same with record start would be available, yet the one with the
file finish will not. The first element in a list appears to have an index of zero.

Python Tuples
Understanding the Tuples in Python

Tuple is one of the four primary data types in Python. It is a used for storing a collection of objects. A
tuple is quite similar to a Python list in terms of indexing, nested objects, and repetition; however, the
main difference between both is that the tuples in Python are immutable, unlike the Python list which is
mutable.

The following is an example of a tuple.

Example:

. ("Suzuki", "Audi", "BMW"," Skoda ", "Honda") is a tuple.

Key Features of Python Tuple

1. Tuples are an immutable data type, implying that the data elements of this data type cannot be
changed after they are generated.
2. Each data element in a tuple has a particular order that never changes as the tuples are ordered
sequences.

Forming a Tuple:

All the objects-also known as "elements"-must be separated by a comma, enclosed in parenthesis ().
Although parentheses are not required, they are recommended.

Any number of items, including those with various data types (dictionary, string, float, list, etc.), can be
contained in a tuple.

Let us consider the following example demonstrating the inclusion of different data types in a tuple:

Code:

. # Python program to show how to create a tuple


. # Creating an empty tuple
. emptyTuple = ()

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


. print("Empty tuple: ", emptyTuple)
.
. # Creating a tuple having integers
. integerTuple = (3, 6, 7, 10, 16, 23)
. print("Tuple with integers: ", integerTuple)
.
. # Creating a tuple having objects of different data types
. mixedTuple = (6, "Javatpoint", 14.3)
. print("Tuple with different data types: ", mixedTuple)
.
. # Creating a nested tuple
. nestedTuple = ("Javatpoint", {4: 5, 6: 2, 8:2}, (5, 3, 5, 6))
. print("A nested tuple: ", nestedTuple)
Output:

Empty tuple: ()
Tuple with integers: (3, 6, 7, 10, 16, 23)
Tuple with different data types: (6, 'Javatpoint', 14.3)
A nested tuple: ('Javatpoint', {4: 5, 6: 2, 8: 2}, (5, 3, 5, 6))

Python List Vs Tuple


This tutorial will study the major differences between lists and tuples and how to handle these two data
structures.

Lists and tuples are types of data structures that hold one or more than one objects or items in a
predefined order. We can contain objects of any data type in a list or tuple, including the null data type
defined by the None Keyword.

What is a List?

In other programming languages, list objects are declared similarly to arrays. Lists don't have to be
homogeneous all the time, so they can simultaneously store items of different data types. This makes lists
the most useful tool. The list is a kind of container data Structure of Python that is used to hold numerous
pieces of data simultaneously. Lists are helpful when we need to iterate over some elements and keep
hold of the items.

What is a Tuple?

A tuple is another data structure to store the collection of items of many data types, but unlike mutable
lists, tuples are immutable. A tuple, in other words, is a collection of items separated by commas.
Because of its static structure, the tuple is more efficient than the list.

Differences between Lists and Tuples

In most cases, lists and tuples are equivalent. However, there are some important differences to be
explored in this article.

List and Tuple Syntax Differences

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


The syntax of a list differs from that of a tuple. Items of a tuple are enclosed by parentheses or curved
brackets (), whereas items of a list are enclosed by square brackets [].

Example Code

. # Python code to show the difference between creating a list and a tuple
.
. list_ = [4, 5, 7, 1, 7]
. tuple_ = (4, 1, 8, 3, 9)
.
. print("List is: ", list_)
. print("Tuple is: ", tuple_)
Output:

List is: [4, 5, 7, 1, 7]


Tuple is: (4, 1, 8, 3, 9)
We declared a variable named list_, which contains a certain number of integers ranging from 1 to 10.
The list is enclosed in square brackets []. We also created a variable called tuple_, which holds a certain
number of integers. The tuple is enclosed in curly brackets (). The type() method in Python returns the
data type of the data structure or object passed to it.

Python Set

A Python set is the collection of the unordered items. Each element in the set must be unique, immutable,
and the sets remove the duplicate elements. Sets are mutable which means we can modify it after its
creation.

Unlike other collections in Python, there is no index attached to the elements of the set, i.e., we cannot
directly access any element of the set by the index. However, we can print them all together, or we can
get the list of elements by looping through the set.

Creating a set

The set can be created by enclosing the comma-separated immutable items with the curly braces {}.
Python also provides the set() method, which can be used to create the set by the passed sequence.

Example 1: Using curly braces

. Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}


. print(Days)
. print(type(Days))
. print("looping through the set elements ... ")
. for i in Days:
. print(i)
Output:

{'Friday', 'Tuesday', 'Monday', 'Saturday', 'Thursday', 'Sunday', 'Wednesday'}

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


<class 'set'>
looping through the set elements ...
Friday
Tuesday
Monday
Saturday
Thursday
Sunday
Wednesday

Python Dictionary
Dictionaries are a useful data structure for storing data in Python because they are capable of imitating
real-world data arrangements where a certain value exists for a given key.

The data is stored as key-value pairs using a Python dictionary.

o This data structure is mutable


o The components of dictionary were made using keys and values.
o Keys must only have one component.
o Values can be of any type, including integer, list, and tuple.
A dictionary is, in other words, a group of key-value pairs, where the values can be any Python object.
The keys, in contrast, are immutable Python objects, such as strings, tuples, or numbers. Dictionary
entries are ordered as of Python version 3.7. In Python 3.6 and before, dictionaries are generally
unordered.

Creating the Dictionary

Curly brackets are the simplest way to generate a Python dictionary, although there are other approaches
as well. With many key-value pairs surrounded in curly brackets and a colon separating each key from its
value, the dictionary can be built. (:). The following provides the syntax for defining the dictionary.

Syntax:

. Dict = {"Name": "Gayle", "Age": 25}


In the above dictionary Dict, The keys Name and Age are the strings which comes under the category of
an immutable object.

Python Functions
This tutorial will go over the fundamentals of Python functions, including what they are, their syntax,
their primary parts, return keywords, and significant types. We'll also look at some examples of Python
function definitions.

What are Python Functions?

A collection of related assertions that carry out a mathematical, analytical, or evaluative operation is
known as a function. An assortment of proclamations called Python Capabilities returns the specific

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


errand. Python functions are necessary for intermediate-level programming and are easy to define.
Function names meet the same standards as variable names do. The objective is to define a function and
group-specific frequently performed actions. Instead of repeatedly creating the same code block for
various input variables, we can call the function and reuse the code it contains with different variables.

Client-characterized and worked-in capabilities are the two primary classes of capabilities in Python. It
aids in maintaining the program's uniqueness, conciseness, and structure.

Advantages of Python Functions

Pause We can stop a program from repeatedly using the same code block by including functions.

o Once defined, Python functions can be called multiple times and from any location in a program.
o Our Python program can be broken up into numerous, easy-to-follow functions if it is significant.
o The ability to return as many outputs as we want using a variety of arguments is one of Python's
most significant achievements.
o However, Python programs have always incurred overhead when calling functions.
However, calling functions has always been overhead in a Python program.

Syntax

. # An example Python Function


. def function_name( parameters ):
. # code block
The accompanying components make up to characterize a capability, as seen previously.

o The start of a capability header is shown by a catchphrase called def.


o function_name is the function's name, which we can use to distinguish it from other functions.
We will utilize this name to call the capability later in the program. Name functions in Python
must adhere to the same guidelines as naming variables.
o Using parameters, we provide the defined function with arguments. Notwithstanding, they are
discretionary.
o A colon (:) marks the function header's end.
o We can utilize a documentation string called docstring in the short structure to make sense of the
reason for the capability.
o Several valid Python statements make up the function's body. The entire code block's indentation
depth-typically four spaces-must be the same.
o A return expression can get a value from a defined function.

Illustration of a User-Defined Function

We will define a function that returns the argument number's square when called.

. # Example Python Code for User-Defined function


. def square( num ):
. """
. This function computes the square of the number.
. """
. return num**2
. object_ = square(6)

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


. print( "The square of the given number is: ", object_ )
Output:

The square of the given number is: 36


Calling a Function
Calling a Function To define a function, use the def keyword to give it a name, specify the arguments it
must receive, and organize the code block.

When the fundamental framework for a function is finished, we can call it from anywhere in the program.
An illustration of how to use the a_function function can be found below.

. # Example Python Code for calling a function


. # Defining a function
. def a_function( string ):
. "This prints the value of length of string"
. return len(string)
.
. # Calling the function we defined
. print( "Length of the string Functions is: ", a_function( "Functions" ) )
. print( "Length of the string Python is: ", a_function( "Python" ) )
Output:

Length of the string Functions is: 9


Length of the string Python is: 6
Pass by Reference vs. Pass by Value
In the Python programming language, all parameters are passed by reference. It shows that if we modify
the worth of contention within a capability, the calling capability will similarly mirror the change. For
instance,

Code

. # Example Python Code for Pass by Reference vs. Value


. # defining the function
. def square( item_list ):
. '''''''This function will find the square of items in the list'''
. squares = [ ]
. for l in item_list:
. squares.append( l**2 )
. return squares
.
. # calling the defined function
. my_list = [17, 52, 8];
. my_result = square( my_list )
. print( "Squares of the list are: ", my_result )
Output:

Squares of the list are: [289, 2704, 64]

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


Function Arguments

The following are the types of arguments that we can use to call a function:

1. Default arguments
2. Keyword arguments
3. Required arguments
4. Variable-length arguments

1) Default Arguments
A default contention is a boundary that takes as information a default esteem, assuming that no worth is
provided for the contention when the capability is called. The following example demonstrates default
arguments.

Code

. # Python code to demonstrate the use of default arguments


. # defining a function
. def function( n1, n2 = 20 ):
. print("number 1 is: ", n1)
. print("number 2 is: ", n2)
.
.
. # Calling the function and passing only one argument
. print( "Passing only one argument" )
. function(30)
.
. # Now giving two arguments to the function
. print( "Passing two arguments" )
. function(50,30)
Output:

Passing only one argument


number 1 is: 30
number 2 is: 20
Passing two arguments
number 1 is: 50
number 2 is: 30
2) Keyword Arguments
Keyword arguments are linked to the arguments of a called function. While summoning a capability with
watchword contentions, the client might tell whose boundary esteem it is by looking at the boundary
name.

We can eliminate or orchestrate specific contentions in an alternate request since the Python translator
will interface the furnished watchwords to connect the qualities with its boundaries. One more method
for utilizing watchwords to summon the capability() strategy is as per the following:

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


Code

. # Python code to demonstrate the use of keyword arguments


. # Defining a function
. def function( n1, n2 ):
. print("number 1 is: ", n1)
. print("number 2 is: ", n2)
.
. # Calling function and passing arguments without using keyword
. print( "Without using keyword" )
. function( 50, 30)
.
. # Calling function and passing arguments using keyword
. print( "With using keyword" )
. function( n2 = 50, n1 = 30)
Output:

Without using keyword


number 1 is: 50
number 2 is: 30
With using keyword
number 1 is: 30
number 2 is: 50

3) Required Arguments

Required arguments are those supplied to a function during its call in a predetermined positional
sequence. The number of arguments required in the method call must be the same as those provided in
the function's definition.

We should send two contentions to the capability() all put together; it will return a language structure
blunder, as seen beneath.

Code
. # Python code to demonstrate the use of default arguments
. # Defining a function
. def function( n1, n2 ):
. print("number 1 is: ", n1)
. print("number 2 is: ", n2)
.
. # Calling function and passing two arguments out of order, we need num1 to be 20 and num2 to
be 30
. print( "Passing out of order arguments" )
. function( 30, 20 )
.
. # Calling function and passing only one argument
. print( "Passing only one argument" )

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


. try:
. function( 30 )
. except:
. print( "Function needs two positional arguments" )
Output:

Passing out of order arguments


number 1 is: 30
number 2 is: 20
Passing only one argument
Function needs two positional arguments

4) Variable-Length Arguments

We can involve unique characters in Python capabilities to pass many contentions. However, we need a
capability. This can be accomplished with one of two types of characters:

"args" and "kwargs" refer to arguments not based on keywords.

To help you understand arguments of variable length, here's an example.

Code
. # Python code to demonstrate the use of variable-length arguments
. # Defining a function
. def function( *args_list ):
. ans = []
. for l in args_list:
. ans.append( l.upper() )
. return ans
. # Passing args arguments
. object = function('Python', 'Functions', 'tutorial')
. print( object )
.
. # defining a function
. def function( **kargs_list ):
. ans = []
. for key, value in kargs_list.items():
. ans.append([key, value])
. return ans
. # Paasing kwargs arguments
. object = function(First = "Python", Second = "Functions", Third = "Tutorial")
. print(object)
Output:

['PYTHON', 'FUNCTIONS', 'TUTORIAL']


[['First', 'Python'], ['Second', 'Functions'], ['Third', 'Tutorial']]

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


return Statement

When a defined function is called, a return statement is written to exit the function and return the
calculated value.

Syntax:

. return < expression to be returned as output >


The return statement can be an argument, a statement, or a value, and it is provided as output when a
particular job or function is finished. A declared function will return an empty string if no return
statement is written.

A return statement in Python functions is depicted in the following example.

Code

. # Python code to demonstrate the use of return statements


. # Defining a function with return statement
. def square( num ):
. return num**2
.
. # Calling function and passing arguments.
. print( "With return statement" )
. print( square( 52 ) )
.
. # Defining a function without return statement
. def square( num ):
. num**2
.
. # Calling function and passing arguments.
. print( "Without return statement" )
. print( square( 52 ) )
Output:

With return statement


2704
Without return statement
None

The Anonymous Functions

Since we do not use the def keyword to declare these kinds of Python functions, they are unknown. The
lambda keyword can define anonymous, short, single-output functions.

Arguments can be accepted in any number by lambda expressions; However, the function only produces
a single value from them. They cannot contain multiple instructions or expressions. Since lambda needs
articulation, a mysterious capability can't be straightforwardly called to print.

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


Lambda functions can only refer to variables in their argument list and the global domain name because
they contain their distinct local domain.

In contrast to inline expressions in C and C++, which pass function stack allocations at execution for
efficiency reasons, lambda expressions appear to be one-line representations of functions.

Syntax
Lambda functions have exactly one line in their syntax:

. lambda [argument1 [,argument2... .argumentn]] : expression


Below is an illustration of how to use the lambda function:

Code
. # Python code to demonstrate ananymous functions
. # Defining a function
. lambda_ = lambda argument1, argument2: argument1 + argument2;
.
. # Calling the function and passing values
. print( "Value of the function is : ", lambda_( 20, 30 ) )
. print( "Value of the function is : ", lambda_( 40, 50 ) )
Output:

Value of the function is : 50


Value of the function is : 90
Scope and Lifetime of Variables
A variable's scope refers to the program's domain wherever it is declared. A capability's contentions and
factors are not external to the characterized capability. They only have a local domain as a result.

The length of time a variable remains in RAM is its lifespan. The lifespan of a function is the same as the
lifespan of its internal variables. When we exit the function, they are taken away from us. As a result, the
value of a variable in a function does not persist from previous executions.

An easy illustration of a function's scope for a variable can be found here.

Code

. # Python code to demonstrate scope and lifetime of variables


. #defining a function to print a number.
. def number( ):
. num = 50
. print( "Value of num inside the function: ", num)
.
. num = 10
. number()
. print( "Value of num outside the function:", num)
Output:

Value of num inside the function: 50

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


Value of num outside the function: 10
Here, we can see that the initial value of num is 10. Even though the function number() changed the value
of num to 50, the value of num outside of the function remained unchanged.

This is because the capability's interior variable num is not quite the same as the outer variable (nearby to
the capability). Despite having a similar variable name, they are separate factors with discrete extensions.

Factors past the capability are available inside the capability. The impact of these variables is global. We
can retrieve their values within the function, but we cannot alter or change them. The value of a variable
can be changed outside of the function if it is declared global with the keyword global.

Python Capability inside Another Capability


Capabilities are viewed as top-of-the-line objects in Python. First-class objects are treated the same
everywhere they are used in a programming language. They can be stored in built-in data structures, used
as arguments, and in conditional expressions. If a programming language treats functions like first-class
objects, it is considered to implement first-class functions. Python lends its support to the concept of
First-Class functions.

A function defined within another is called an "inner" or "nested" function. The parameters of the outer
scope are accessible to inner functions. Internal capabilities are developed to cover them from the
progressions outside the capability. Numerous designers see this interaction as an embodiment.

Code

. # Python code to show how to access variables of a nested functions


. # defining a nested function
. def word():
. string = 'Python functions tutorial'
. x=5
. def number():
. print( string )
. print( x )
.
. number()
. word()
Output:

Python functions tutorial


5
Python Built-in Functions
The Python built-in functions are defined as the functions whose functionality is pre-defined in Python.
The python interpreter has several functions that are always present for use. These functions are known
as Built-in Functions. There are several built-in functions in Python which are listed below:

Python abs() Function


The python abs() function is used to return the absolute value of a number. It takes only one argument, a
number whose absolute value is to be returned. The argument can be an integer and floating-point
number. If the argument is a complex number, then, abs() returns its magnitude.

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


Python all() Function
The python all() function accepts an iterable object (such as list, dictionary, etc.). It returns true if all
items in passed iterable are true. Otherwise, it returns False. If the iterable object is empty, the all()
function returns True.

Python bin() Function


The python bin() function is used to return the binary representation of a specified integer. A result
always starts with the prefix 0b.

Python bool()
The python bool() converts a value to boolean(True or False) using the standard truth testing procedure.

Python bytes()
The python bytes() in Python is used for returning a bytes object. It is an immutable version of the
bytearray() function.

Python callable() Function


A python callable() function in Python is something that can be called. This built-in function checks and
returns true if the object passed appears to be callable, otherwise false.

Python compile() Function


The python compile() function takes source code as input and returns a code object which can later be
executed by exec() function.

Python exec() Function


The python exec() function is used for the dynamic execution of Python program which can either be a
string or object code and it accepts large blocks of code, unlike the eval() function which only accepts a
single expression.

Python sum() Function


As the name says, python sum() function is used to get the sum of numbers of an iterable, i.e., list.

Python any() Function


The python any() function returns true if any item in an iterable is true. Otherwise, it returns False.

Python ascii() Function


The python ascii() function returns a string containing a printable representation of an object and escapes
the non-ASCII characters in the string using \x, \u or \U escapes.

Python bytearray()
The python bytearray() returns a bytearray object and can convert objects into bytearray objects, or
create an empty bytearray object of the specified size.

Python eval() Function


The python eval() function parses the expression passed to it and runs python expression(code) within the
program.

Python float()
The python float() function returns a floating-point number from a number or string.

Python format() Function

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


The python format() function returns a formatted representation of the given value.

Python frozenset()
The python frozenset() function returns an immutable frozenset object initialized with elements from the
given iterable.

Python getattr() Function


The python getattr() function returns the value of a named attribute of an object. If it is not found, it
returns the default value.

Python globals() Function


The python globals() function returns the dictionary of the current global symbol table.

A Symbol table is defined as a data structure which contains all the necessary information about the
program. It includes variable names, methods, classes, etc.

Python hasattr() Function


The python any() function returns true if any item in an iterable is true, otherwise it returns False.

Python iter() Function


The python iter() function is used to return an iterator object. It creates an object which can be iterated
one element at a time.

Python len() Function


The python len() function is used to return the length (the number of items) of an object.

Python list()
The python list() creates a list in python.

Python locals() Function


The python locals() method updates and returns the dictionary of the current local symbol table

Python map() Function


The python map() function is used to return a list of results after applying a given function to each item
of an iterable(list, tuple etc.).

Python memoryview() Function


The python memoryview() function returns a memoryview object of the given argument.

Python object()
The python object() returns an empty object. It is a base for all the classes and holds the built-in
properties and methods which are default for all the classes.

Python open() Function


The python open() function opens the file and returns a corresponding file object.

Python chr() Function


Python chr() function is used to get a string representing a character which points to a Unicode code
integer. For example, chr(97) returns the string 'a'. This function takes an integer argument and throws an
error if it exceeds the specified range. The standard range of the argument is from 0 to 1,114,111.

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


Python complex()
Python complex() function is used to convert numbers or string into a complex number. This method
takes two optional parameters and returns a complex number. The first parameter is called a real and
second as imaginary parts.

Python delattr() Function


Python delattr() function is used to delete an attribute from a class. It takes two parameters, first is an
object of the class and second is an attribute which we want to delete. After deleting the attribute, it no
longer available in the class and throws an error if try to call it using the class object.

Python dir() Function


Python dir() function returns the list of names in the current local scope. If the object on which method is
called has a method named __dir__(), this method will be called and must return the list of attributes. It
takes a single object type argument.

Python divmod() Function


Python divmod() function is used to get remainder and quotient of two numbers. This function takes two
numeric arguments and returns a tuple. Both arguments are required and numeric

Python enumerate() Function


Python enumerate() function returns an enumerated object. It takes two parameters, first is a sequence of
elements and the second is the start index of the sequence. We can get the elements in sequence either
through a loop or next() method.

Python dict()
Python dict() function is a constructor which creates a dictionary. Python dictionary provides three
different constructors to create a dictionary:

o If no argument is passed, it creates an empty dictionary.


o If a positional argument is given, a dictionary is created with the same key-value pairs. Otherwise,
pass an iterable object.
o If keyword arguments are given, the keyword arguments and their values are added to the
dictionary created from the positional argument.
Python filter() Function
Python filter() function is used to get filtered elements. This function takes two arguments, first is a
function and the second is iterable. The filter function returns a sequence of those elements of iterable
object for which function returns true value.

Python hash() Function


Python hash() function is used to get the hash value of an object. Python calculates the hash value by
using the hash algorithm. The hash values are integers and used to compare dictionary keys during a
dictionary lookup. We can hash only the types which are given below:

Hashable types: * bool * int * long * float * string * Unicode * tuple * code object.

Python help() Function


Python help() function is used to get help related to the object passed during the call. It takes an optional
parameter and returns help information. If no argument is given, it shows the Python help console. It
internally calls python's help function.

Python min() Function

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


Python min() function is used to get the smallest element from the collection. This function takes two
arguments, first is a collection of elements and second is key, and returns the smallest element from the
collection.

Etc

Lambda Functions in Python?


Lambda Functions in Python are anonymous functions, implying they don't have a name. The def
keyword is needed to create a typical function in Python, as we already know. We can also use the
lambda keyword in Python to define an unnamed function.

Syntax
The syntax of the Lambda Function is given below -

. lambda arguments: expression


This function accepts any count of inputs but only evaluates and returns one expression. That means it
takes many inputs but returns only one output.

Lambda functions can be used whenever function arguments are necessary. In addition to other forms of
formulations in functions, it has a variety of applications in certain coding domains. It's important to
remember that according to syntax, lambda functions are limited to a single statement.

Example
Here we share some examples of lambda functions in Python for learning purposes. Program Code 1:

Now we gave an example of a lambda function that adds 4 to the input number is shown below.

. # Code to demonstrate how we can use a lambda function for adding 4 numbers
. add = lambda num: num + 4
. print( add(6) )
Output:

Now we compile the above code in Python, and after successful compilation, we run it. Then the output
is given below -

10

Modular Programming

Modular programming is the practice of segmenting a single, complicated coding task into multiple,
simpler, easier-to-manage sub-tasks. We call these subtasks modules. Therefore, we can build a bigger
program by assembling different modules that act like building blocks.

Modularizing our code in a big application has a lot of benefits.

Simplification: A module often concentrates on one comparatively small area of the overall problem
instead of the full task. We will have a more manageable design problem to think about if we are only
concentrating on one module. Program development is now simpler and much less vulnerable to mistakes.

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


Flexibility: Modules are frequently used to establish conceptual separations between various problem
areas. It is less likely that changes to one module would influence other portions of the program if
modules are constructed in a fashion that reduces interconnectedness. (We might even be capable of
editing a module despite being familiar with the program beyond it.) It increases the likelihood that a
group of numerous developers will be able to collaborate on a big project.

Reusability: Functions created in a particular module may be readily accessed by different sections of
the assignment (through a suitably established api). As a result, duplicate code is no longer necessary.

Scope: Modules often declare a distinct namespace to prevent identifier clashes in various parts of a
program.

In Python, modularization of the code is encouraged through the use of functions, modules, and packages.

Modules in Python
A document with definitions of functions and various statements written in Python is called a Python
module.

In Python, we can define a module in one of 3 ways:

o Python itself allows for the creation of modules.


o Similar to the re (regular expression) module, a module can be primarily written in C
programming language and then dynamically inserted at run-time.
o A built-in module, such as the itertools module, is inherently included in the interpreter.
A module is a file containing Python code, definitions of functions, statements, or classes. An
example_module.py file is a module we will create and whose name is example_module.

We employ modules to divide complicated programs into smaller, more understandable pieces. Modules
also allow for the reuse of code.

Rather than duplicating their definitions into several applications, we may define our most frequently
used functions in a separate module and then import the complete module.

Let's construct a module. Save the file as example_module.py after entering the following.

Example:

. # Here, we are creating a simple Python program to show how to create a module.
. # defining a function in the module to reuse it
. def square( number ):
. # here, the above function will square the number passed as the input
. result = number ** 2
. return result # here, we are returning the result of the function
Here, a module called example_module contains the definition of the function square(). The function
returns the square of a given number.

How to Import Modules in Python?

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


In Python, we may import functions from one module into our program, or as we say into, another
module.

For this, we make use of the import Python keyword. In the Python window, we add the next to import
keyword, the name of the module we need to import. We will import the module we defined earlier
example_module.

Syntax:

. import example_module
The functions that we defined in the example_module are not immediately imported into the present
program. Only the name of the module, i.e., example_ module, is imported here.

We may use the dot operator to use the functions using the module name. For instance:

Example:

. # here, we are calling the module square method and passing the value 4
. result = example_module.square( 4 )
. print("By using the module square of number is: ", result )
Output:

By using the module square of number is: 16

Python Exceptions
When a Python program meets an error, it stops the execution of the rest of the program. An error in
Python might be either an error in the syntax of an expression or a Python exception. We will see what an
exception is. Also, we will see the difference between a syntax error and an exception in this tutorial.
Following that, we will learn about trying and except blocks and how to raise exceptions and make
assertions. After that, we will see the Python exceptions list.

What is an Exception?
An exception in Python is an incident that happens while executing a program that causes the regular
course of the program's commands to be disrupted. When a Python code comes across a condition it can't
handle, it raises an exception. An object in Python that describes an error is called an exception.

When a Python code throws an exception, it has two options: handle the exception immediately or stop
and quit.

Exceptions versus Syntax Errors


When the interpreter identifies a statement that has an error, syntax errors occur. Consider the following
scenario:

Code

. #Python code after removing the syntax error


. string = "Python Exceptions"
.

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


. for s in string:
. if (s != o:
. print( s )
Output:

if (s != o:
^
SyntaxError: invalid syntax
The arrow in the output shows where the interpreter encountered a syntactic error. There was one
unclosed bracket in this case. Close it and rerun the program:

Code
. #Python code after removing the syntax error
. string = "Python Exceptions"
.
. for s in string:
. if (s != o):
. print( s )
Output:

2 string = "Python Exceptions"


4 for s in string:
----> 5 if (s != o):
6 print( s )

NameError: name 'o' is not defined


We encountered an exception error after executing this code. When syntactically valid Python code
produces an error, this is the kind of error that arises. The output's last line specified the name of the
exception error code encountered. Instead of displaying just "exception error", Python displays
information about the sort of exception error that occurred. It was a NameError in this situation. Python
includes several built-in exceptions. However, Python offers the facility to construct custom exceptions.

Try and Except Statement - Catching Exceptions


In Python, we catch exceptions and handle them using try and except code blocks. The try clause
contains the code that can raise an exception, while the except clause contains the code lines that handle
the exception. Let's see if we can access the index from the array, which is more than the array's length,
and handle the resulting exception.

Code
. # Python code to catch an exception and handle it using try and except code blocks
.
. a = ["Python", "Exceptions", "try and except"]
. try:
. #looping through the elements of the array a, choosing a range that goes beyond the length of
the array
. for i in range( 4 ):
. print( "The index and element from the array is", i, a[i] )
. #if an error occurs in the try block, then except block will be executed by the Python interpreter

. except:

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


. print ("Index out of range")
Output:

The index and element from the array is 0 Python


The index and element from the array is 1 Exceptions
The index and element from the array is 2 try and except
Index out of range
The code blocks that potentially produce an error are inserted inside the try clause in the preceding
example. The value of i greater than 2 attempts to access the list's item beyond its length, which is not
present, resulting in an exception. The except clause then catches this exception and executes code
without stopping it.

How to Raise an Exception


If a condition does not meet our criteria but is correct according to the Python interpreter, we can
intentionally raise an exception using the raise keyword. We can use a customized exception in
conjunction with the statement.

If we wish to use raise to generate an exception when a given condition happens, we may do so as
follows:

Code
. #Python code to show how to raise an exception in Python
. num = [3, 4, 5, 7]
. if len(num) > 3:
. raise Exception( f"Length of the given list must be less than or equal to 3 but is {len(num)}" )

Output:

1 num = [3, 4, 5, 7]
2 if len(num) > 3:
----> 3 raise Exception( f"Length of the given list must be less than or equal to 3 but is {len(num)}" )

Exception: Length of the given list must be less than or equal to 3 but is 4
The implementation stops and shows our exception in the output, providing indications as to what went
incorrect.

Assertions in Python
When we're finished verifying the program, an assertion is a consistency test that we can switch on or off.

The simplest way to understand an assertion is to compare it with an if-then condition. An exception is
thrown if the outcome is false when an expression is evaluated.

Assertions are made via the assert statement, which was added in Python 1.5 as the latest keyword.

Assertions are commonly used at the beginning of a function to inspect for valid input and at the end of
calling the function to inspect for valid output.

The assert Statement

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


Python examines the adjacent expression, preferably true when it finds an assert statement. Python
throws an AssertionError exception if the result of the expression is false.

The syntax for the assert clause is −


. assert Expressions[, Argument]
Python uses ArgumentException, if the assertion fails, as the argument for the AssertionError. We can
use the try-except clause to catch and handle AssertionError exceptions, but if they aren't, the program
will stop, and the Python interpreter will generate a traceback.

Code
. #Python program to show how to use assert keyword
. # defining a function
. def square_root( Number ):
. assert ( Number < 0), "Give a positive integer"
. return Number**(1/2)
.
. #Calling function and passing the values
. print( square_root( 36 ) )
. print( square_root( -36 ) )
Output:

7 #Calling function and passing the values


----> 8 print( square_root( 36 ) )
9 print( square_root( -36 ) )

Input In [23], in square_root(Number)


3 def square_root( Number ):
----> 4 assert ( Number < 0), "Give a positive integer"
5 return Number**(1/2)

AssertionError: Give a positive integer


Try with Else Clause
Python also supports the else clause, which should come after every except clause, in the try, and except
blocks. Only when the try clause fails to throw an exception the Python interpreter goes on to the else
block.

Here is an instance of a try clause with an else clause.

Code
. # Python program to show how to use else clause with try and except clauses
.
. # Defining a function which returns reciprocal of a number
. def reciprocal( num1 ):
. try:
. reci = 1 / num1
. except ZeroDivisionError:
. print( "We cannot divide by zero" )
. else:
. print ( reci )
. # Calling the function and passing values

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


. reciprocal( 4 )
. reciprocal( 0 )
Output:

0.25
We cannot divide by zero

Finally Keyword in Python

The finally keyword is available in Python, and it is always used after the try-except block. The finally
code block is always executed after the try block has terminated normally or after the try block has
terminated for some other reason.

Here is an example of finally keyword with try-except clauses:

Code
. # Python code to show the use of finally clause
.
. # Raising an exception in try block
. try:
. div = 4 // 0
. print( div )
. # this block will handle the exception raised
. except ZeroDivisionError:
. print( "Atepting to divide by zero" )
. # this will always be executed no matter exception is raised or not
. finally:
. print( 'This is code of finally clause' )
Output:

Atepting to divide by zero


This is code of finally clause
User-Defined Exceptions
By inheriting classes from the typical built-in exceptions, Python also lets us design our customized
exceptions.

Here is an illustration of a RuntimeError. In this case, a class that derives from RuntimeError is produced.
Once an exception is detected, we can use this to display additional detailed information.

We raise a user-defined exception in the try block and then handle the exception in the except block. An
example of the class EmptyError is created using the variable var.

Code
. class EmptyError( RuntimeError ):
. def __init__(self, argument):
. self.arguments = argument
. Once the preceding class has been created, the following is how to raise an exception:
. Code
. var = " "
. try:

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


. raise EmptyError( "The variable is empty" )
. except (EmptyError, var):
. print( var.arguments )
Output:

2 try:
----> 3 raise EmptyError( "The variable is empty" )
4 except (EmptyError, var):

EmptyError: The variable is empty

Python Exceptions List


Here is the complete list of Python in-built exceptions.

Sr.No. Name of the Exception Description of the Exception

All exceptions of Python have a base


1 Exception
class.

If the next() method returns null for an


2 StopIteration
iterator, this exception is raised.

3 SystemExit The sys.exit() procedure raises this value.

Excluding the StopIteration and


4 StandardError SystemExit, this is the base class for all
Python built-in exceptions.

All mathematical computation errors


5 ArithmeticError
belong to this base class.

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


This exception is raised when a
6 OverflowError computation surpasses the numeric data
type's maximum limit.

If a floating-point operation fails, this


7 FloatingPointError
exception is raised.

For all numeric data types, its value is


8 ZeroDivisionError raised whenever a number is attempted to
be divided by zero.

If the Assert statement fails, this exception


9 AssertionError
is raised.

This exception is raised if a variable


10 AttributeError
reference or assigning a value fails.

When the endpoint of the file is


approached, and the interpreter didn't get
11 EOFError
any input value by raw_input() or input()
functions, this exception is raised.

This exception is raised if using the import


12 ImportError
keyword to import a module fails.

If the user interrupts the execution of a


13 KeyboardInterrupt program, generally by hitting Ctrl+C, this
exception is raised.

LookupErrorBase is the base class for all


14 LookupError
search errors.

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


This exception is raised when the index
15 IndexError
attempted to be accessed is not found.

When the given key is not found in the


16 KeyError dictionary to be found in, this exception is
raised.

This exception is raised when a variable


17 NameError isn't located in either local or global
namespace.

This exception is raised when we try to


access a local variable inside a function,
18 UnboundLocalError
and the variable has not been assigned any
value.

All exceptions that arise beyond the


19 EnvironmentError
Python environment have this base class.

If an input or output action fails, like when


using the print command or the open()
20 IOError
function to access a file that does not
exist, this exception is raised.

This exception is raised whenever a syntax


22 SyntaxError
error occurs in our program.

This exception was raised when we made


23 IndentationError
an improper indentation.

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


This exception is raised when the
sys.exit() method is used to terminate the
24 SystemExit
Python interpreter. The parser exits if the
situation is not addressed within the code.

This exception is raised whenever a data


25 TypeError type-incompatible action or function is
tried to be executed.

This exception is raised if the parameters


for a built-in method for a particular data
26 ValueError
type are of the correct type but have been
given the wrong values.

This exception is raised when an error that


27 RuntimeError occurred during the program's execution
cannot be classified.

If an abstract function that the user must


28 NotImplementedError define in an inherited class is not defined,
this exception is raised.

Python Date and time


Python provides the datetime module work with real dates and times. In real-world applications, we need
to work with the date and time. Python enables us to schedule our Python script to run at a particular
timing.

In Python, the date is not a data type, but we can work with the date objects by importing the module
named with datetime, time, and calendar.

In this section of the tutorial, we will discuss how to work with the date and time objects in Python.

The datetime classes are classified in the six main classes.

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


o date - It is a naive ideal date. It consists of the year, month, and day as attributes.
o time - It is a perfect time, assuming every day has precisely 24*60*60 seconds. It has hour,
minute, second, microsecond, and tzinfo as attributes.
o datetime - It is a grouping of date and time, along with the attributes year, month, day, hour,
minute, second, microsecond, and tzinfo.
o timedelta - It represents the difference between two dates, time or datetime instances to
microsecond resolution.
o tzinfo - It provides time zone information objects.
o timezone - It is included in the new version of Python. It is the class that implements
the tzinfo abstract base class.

Python Regex - RegEx Functions | Metacharacters | Special Sequences


A regular expression is a set of characters with highly specialized syntax that we can use to find or match
other characters or groups of characters. In short, regular expressions, or Regex, are widely used in the
UNIX world.

Import the re Module

. # Importing re module
. import re
The re-module in Python gives full support for regular expressions of Pearl style. The re module raises
the re.error exception whenever an error occurs while implementing or using a regular expression.

We'll go over crucial functions utilized to deal with regular expressions.

But first, a minor point: many letters have a particular meaning when utilized in a regular
expression called metacharacters.

The majority of symbols and characters will easily match. (A case-insensitive feature can be enabled,
allowing this RE to match Python or PYTHON.) For example, the regular expression 'check' will match
exactly the string 'check'.

There are some exceptions to this general rule; certain symbols are special metacharacters that don't
match. Rather, they indicate that they must compare something unusual or have an effect on other parts
of the RE by recurring or modifying their meaning.

Metacharacters or Special Characters

As the name suggests, there are some characters with special meanings:

Characters Meaning

Dot - It matches any characters except the


.
newline character.

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


Caret - It is used to match the pattern from the
^
start of the string. (Starts With)

Dollar - It matches the end of the string before


$
the new line character. (Ends with)

Asterisk - It matches zero or more


*
occurrences of a pattern.

Plus - It is used when we want a pattern to


+
match at least one.

Question mark - It matches zero or one


?
occurrence of a pattern.

Curly Braces - It matches the exactly


{}
specified number of occurrences of a pattern

[] Bracket - It defines the set of characters

| Pipe - It matches any of two defined patterns.

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


UNIT-IV

Python OOPs Concepts


Like other general-purpose programming languages, Python is also an object-oriented language since its
beginning. It allows us to develop applications using an Object-Oriented approach. In Python, we can
easily create and use classes and objects.

An object-oriented paradigm is to design the program using classes and objects. The object is related to
real-word entities such as book, house, pencil, etc. The oops concept focuses on writing the reusable code.
It is a widespread technique to solve the problem by creating objects.

Major principles of object-oriented programming system are given below.

o Class
o Object
o Method
o Inheritance
o Polymorphism
o Data Abstraction
o Encapsulation

Class

The class can be defined as a collection of objects. It is a logical entity that has some specific attributes
and methods. For example: if you have an employee class, then it should contain an attribute and method,
i.e. an email id, name, age, salary, etc.

Syntax

. class ClassName:
. <statement-1>
. .
. .
. <statement-N>
Object
The object is an entity that has state and behavior. It may be any real-world object like the mouse,
keyboard, chair, table, pen, etc.

Everything in Python is an object, and almost everything has attributes and methods. All functions have a
built-in attribute __doc__, which returns the docstring defined in the function source code.

When we define a class, it needs to create an object to allocate the memory. Consider the following
example.

Example:

. class car:
. def __init__(self,modelname, year):

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


. self.modelname = modelname
. self.year = year
. def display(self):
. print(self.modelname,self.year)
.
. c1 = car("Toyota", 2016)
. c1.display()
Output:

Toyota 2016
In the above example, we have created the class named car, and it has two attributes modelname and year.
We have created a c1 object to access the class attribute. The c1 object will allocate memory for these
values. We will learn more about class and object in the next tutorial.

Method
The method is a function that is associated with an object. In Python, a method is not unique to class
instances. Any object type can have methods.

Inheritance
Inheritance is the most important aspect of object-oriented programming, which simulates the real-world
concept of inheritance. It specifies that the child object acquires all the properties and behaviors of the
parent object.

By using inheritance, we can create a class which uses all the properties and behavior of another class.
The new class is known as a derived class or child class, and the one whose properties are acquired is
known as a base class or parent class.

It provides the re-usability of the code.

Polymorphism
Polymorphism contains two words "poly" and "morphs". Poly means many, and morph means shape. By
polymorphism, we understand that one task can be performed in different ways. For example - you have
a class animal, and all animals speak. But they speak differently. Here, the "speak" behavior is
polymorphic in a sense and depends on the animal. So, the abstract "animal" concept does not actually
"speak", but specific animals (like dogs and cats) have a concrete implementation of the action "speak".

Encapsulation
Encapsulation is also an essential aspect of object-oriented programming. It is used to restrict access to
methods and variables. In encapsulation, code and data are wrapped together within a single unit from
being modified by accident.

Data Abstraction
Data abstraction and encapsulation both are often used as synonyms. Both are nearly synonyms because
data abstraction is achieved through encapsulation.

Abstraction is used to hide internal details and show only functionalities. Abstracting something means to
give names to things so that the name captures the core of what a function or a whole program does.

Object-oriented vs. Procedure-oriented Programming languages

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


The difference between object-oriented and procedure-oriented programming is given below:

Index Object-oriented Procedural Programming


Programming

Object-oriented programming is
Procedural programming uses a
the problem-solving approach
1. list of instructions to do
and used where computation is
computation step by step.
done by using objects.

In procedural programming, It
It makes the development and is not easy to maintain the
2.
maintenance easier. codes when the project
becomes lengthy.

It simulates the real world It doesn't simulate the real


entity. So real-world problems world. It works on step by step
3.
can be easily solved through instructions divided into small
oops. parts called functions.

It provides data hiding. So it is


Procedural language doesn't
more secure than procedural
4. provide any proper way for data
languages. You cannot access
binding, so it is less secure.
private data from anywhere.

Example of object-oriented Example of procedural


5. programming languages is C++, languages are: C, Fortran,
Java, .Net, Python, C#, etc. Pascal, VB etc.

Python Objects Classes


Python is an object-oriented programming language that offers classes, which are a potent tool for
writing reusable code. To describe objects with shared characteristics and behaviours, classes are utilised.
We shall examine Python's ideas of classes and objects in this article.

Classes in Python:

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


In Python, a class is a user-defined data type that contains both the data itself and the methods that may
be used to manipulate it. In a sense, classes serve as a template to create objects. They provide the
characteristics and operations that the objects will employ.

Suppose a class is a prototype of a building. A building contains all the details about the floor, rooms,
doors, windows, etc. we can make as many buildings as we want, based on these details. Hence, the
building can be seen as a class, and we can create as many objects of this class.

Creating Classes in Python


In Python, a class can be created by using the keyword class, followed by the class name. The syntax to
create a class is given below.

Syntax

. class ClassName:
. #statement_suite
In Python, we must notice that each class is associated with a documentation string which can be
accessed by using <class-name>.__doc__. A class contains a statement suite including fields,
constructor, function, etc. definition.

Python Constructor
A constructor is a special type of method (function) which is used to initialize the instance members of
the class.

In C++ or Java, the constructor has the same name as its class, but it treats constructor differently in
Python. It is used to create an object.

Constructors can be of two types.

1. Parameterized Constructor
2. Non-parameterized Constructor

Constructor definition is executed when we create the object of this class. Constructors also verify that
there are enough resources for the object to perform any start-up task.

Creating the constructor in python


In Python, the method the __init__() simulates the constructor of the class. This method is called when
the class is instantiated. It accepts the self-keyword as a first argument which allows accessing the
attributes or method of the class.

We can pass any number of arguments at the time of creating the class object, depending upon
the __init__() definition. It is mostly used to initialize the class attributes. Every class must have a
constructor, even if it simply relies on the default constructor.

Consider the following example to initialize the Employee class attributes.

Example

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


. class Employee:
. def __init__(self, name, id):
. self.id = id
. self.name = name
.
. def display(self):
. print("ID: %d \nName: %s" % (self.id, self.name))
.
.
. emp1 = Employee("John", 101)
. emp2 = Employee("David", 102)
.
. # accessing display() method to print employee 1 information
.
. emp1.display()
.
. # accessing display() method to print employee 2 information
. emp2.display()
Output:

ID: 101
Name: John
ID: 102
Name: David
Python Inheritance
Inheritance is an important aspect of the object-oriented paradigm. Inheritance provides code reusability
to the program because we can use an existing class to create a new class instead of creating it from
scratch.

In inheritance, the child class acquires the properties and can access all the data members and functions
defined in the parent class. A child class can also provide its specific implementation to the functions of
the parent class. In this section of the tutorial, we will discuss inheritance in detail.

In python, a derived class can inherit base class by just mentioning the base in the bracket after the
derived class name. Consider the following syntax to inherit a base class into the derived class.

Syntax
. class derived-class(base class):
. <class-suite>
A class can inherit multiple classes by mentioning all of them inside the bracket. Consider the following
syntax.

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


Syntax

. class derive-class(<base class 1>, <base class 2>, ..... <base class n>):
. <class - suite>

Example 1

. class Animal:
. def speak(self):
. print("Animal Speaking")
. #child class Dog inherits the base class Animal
. class Dog(Animal):
. def bark(self):
. print("dog barking")
. d = Dog()
. d.bark()
. d.speak()
Output:

dog barking
Animal Speaking

Python Multi-Level inheritance

Multi-Level inheritance is possible in python like other object-oriented languages. Multi-level inheritance
is archived when a derived class inherits another derived class. There is no limit on the number of levels
up to which, the multi-level inheritance is archived in python.

The syntax of multi-level inheritance is given below.

Syntax
. class class1:
. <class-suite>
. class class2(class1):
. <class suite>
. class class3(class2):
. <class suite>

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


Example

. class Animal:
. def speak(self):
. print("Animal Speaking")
. #The child class Dog inherits the base class Animal
. class Dog(Animal):
. def bark(self):
. print("dog barking")
. #The child class Dogchild inherits another child class Dog
. class DogChild(Dog):
. def eat(self):
. print("Eating bread...")
. d = DogChild()
. d.bark()
. d.speak()
. d.eat()
Output:

dog barking
Animal Speaking
Eating bread...

Python Multiple inheritance

Python provides us the flexibility to inherit multiple base classes in the child class.

The syntax to perform multiple inheritance is given below.

Syntax

. class Base1:
. <class-suite>
.
. class Base2:
. <class-suite>
. .
. class BaseN:
. <class-suite>
.

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


. class Derived(Base1, Base2, ...... BaseN):
. <class-suite>

Example

. class Calculation1:
. def Summation(self,a,b):
. return a+b;
. class Calculation2:
. def Multiplication(self,a,b):
. return a*b;
. class Derived(Calculation1,Calculation2):
. def Divide(self,a,b):
. return a/b;
. d = Derived()
. print(d.Summation(10,20))
. print(d.Multiplication(10,20))
. print(d.Divide(10,20))
Output:

30
200
0.5
Abstraction in Python
Abstraction is used to hide the internal functionality of the function from the users. The users only
interact with the basic implementation of the function, but inner working is hidden. User is familiar with
that "what function does" but they don't know "how it does."

In simple words, we all use the smartphone and very much familiar with its functions such as camera,
voice-recorder, call-dialing, etc., but we don't know how these operations are happening in the
background. Let's take another example - When we use the TV remote to increase the volume. We don't
know how pressing a key increases the volume of the TV. We only know to press the "+" button to
increase the volume.

That is exactly the abstraction that works in the object-oriented concept.

Why Abstraction is Important?


In Python, an abstraction is used to hide the irrelevant data/class in order to reduce the complexity. It also
enhances the application efficiency. Next, we will learn how we can achieve abstraction using the Python
program.

Abstraction classes in Python


In Python, abstraction can be achieved by using abstract classes and interfaces.

A class that consists of one or more abstract method is called the abstract class. Abstract methods do not
contain their implementation. Abstract class can be inherited by the subclass and abstract method gets its
definition in the subclass. Abstraction classes are meant to be the blueprint of the other class. An abstract
class can be useful when we are designing large functions. An abstract class is also helpful to provide the
standard interface for different implementations of components. Python provides the abc module to use
the abstraction in the Python program. Let's see the following syntax.

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


Syntax

. from abc import ABC


. class ClassName(ABC):
We import the ABC class from the abc module.

Abstract Base Classes


An abstract base class is the common application program of the interface for a set of subclasses. It can
be used by the third-party, which will provide the implementations such as with plugins. It is also
beneficial when we work with the large code-base hard to remember all the classes.

Abstract Base Classes


An abstract base class is the common application program of the interface for a set of subclasses. It can
be used by the third-party, which will provide the implementations such as with plugins. It is also
beneficial when we work with the large code-base hard to remember all the classes.

Python File Handling


Introduction:

In this tutorial, we are discussing Python file handling. Python supports the file-handling process. Till
now, we were taking the input from the console and writing it back to the console to interact with the user.
Users can easily handle the files, like read and write the files in Python. In another programming
language, the file-handling process is lengthy and complicated. But we know Python is an easy
programming language. So, like other things, file handling is also effortless and short in Python.

Sometimes, it is not enough to only display the data on the console. The data to be displayed may be very
large, and only a limited amount of data can be displayed on the console since the memory is volatile, it
is impossible to recover the programmatically generated data again and again.

The file handling plays an important role when the data needs to be stored permanently into the file. A
file is a named location on disk to store related information. We can access the stored information (non-
volatile) after the program termination.

In Python, files are treated in two modes as text or binary. The file may be in the text or binary format,
and each line of a file is ended with the special character like a comma (,) or a newline character. Python
executes the code line by line. So, it works in one line and then asks the interpreter to start the new line
again. This is a continuous process in Python.

Hence, a file operation can be done in the following order.

o Open a file
o Read or write - Performing operation
o Close the file

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


PYTHON MYSQL

UNIT-V
Environment Setup
To build the real world applications, connecting with the databases is the necessity for the programming
languages. However, python allows us to connect our application to the databases like MySQL, SQLite,
MongoDB, and many others.

MySQL connectivity, and we will perform the database operations in python.

Install mysql.connector
To connect the python application with the MySQL database, we must import the mysql.connector
module in the program.

The mysql.connector is not a built-in module that comes with the python installation. We need to install it
to get it working.

. p install mysql-connector
Or follow the following steps.

1. Click the link:


https://files.pythonhosted.org/packages/8f/6d/fb8ebcbbaee68b172ce3dfd08c7b8660d09f91d8d5411298bc
acbd309f96/mysql-connector-python-8.0.13.tar.gz to download the source code.

2. Extract the archived file.


3. Open the terminal (CMD for windows) and change the present working directory to the source code
directory.

. $ cd mysql-connector-python-8.0.13/
4. Run the file named setup.py with python (python3 in case you have also installed python 2) with the
parameter build.

. $ python setup.py build


5. Run the following command to install the mysql-connector.

. $ python setup.py install


This will take a bit of time to install mysql-connector for python. We can verify the installation once the
process gets over by importing mysql-connector on the python shell.

Database Connection
In this section of the tutorial, we will discuss the steps to connect the python application to the database.

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


There are the following steps to connect a python application to our database.

1. Import mysql.connector module


2. Create the connection object.
3. Create the cursor object
4. Execute the query

Creating the connection


To create a connection between the MySQL database and the python application, the connect() method of
mysql.connector module is used.

Pass the database details like HostName, username, and the database password in the method call. The
method returns the connection object.

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

. Connection-Object= mysql.connector.connect(host = <host-


name> , user = <username> , passwd = <password> )
Consider the following example.

Example

. import mysql.connector
.
. #Create the connection object
. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google")
.
. #printing the connection object
. print(myconn)
Output:

<mysql.connector.connection.MySQLConnection object at 0x7fb142edd780>


Here, we must notice that we can specify the database name in the connect() method if we want to
connect to a specific database.

Example

. import mysql.connector
.
. #Create the connection object
. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google", databas
e = "mydb")
.
. #printing the connection object
. print(myconn)
Output:

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


<mysql.connector.connection.MySQLConnection object at 0x7ff64aa3d7b8>

Creating a cursor object


The cursor object can be defined as an abstraction specified in the Python DB-API 2.0. It facilitates us to
have multiple separate working environments through the same connection to the database. We can
create the cursor object by calling the 'cursor' function of the connection object. The cursor object is an
important aspect of executing queries to the databases.

The syntax to create the cursor object is given below.

. <my_cur> = conn.cursor()

Example

. import mysql.connector
. #Create the connection object
. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google", databas
e = "mydb")
.
. #printing the connection object
. print(myconn)
.
. #creating the cursor object
. cur = myconn.cursor()
.
. print(cur)
Output:

<mysql.connector.connection.MySQLConnection object at 0x7faa17a15748>


MySQLCursor: (Nothing executed yet)

Creating new databases

Getting the list of existing databases

We can get the list of all the databases by using the following MySQL query.

. > show databases;

Example

. import mysql.connector
.
. #Create the connection object
. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google")
.
. #creating the cursor object

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


. cur = myconn.cursor()
.
. try:
. dbs = cur.execute("show databases")
. except:
. myconn.rollback()
. for x in cur:
. print(x)
. myconn.close()
Output:

('EmployeeDB',)
('Test',)
('TestDB',)
('information_schema',)
('javatpoint',)
('javatpoint1',)
('mydb',)
('mysql',)
('performance_schema',)
('testDB',)

Creating the new database

The new database can be created by using the following SQL query.

. > create database <database-name>

Example

. import mysql.connector
.
. #Create the connection object
. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google")
.
. #creating the cursor object
. cur = myconn.cursor()
.
. try:
. #creating a new database
. cur.execute("create database PythonDB2")
.
. #getting the list of all the databases which will now include the new database PythonDB
. dbs = cur.execute("show databases")
.
. except:
. myconn.rollback()
.
. for x in cur:

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


. print(x)
.
. myconn.close()
Output:

('EmployeeDB',)
('PythonDB',)
('Test',)
('TestDB',)
('anshika',)
('information_schema',)
('javatpoint',)
('javatpoint1',)
('mydb',)
('mydb1',)
('mysql',)
('performance_schema',)
('testDB',)

Creating the table


In this section of the tutorial, we will create the new table Employee. We have to mention the database
name while establishing the connection object.

We can create the new table by using the CREATE TABLE statement of SQL. In our database
PythonDB, the table Employee will have the four columns, i.e., name, id, salary, and department_id
initially.

The following query is used to create the new table Employee.

. > create table Employee (name varchar(20) not null, id int primary key, salary float not null, De
pt_Id int not null)

Example

. import mysql.connector
.
. #Create the connection object
. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database
= "PythonDB")
.
. #creating the cursor object
. cur = myconn.cursor()
.
. try:
. #Creating a table with name Employee having four columns i.e., name, id, salary, and departm
ent id

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


. dbs = cur.execute("create table Employee(name varchar(20) not null, id int(20) not null primar
y key, salary float not null, Dept_id int not null)")
. except:
. myconn.rollback()
.
. myconn.close()

Now, we may check that the table Employee is present in the database.

Alter Table
Sometimes, we may forget to create some columns, or we may need to update the table schema. The alter
statement used to alter the table schema if required. Here, we will add the column branch_name to the
table Employee. The following SQL query is used for this purpose.

. alter table Employee add branch_name varchar(20) not null


Consider the following example.

Example

. import mysql.connector
.
. #Create the connection object
. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database
= "PythonDB")
.
. #creating the cursor object
. cur = myconn.cursor()
.
. try:
. #adding a column branch name to the table Employee
. cur.execute("alter table Employee add branch_name varchar(20) not null")
. except:
. myconn.rollback()
.
. myconn.close()

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


Insert Operation
Adding a record to the table
The INSERT INTO statement is used to add a record to the table. In python, we can mention the format
specifier (%s) in place of values.

We provide the actual values in the form of tuple in the execute() method of the cursor.

Consider the following example.

Example

. import mysql.connector
. #Create the connection object
. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database
= "PythonDB")
. #creating the cursor object
. cur = myconn.cursor()
. sql = "insert into Employee(name, id, salary, dept_id, branch_name) values (%s, %s, %s, %s, %s
)"
.
. #The row values are provided in the form of tuple
. val = ("John", 110, 25000.00, 201, "Newyork")
.
. try:
. #inserting the values into the table
. cur.execute(sql,val)
.
. #commit the transaction
. myconn.commit()
.
. except:
. myconn.rollback()
.
. print(cur.rowcount,"record inserted!")
. myconn.close()
Output:

1 record inserted!

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


Insert multiple rows
We can also insert multiple rows at once using the python script. The multiple rows are mentioned as the
list of various tuples.

Each element of the list is treated as one particular row, whereas each element of the tuple is treated as
one particular column value (attribute).

Consider the following example.

Example

. import mysql.connector
.
. #Create the connection object
. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database
= "PythonDB")
.
. #creating the cursor object
. cur = myconn.cursor()
. sql = "insert into Employee(name, id, salary, dept_id, branch_name) values (%s, %s, %s, %s, %s
)"
. val = [("John", 102, 25000.00, 201, "Newyork"),("David",103,25000.00,202,"Port of spain"),("N
ick",104,90000.00,201,"Newyork")]
.
. try:
. #inserting the values into the table
. cur.executemany(sql,val)
.
. #commit the transaction
. myconn.commit()
. print(cur.rowcount,"records inserted!")
.
. except:
. myconn.rollback()
.
. myconn.close()
Output:

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


3 records inserted!

Row ID

In SQL, a particular row is represented by an insertion id which is known as row id. We can get the last
inserted row id by using the attribute lastrowid of the cursor object.

Consider the following example.

Example

. import mysql.connector
. #Create the connection object
. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database
= "PythonDB")
. #creating the cursor object
. cur = myconn.cursor()
.
. sql = "insert into Employee(name, id, salary, dept_id, branch_name) values (%s, %s, %s, %s, %s
)"
.
. val = ("Mike",105,28000,202,"Guyana")
.
. try:
. #inserting the values into the table
. cur.execute(sql,val)
.
. #commit the transaction
. myconn.commit()
.
. #getting rowid
. print(cur.rowcount,"record inserted! id:",cur.lastrowid)
.
. except:
. myconn.rollback()
.

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


. myconn.close()
Output:

1 record inserted! Id: 0


Read Operation
The SELECT statement is used to read the values from the databases. We can restrict the output of a
select query by using various clause in SQL like where, limit, etc.

Python provides the fetchall() method returns the data stored inside the table in the form of rows. We can
iterate the result to get the individual rows.

In this section of the tutorial, we will extract the data from the database by using the python script. We
will also format the output to print it on the console.

Example

. import mysql.connector
.
. #Create the connection object
. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database
= "PythonDB")
.
. #creating the cursor object
. cur = myconn.cursor()
.
. try:
. #Reading the Employee data
. cur.execute("select * from Employee")
.
. #fetching the rows from the cursor object
. result = cur.fetchall()
. #printing the result
.
. for x in result:
. print(x);
. except:
. myconn.rollback()
.
. myconn.close()
Output:

('John', 101, 25000.0, 201, 'Newyork')


('John', 102, 25000.0, 201, 'Newyork')
('David', 103, 25000.0, 202, 'Port of spain')
('Nick', 104, 90000.0, 201, 'Newyork')
('Mike', 105, 28000.0, 202, 'Guyana')

Reading specific columns


We can read the specific columns by mentioning their names instead of using star (*).

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


In the following example, we will read the name, id, and salary from the Employee table and print it on
the console.

Example

. import mysql.connector
. #Create the connection object
. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database
= "PythonDB")
. #creating the cursor object
. cur = myconn.cursor()
. try:
. #Reading the Employee data
. cur.execute("select name, id, salary from Employee")
.
. #fetching the rows from the cursor object
. result = cur.fetchall()
. #printing the result
. for x in result:
. print(x);
. except:
. myconn.rollback()
. myconn.close()
Output:

('John', 101, 25000.0)


('John', 102, 25000.0)
('David', 103, 25000.0)
('Nick', 104, 90000.0)
('Mike', 105, 28000.0)

The fetchone() method


The fetchone() method is used to fetch only one row from the table. The fetchone() method returns the
next row of the result-set.

Consider the following example.

Example

. import mysql.connector
.
. #Create the connection object
. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database
= "PythonDB")
.
. #creating the cursor object
. cur = myconn.cursor()
.
. try:
. #Reading the Employee data

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


. cur.execute("select name, id, salary from Employee")
.
. #fetching the first row from the cursor object
. result = cur.fetchone()
.
. #printing the result
. print(result)
.
. except:
. myconn.rollback()
.
. myconn.close()
Output:

('John', 101, 25000.0)

Formatting the result


We can format the result by iterating over the result produced by the fetchall() or fetchone() method of
cursor object since the result exists as the tuple object which is not readable.

Consider the following example.

Example

. import mysql.connector
.
. #Create the connection object
. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database
= "PythonDB")
.
. #creating the cursor object
. cur = myconn.cursor()
.
. try:
.
. #Reading the Employee data
. cur.execute("select name, id, salary from Employee")
.
. #fetching the rows from the cursor object
. result = cur.fetchall()
.
. print("Name id Salary");
. for row in result:
. print("%s %d %d"%(row[0],row[1],row[2]))
. except:
. myconn.rollback()
.
. myconn.close()
Output:

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


Name id Salary
John 101 25000
John 102 25000
David 103 25000
Nick 104 90000
Mike 105 28000

Using where clause

We can restrict the result produced by the select statement by using the where clause. This will extract
only those columns which satisfy the where condition.

Consider the following example.

Example: printing the names that start with j

. import mysql.connector
.
. #Create the connection object
. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database
= "PythonDB")
.
. #creating the cursor object
. cur = myconn.cursor()
.
. try:
. #Reading the Employee data
. cur.execute("select name, id, salary from Employee where name like 'J%'")
.
. #fetching the rows from the cursor object
. result = cur.fetchall()
.
. print("Name id Salary");
.
. for row in result:
. print("%s %d %d"%(row[0],row[1],row[2]))
. except:
. myconn.rollback()
.
. myconn.close()
Output:

Name id Salary
John 101 25000
John 102 25000

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


Example: printing the names with id = 101, 102, and 103

. import mysql.connector
.
. #Create the connection object
. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database
= "PythonDB")
.
. #creating the cursor object
. cur = myconn.cursor()
.
. try:
. #Reading the Employee data
. cur.execute("select name, id, salary from Employee where id in (101,102,103)")
.
. #fetching the rows from the cursor object
. result = cur.fetchall()
.
. print("Name id Salary");
.
. for row in result:
. print("%s %d %d"%(row[0],row[1],row[2]))
. except:
. myconn.rollback()
.
. myconn.close()
Output:

Name id Salary
John 101 25000
John 102 25000
David 103 2500

Ordering the result


The ORDER BY clause is used to order the result. Consider the following example.

Example

. import mysql.connector
.
. #Create the connection object
. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database
= "PythonDB")
.
. #creating the cursor object
. cur = myconn.cursor()
.
. try:
. #Reading the Employee data

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


. cur.execute("select name, id, salary from Employee order by name")
.
. #fetching the rows from the cursor object
. result = cur.fetchall()
.
. print("Name id Salary");
.
. for row in result:
. print("%s %d %d"%(row[0],row[1],row[2]))
. except:
. myconn.rollback()
.
. myconn.close()
Output:

Name id Salary
David 103 25000
John 101 25000
John 102 25000
Mike 105 28000
Nick 104 90000

Order by DESC
This orders the result in the decreasing order of a particular column.

Example

. import mysql.connector
.
. #Create the connection object
. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database
= "PythonDB")
.
. #creating the cursor object
. cur = myconn.cursor()
.
. try:
. #Reading the Employee data
. cur.execute("select name, id, salary from Employee order by name desc")
.
. #fetching the rows from the cursor object
. result = cur.fetchall()
.
. #printing the result
. print("Name id Salary");
. for row in result:
. print("%s %d %d"%(row[0],row[1],row[2]))
.
. except:

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


. myconn.rollback()
.
. myconn.close()
Output:

Name id Salary
Nick 104 90000
Mike 105 28000
John 101 25000
John 102 25000
David 103 25000
Update Operation
The UPDATE-SET statement is used to update any column inside the table. The following SQL query is
used to update a column.

. > update Employee set name = 'alex' where id = 110


Consider the following example.

Example

. import mysql.connector
.
. #Create the connection object
. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database
= "PythonDB")
.
. #creating the cursor object
. cur = myconn.cursor()
.
. try:
. #updating the name of the employee whose id is 110
. cur.execute("update Employee set name = 'alex' where id = 110")
. myconn.commit()
. except:
.
. myconn.rollback()
.
. myconn.close()

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


Delete Operation
The DELETE FROM statement is used to delete a specific record from the table. Here, we must impose a
condition using WHERE clause otherwise all the records from the table will be removed.

The following SQL query is used to delete the employee detail whose id is 110 from the table.

. > delete from Employee where id = 110


Consider the following example.

Example

. import mysql.connector
.
. #Create the connection object
. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database
= "PythonDB")
.
. #creating the cursor object
. cur = myconn.cursor()
.
. try:
. #Deleting the employee details whose id is 110
. cur.execute("delete from Employee where id = 110")
. myconn.commit()
. except:
.
. myconn.rollback()
.
. myconn.close()

Join Operation
We can combine the columns from two or more tables by using some common column among them by
using the join statement.

We have only one table in our database, let's create one more table Departments with two columns
department_id and department_name.

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


. create table Departments (Dept_id int(20) primary key not null, Dept_Name varchar(20) not null
);

As we have created a new table Departments as shown in the above image. However, we haven't yet
inserted any value inside it.

Let's insert some Departments ids and departments names so that we can map this to our Employee table.

. insert into Departments values (201, "CS");


. insert into Departments values (202, "IT");
Let's look at the values inserted in each of the tables. Consider the following image.

Now, let's create a python script that joins the two tables on the common column, i.e., dept_id.

Example

. import mysql.connector
.
. #Create the connection object
. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database
= "PythonDB")
.
. #creating the cursor object
. cur = myconn.cursor()
.
. try:
. #joining the two tables on departments_id

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


. cur.execute("select Employee.id, Employee.name, Employee.salary, Departments.Dept_id, De
partments.Dept_Name from Departments join Employee on Departments.Dept_id = Employee.Dept_id")

. print("ID Name Salary Dept_Id Dept_Name")


. for row in cur:
. print("%d %s %d %d %s"%(row[0], row[1],row[2],row[3],row[4]))
.
. except:
. myconn.rollback()
.
. myconn.close()
Output:

ID Name Salary Dept_Id Dept_Name


101 John 25000 201 CS
102 John 25000 201 CS
103 David 25000 202 IT
104 Nick 90000 201 CS
105 Mike 28000 202 IT

Right Join
Right join shows all the columns of the right-hand side table as we have two tables in the database
PythonDB, i.e., Departments and Employee. We do not have any Employee in the table who is not
working for any department (Employee for which department id is null). However, to understand the
concept of right join let's create the one.

Execute the following query on the MySQL server.

. insert into Employee(name, id, salary, branch_name) values ("Alex",108,29900,"Mumbai");


This will insert an employee Alex who doesn't work for any department (department id is null).

Now, we have an employee in the Employee table whose department id is not present in the Departments
table. Let's perform the right join on the two tables now.

Example

. import mysql.connector
.
. #Create the connection object
. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database
= "PythonDB")
.
. #creating the cursor object
. cur = myconn.cursor()
.
. try:
. #joining the two tables on departments_id

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


. result = cur.execute("select Employee.id, Employee.name, Employee.salary, Departments.Dep
t_id, Departments.Dept_Name from Departments right join Employee on Departments.Dept_id = Employ
ee.Dept_id")
.
. print("ID Name Salary Dept_Id Dept_Name")
.
. for row in cur:
. print(row[0]," ", row[1]," ",row[2]," ",row[3]," ",row[4])
.
.
. except:
. myconn.rollback()
.
. myconn.close()
Output:

ID Name Salary Dept_Id Dept_Name


101 John 25000.0 201 CS
102 John 25000.0 201 CS
103 David 25000.0 202 IT
104 Nick 90000.0 201 CS
105 Mike 28000.0 202 IT
108 Alex 29900.0 None None
Left Join
The left join covers all the data from the left-hand side table. It has just opposite effect to the right join.
Consider the following example.

Example

. import mysql.connector
.
. #Create the connection object
. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database
= "PythonDB")
.
. #creating the cursor object
. cur = myconn.cursor()
.
. try:
. #joining the two tables on departments_id
. result = cur.execute("select Employee.id, Employee.name, Employee.salary, Departments.Dep
t_id, Departments.Dept_Name from Departments left join Employee on Departments.Dept_id = Employe
e.Dept_id")
. print("ID Name Salary Dept_Id Dept_Name")
. for row in cur:
. print(row[0]," ", row[1]," ",row[2]," ",row[3]," ",row[4])
.

. except:
. myconn.rollback()

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


.
. myconn.close()
Output:

ID Name Salary Dept_Id Dept_Name


101 John 25000.0 201 CS
102 John 25000.0 201 CS
103 David 25000.0 202 IT
104 Nick 90000.0 201 CS
105 Mike 28000.0 202 IT

Performing Transactions
Transactions ensure the data consistency of the database. We have to make sure that more than one
applications must not modify the records while performing the database operations. The transactions
have the following properties.

1. Atomicity
Either the transaction completes, or nothing happens. If a transaction contains 4 queries then all
these queries must be executed, or none of them must be executed.
2. Consistency
The database must be consistent before the transaction starts and the database must also be
consistent after the transaction is completed.
3. Isolation
Intermediate results of a transaction are not visible outside the current transaction.
4. Durability
Once a transaction was committed, the effects are persistent, even after a system failure.

Python commit() method


Python provides the commit() method which ensures the changes made to

the database consistently take place.

The syntax to use the commit() method is given below.

. conn.commit() #conn is the connection object


All the operations that modify the records of the database do not take place until the commit() is called.

Python rollback() method


The rollback() method is used to revert the changes that are done to the database. This method is useful in
the sense that, if some error occurs during the database operations, we can rollback that transaction to
maintain the database consistency.

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

. Conn.rollback()

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524


Closing the connection
We need to close the database connection once we have done all the operations regarding the database.
Python provides the close() method. The syntax to use the close() method is given below.

. conn.close()
In the following example, we are deleting all the employees who are working for the CS department.

Example

. import mysql.connector
.
. #Create the connection object
. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database
= "PythonDB")
.
. #creating the cursor object
. cur = myconn.cursor()
.
. try:
. cur.execute("delete from Employee where Dept_id = 201")
. myconn.commit()
. print("Deleted !")
. except:
. print("Can't delete !")
. myconn.rollback()
.
. myconn.close()
Output:Deleted !

Website:www.gedutech.net Emailid:[email protected] Contact Number:7416839768 7676886524

You might also like