Unit 1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 31

Ratnesh Kumar Shukla (Computer Science & Engineering)

PYTHON PROGRAMMING (BCC302)

(Unit 1)

I Introduction to Python: Python variables, Python basic Operators, Understanding python blocks.
Python Data Types, Declaring and using Numeric data types: int, float etc. 03

Introduction of Python:
Python is a general-purpose, dynamic, high-level, and interpreted programming language. It supports
Object Oriented programming approach to develop applications. It is simple and easy to learn and
provides lots of high-level data structures.
Python is an easy-to-learn yet powerful and versatile scripting language, which makes it attractive for
Application Development.
With its interpreted nature, Python's syntax and dynamic typing make it an ideal language for
scripting and rapid application development.
Python supports multiple programming patterns, including object-oriented, imperative, and functional
or procedural programming styles.
Python is not intended to work in a particular area, such as web programming. It is a multipurpose
programming language because it can be used with web, enterprise, 3D CAD, etc.
We don't need to use data types to declare variable because it is dynamically typed, so we can write
a=10 to assign an integer value in an integer variable.
Python makes development and debugging fast because no compilation step is included in Python
development, and the edit-test-debug cycle is very fast.
Python has many web-based assets, open-source projects, and a vibrant community. Learning the
language, working together on projects, and contributing to the Python ecosystem are all made very
easy for developers.
Because of its straightforward language framework, Python is easier to understand and write code in.
This makes it a fantastic programming language for novices. Additionally, it assists seasoned
programmers in writing clearer, error-free code.
Python is an open-source, cost-free programming language. It is utilized in several sectors and
disciplines as a result.
In Python, code readability and maintainability are important. As a result, even if the code was
developed by someone else, it is easy to understand and adapt by some other developer.
Python has many third-party libraries that can be used to make its functionality easier. These libraries
cover many domains, for example, web development, scientific computing, data analysis, and more.

Python Cycles:
1. Python‟s programming cycle is dramatically shorter than that of traditional programming cycle.
2. In Python, there are no compile or link steps.
3. Python programs simply import modules at runtime and use the objects they contain. Because of
this, Python programs run immediately after changes are made.
4. In cases where dynamic module reloading can be used, it is even possible to change and reload
parts of a running program without stopping it at all.
5. Python‟s impact on the programming cycle is as follows:

1
Ratnesh Kumar Shukla (Computer Science & Engineering)

Since Python is interpreted, there is a rapid turnaround after program changes. And because Python‟s
parser is embedded in Python-based
systems, it is easy to modify programs at runtime.
Python IDE( Integrated Development Environment):
1. IDE is a software package that consists of several tools for developing and testing the software.
2. An IDE helps the developer by automating the process.
3. IDEs integrate many tools that are designed for SDLC.
4. IDEs were introduced to diminish the coding and typing errors.
5. Some of the Python IDEs are :

a. PyCharm : PyCharm assists the developers to be more productive and provides smart suggestions.
It saves time by taking care of routine tasks, hence increases productivity.
Features of PyCharm :
i. It has smart code navigation, good code editor, a function for quick refactoring.
ii. The integrated activities with PyCharm are profiling, testing, debugging, remote development, and
deployments.
iii. PyCharm supports Python web development frameworks, Angular JS, JavaScript, CSS, HTML
and live editing functions.

b. Spyder : Spyder is widely used for data science works. It is mostly used to create a secure and
scientific environment for Python. Spyder Python uses PyQt (Python plug-in) which a developer can
add as an extension.
Features of Spyder :
i. It has good syntax highlighting and auto code completion
features.
ii. Spyder Python explores and edits variables directly from GUI.
iii. It performs very well in multi-language editor.

c. PyDev : It is an external plug-in for Eclipse and is very popular as Python interpreter.
Features of PyDev :
i. PyDev has strong parameters like refactoring, debugging, type hinting, code analysis, and code
coverage function.
ii. PyDev supports tokens browser, PyLint integration, interactive console, remote debugger, Unittest
integration, etc.

d. IDLE (Integrated Development and Learning Environment): IDLE is a basic IDE mainly used
by beginner level developer.
i. IDLE Python is a cross-platform IDE, hence it increases the flexibility for users.
ii. It is developed only in Python in collaboration with Tkinter GUI toolkit.
iii. The feature of multi-window text editor in IDLE has some great functions like smart indentation,
call tips, Python colorizing, and undo option.

2
Ratnesh Kumar Shukla (Computer Science & Engineering)

e. Visual studio : It enables development for various platforms and has its own marketplace for
extensions.
Features of visual studio :
i. It supports Python coding in visual studio, debugging, and other activities.
ii. It has both paid and free versions in the market with great features.
Python Basic Syntax:
There is no use of curly braces or semicolon in Python programming language. It is English-like
language. But Python uses the indentation to define a block of code. Indentation is nothing but adding
whitespace before the statement when it is needed.

For example -

def func():
statement 1
statement 2
…………………
…………………
statement N
In this example, the statements that are the same level to the right belong to the function. Generally,
we can use four whitespaces to define indentation.
Instead of Semicolon as used in other languages, Python ends its statements with a NewLine
character.
Python is a case-sensitive language, which means that uppercase and lowercase letters are treated
differently. For example, 'name' and 'Name' are two different variables in Python.
In Python, comments can be added using the '#' symbol. Any text written after the '#' symbol is
considered a comment and is ignored by the interpreter. This trick is useful for adding notes to the
code or temporarily disabling a code block. It also helps in understanding the code better by some
other developers.
'If', 'otherwise', 'for', 'while', 'try', 'except', and 'finally' are a few reserved keywords in Python that
cannot be used as variable names. These terms are used in the language for particular reasons and
have fixed meanings. If you use these keywords, your code may include errors, or the interpreter may
reject them as potential new Variables.

Python Features: 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.
Easy to use and Learn: Python has a simple and easy-to-understand syntax, unlike traditional
languages like C, C++, Java, etc., making it easy for beginners to learn.
Expressive Language: It allows programmers to express complex concepts in just a few lines of code
or reduces Developer's Time.
Interpreted Language: Python does not require compilation, allowing rapid development and
testing. It uses Interpreter instead of Compiler.
Object-Oriented Language: It supports object-oriented programming, making writing reusable and
modular code easy.
Open Source Language: Python is open source and free to use, distribute and modify.
Extensible: Python can be extended with modules written in C, C++, or other languages.
Learn Standard Library: Python's standard library contains many modules and functions that can be
used for various tasks, such as string manipulation, web programming, and more.
GUI Programming Support: Python provides several GUI frameworks, such as Tkinter and PyQt,
allowing developers to create desktop applications easily.
Integrated: Python can easily integrate with other languages and technologies, such as C/C++, Java,
and . NET.
Embeddable: Python code can be embedded into other applications as a scripting language.
Dynamic Memory Allocation: Python automatically manages memory allocation, making it easier
for developers to write complex programs without worrying about memory management.

3
Ratnesh Kumar Shukla (Computer Science & Engineering)

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.
Versatility: Python is a universal language in various domains such as web development, machine
learning, data analysis, scientific computing, and more.
Large Community: Python has a vast and active community of developers contributing to its
development and offering support. This makes it easy for beginners to get help and learn from
experienced developers.
Career Opportunities: Python is a highly popular language in the job market. Learning Python can
open up several career opportunities in data science, artificial intelligence, web development, and
more.
High Demand: With the growing demand for automation and digital transformation, the need for
Python developers is rising. Many industries seek skilled Python developers to help build their digital
infrastructure.
Increased Productivity: Python has a simple syntax and powerful libraries that can help developers
write code faster and more efficiently. This can increase productivity and save time for developers
and organizations.
Big Data and Machine Learning: Python has become the go-to language for big data and machine
learning. Python has become popular among data scientists and machine learning engineers with
libraries like NumPy, Pandas, Scikit-learn, TensorFlow, and more.
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.
Desktop Applications: PyQt and Tkinter are useful libraries that can be used in GUI - Graphical User
Interface-based Desktop Applications. There are better languages for this field, but it can be used with
other languages for making Applications.
Console-based Applications: Python is also commonly used to create command-line or console-
based applications because of its ease of use and support for advanced features such as input/output
redirection and piping.
Mobile Applications: While Python is not commonly used for creating mobile applications, it can
still be combined with frameworks like Kivy or BeeWare to create cross-platform mobile
applications.
Software Development: Python is considered one of the best software-making languages. Python is
easily compatible with both from Small Scale to Large Scale software.
Artificial Intelligence: AI is an emerging Technology, and Python is a perfect language for artificial
intelligence and machine learning because of the availability of powerful libraries such as
TensorFlow, Keras, and PyTorch.
Web Applications: Python is commonly used in web development on the backend with frameworks
like Django and Flask and on the front end with tools like JavaScript and HTML.
Enterprise Applications: Python can be used to develop large-scale enterprise applications with
features such as distributed computing, networking, and parallel processing.
3D CAD Applications: Python can be used for 3D computer-aided design (CAD) applications
through libraries such as Blender.
Machine Learning: Python is widely used for machine learning due to its simplicity, ease of use, and
availability of powerful machine learning libraries.
Computer Vision or Image Processing Applications: Python can be used for computer vision and
image processing applications through powerful libraries such as OpenCV and Scikit-image.
Speech Recognition: Python can be used for speech recognition applications through libraries such as
Speech Recognition and PyAudio.
Scientific computing: Libraries like NumPy, SciPy, and Pandas provide advanced numerical
computing capabilities for tasks like data analysis, machine learning, and more.
Education: Python's easy-to-learn syntax and availability of many resources make it an ideal
language for teaching programming to beginners.

4
Ratnesh Kumar Shukla (Computer Science & Engineering)

Testing: Python is used for writing automated tests, providing frameworks like unit tests and pytest
that help write test cases and generate reports.
Gaming: Python has libraries like Pygame, which provide a platform for developing games using
Python.
IoT: Python is used in IoT for developing scripts and applications for devices like Raspberry Pi,
Arduino, and others.
Networking: Python is used in networking for developing scripts and applications for network
automation, monitoring, and management.
DevOps: Python is widely used in DevOps for automation and scripting of infrastructure
management, configuration management, and deployment processes.
Finance: Python has libraries like Pandas, Scikit-learn, and Statsmodels for financial modeling and
analysis.
Audio and Music: Python has libraries like Pyaudio, which is used for audio processing, synthesis,
and analysis, and Music21, which is used for music analysis and generation.
Writing scripts: Python is used for writing utility scripts to automate tasks like file operations, web
scraping, and data processing.
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.

Python History and Versions:


 Python laid its foundation in the late 1980s.
 The implementation of Python was started in December 1989 by Guido Van Rossum at CWI
in Netherland.
 In February 1991, Guido Van Rossum published the code (labeled version 0.9.0) to
alt.sources. In 1994, Python 1.0 was released with new features like lambda, map, filter, and
reduce.
 Python 2.0 added new features such as list comprehensions, garbage collection systems. On
December 3, 2008, Python 3.0 (also called "Py3K") was released. It was designed to rectify
the fundamental flaw of the language. 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.
The following programming languages influence Python:
 ABC language.
 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.

5
Ratnesh Kumar Shukla (Computer Science & Engineering)

A list of Python versions with its released date is given below.

Python Version Released Date

 Python 3.11.5  24 August 2023.


 Python 3.11.4,  6 June 2023.
 Python 3.11.3  5 April 2023.
 Python 3.11.2  8 February 2023.
 Python 3.11.1  6 December 2022.
 Python 3.11.0  24 October 2022.
 Python 3.10.13  24 August 2023.
 Python 3.10.12  6 June 2023.
 Python 3.10.11  5 April 2023.
 Python 3.10.10  8 February 2023.
 Python 3.10.9  6 December 2022.
 Python 3.10.8  8 October 2022.
 Python 3.10.7  6 September 2022.
 Python 3.10.6  8 August 2022.
 Python 3.10.5  6 June 2022.
 Python 3.10.4  24 March 2022.
 Python 3.10.3  16 March 2022.
 Python 3.10.2  14 January 2022.
 Python 3.10.1  6 December 2021.
 Python 3.10.0  4 October 2021.
 Python 3.9.18  24 August 2023.
 Python 3.9.17  6 June 2023.
 Python 3.9.16  6 December 2022.
 Python 3.9.15  11 October 2022.
 Python 3.9.14  6 September 2022.
 Python 3.9.13  17 May 2022.
 Python 3.9.12  24 March 2022.
 Python 3.9.11  16 March 2022.
 Python 3.9.10  14 January 2022.
 Python 3.9.9  15 November 2021.
 Python 3.9.8  05 November 2021.
 Python 3.9.7  30 August 2021.
 Python 3.9.6  28 June 2021.
 Python 3.9.5  3 May 2021.
 Python 3.9.4  4 April 2021.
 Python 3.9.3  2 April 2021.
 Python 3.9.2  19 February 2021.
 Python 3.9.1  8 December 2020.
 Python 3.9.0  5 October 2020.
 Python 3.8.18  24 August 2023.
 Python 3.8.17  6 June 2023.
 Python 3.8.16  6 December 2022.
 Python 3.8.15  11 October 2022.
 Python 3.8.14  6 September 2022.
 Python 3.8.13  16 March 2022.
 Python 3.8.12  30 August 2021.
 Python 3.8.11  28 June 2021.
 Python 3.8.10  3 May 2021.
 Python 3.8.9  2 April 2021.
 Python 3.8.8  19 February 2021.

6
Ratnesh Kumar Shukla (Computer Science & Engineering)

 Python 3.8.7  21 December 2020.


 Python 3.8.6  23 September 2020.
 Python 3.8.5  20 July 2020.
 Python 3.8.4  13 July 2020.
 Python 3.8.3  13 May 2020.
 Python 3.8.2  24 February 2020.
 Python 3.8.1  18 December 2019.
 Python 3.8.0  14 October 2019.
 Python 3.7.17  6 June 2023.
 Python 3.7.16  6 December 2022.
 Python 3.7.15  11 October 2022.
 Python 3.7.14  6 September 2022.
 Python 3.7.13  16 March 2022.
 Python 3.7.12  4 September 2021.
 Python 3.7.11  28 June 2021.
 Python 3.7.10  15 February 2021.
 Python 3.7.9  17 August 2020.
 Python 3.7.8  27 June 2020.
 Python 3.7.7  10 March 2020.
 Python 3.7.6  18 December 2019.
 Python 3.7.5  15 October 2019.
 Python 3.7.4  08 July 2019.
 Python 3.7.3  25 March 2019.
 Python 3.7.2  24 December 2018.
 Python 3.7.1  20 October 2018.
 Python 3.7.0  27 June 2018.
 Python 3.6.15  4 September 2021.
 Python 3.6.14  28 June 2021.
 Python 3.6.13  15 February 2021.
 Python 3.6.12  17 August 2020.
 Python 3.6.11  27 June 2020.
 Python 3.6.10  18 December 2019.
 Python 3.6.9  02 July 2019.
 Python 3.6.8  24 December 2018.
 Python 3.6.7  20 October 2018.
 Python 3.6.6  27 June 2018.
 Python 3.6.5  28 March 2018.
 Python 3.6.4  19 December 2017.
 Python 3.6.3  03 October 2017.
 Python 3.6.2  17 July 2017.
 Python 3.6.1  21 March 2017.
 Python 3.6.0  23 December 2016.
 Python 3.5.10  5 September 2020.
 Python 3.5.8  1 November 2019.
 Python 3.5.7  18 March 2019.
 Python 3.5.6  8 August 2018.
 Python 3.5.5  4 February 2018.
 Python 3.5.4  25 July 2017.
 Python 3.5.3  17 January 2017.
 Python 3.5.2  27 June 2016.
 Python 3.5.1  07 December 2015.
 Python 3.5.0  13 September 2015.
 Python 3.4.10  18 March 2019.
 Python 3.4.9  8 August 2018.

7
Ratnesh Kumar Shukla (Computer Science & Engineering)

 Python 3.4.8  4 February 2018.


 Python 3.4.7  25 July 2017.
 Python 3.4.6  17 January 2017.
 Python 3.4.5  26 June 2016.
 Python 3.4.4  06 December 2015.
 Python 3.4.3  25 February 2015.
 Python 3.4.2  4 October 2014.
 Python 3.4.1  18 May 2014.
 Python 3.4.0  16 March 2014.
 Python 3.3.7  19 September 2017.
 Python 3.3.6  12 October 2014.
 Python 3.3.5  9 March 2014.
 Python 3.3.4  9 February 2014.
 Python 3.3.3  17 November 2013.
 Python 3.3.2  15 May 2013.
 Python 3.3.1  7 April 2013.
 Python 3.3.0  29 September 2012.
 Python 3.2.6  11 October 2014.
 Python 3.2.5  15 May 2013.
 Python 3.2.4  7 April 2013.
 Python 3.2.3  10 April 2012.
 Python 3.2.2  4 September 2011.
 Python 3.2.1  10 July 2011.
 Python 3.2  20 February 2011.
 Python 3.1.5  9 April 2012.
 Python 3.1.4  11 June 2011.
 Python 3.1.3  27 November 2010.
 Python 3.1.2  21 March 2010.
 Python 3.1.1  17 August 2009.
 Python 3.1  27 June 2009.
 Python 3.0.1  13 February 2009.
 Python 3.0  3 December 2008.
 Python 2.7.18  20 April 2020
 Python 2.7.17  19 October 2019
 Python 2.7.16  02 March 2019
 Python 2.7.15  30 April 2018
 Python 2.7.14  16 September 2017
 Python 2.7.13  17 December 2016
 Python 2.7.12  26 June 2016.
 Python 2.7.11  5 December 2015.
 Python 2.7.10  23 May 2015.
 Python 2.7.9  10 December 2014.
 Python 2.7.8  1 July 2014.
 Python 2.7.7  31 May 2014.
 Python 2.7.6  10 November 2013.
 Python 2.7.5  15 May 2013.
 Python 2.7.4  6 April 2013.
 Python 2.7.3  9 April 2012.
 Python 2.7.2  11 June 2011.
 Python 2.7.1  27 November 2010.
 Python 2.7  4 July 2010.
 Python 2.6.9  29 October 2013.
 Python 2.6.8  10 April 2012.
 Python 2.6.7  3 June 2011.

8
Ratnesh Kumar Shukla (Computer Science & Engineering)

 Python 2.6.6  24 August 2010.


 Python 2.6.5  19 March 2010.
 Python 2.6.4  25 October 2009.
 Python 2.6.3  2 October 2009.
 Python 2.6.2  14 April 2009.
 Python 2.6.1  4 December 2008.
 Python 2.6  1 October 2008.
 Python 2.5.4  23 December 2008.
 Python 2.5.3  19 December 2008.
 Python 2.5.2  21 February 2008.
 Python 2.5.1  18 April 2007.
 Python 2.5  19 September 2006.
 Python 2.4.4  18 October 2006.
 Python 2.4.3  29 March 2006.
 Python 2.4.2  28 September 2005.
 Python 2.4.1  30 March 2005.
 Python 2.4  30 November 2004.
 Python 2.3.5  8 February 2005.
 Python 2.3.4  27 May 2004.
 Python 2.3.3  19 December 2003.
 Python 2.3.2  3 October 2003.
 Python 2.3.1  23 September 2003.
 Python 2.3  29 July 2003.
 Python 2.2.3  30 May 2003.
 Python 2.2.2  14 October 2002.
 Python 2.2.1  10 April 2002.
 Python 2.2.1  29 March 2002.
 Python 2.2.2  21 December 2001.
 Python 2.1.3  8 April 2002.
 Python 2.1.2  16 January 2002.
 Python 2.1.1  20 July 2001.
 Python 2.1  15 April 2001.
 Python 2.0.1  22 June 2001.
 Python 2.0  16 October 2000.
 Python 1.6  5 September 2000.
 Python 1.5.2p2  22 March 2000.
 Python 1.5.2p1  6 July 1999.
 Python 1.5.2  30 April 1999.
 Python 1.5.1p1  6 August 1998.
 Python 1.5.1  14 April 1998.
 Python 1.5  17 February 1998.
 Python 1.4  25 October 1996.
Tips to Keep in Mind While Learning Python: 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. In this
section, we will discuss various tips that we should keep in mind while learning Python.
1. Make it Clear Why We Want to Learn: The goal should be clear before learning the Python.
Python is an easy, a vast language as well. It includes numbers of libraries, modules, in-built functions
and data structures. If the goal is unclear then it will be a boring and monotonous journey of learning
Python. Without any clear goal, you perhaps won't make it done.
So, first figure out the motivation behind learning, which can anything be such as knowing something
new, develop projects using Python, switch to Python, etc. Below are the general areas where Python
is widely used. Pick any of them.

9
Ratnesh Kumar Shukla (Computer Science & Engineering)

o Data Analysis and Processing


o Artificial Intelligence
o Games
o Hardware/Sensor/Robots
o Desktop Applications
Choose any one or two areas according to your interest and start the journey towards learning Python.
2. Learn the Basic Syntax: It is the most essential and basic step to learn the syntax of the Python
programming language. We have to learn the basic syntax before dive deeper into learning it. As we
have discussed in our earlier tutorial, Python is easy to learn and has a simple syntax. It doesn't use
semicolon and brackets. Its syntax is like the English language.
So it will take minimum amount of time to learning its syntax. Once we get its syntax properly,
further learning will be easier and quicker getting to work on projects.
3. Write Code by Own: Writing the code is the most effective and robust way to learn Python. First,
try to write code on paper and run in mind (Dry Run) then move to the system. Writing code on paper
will help us get familiar quickly with the syntax and the concept store in the deep memory. While
writing the code, try to use proper functions and suitable variables names.
There are many editors available for Python programming which highlights the syntax related issue
automatically. So we don't need to pay lot of attention of these mistakes.
4. Keep Practicing: The next important step is to do the practice. It needs to implement the Python
concepts through the code. We should be consistence to our daily coding practice.
Consistency is the key of success in any aspect of life not only in programming. Writing code daily
will help to develop muscle memory.
We can do the problem exercise of related concepts or solve at least 2 or 3 problems of Python. It may
seem hard but muscle memory plays large part in programing. It will take us ahead from those who
believe only the reading concept of Python is sufficient.
5. Make Notes as Needed: Creating notes by own is an excellent method to learn the concepts and
syntax of Python. It will establish stability and focus that helps you become a Python developer. Make
brief and concise notes with relevant information and include appropriate examples of the subject
concerned.
6. Discuss Concepts with Other: Coding seems to be solitary activity, but we can enhance our skills
by interacting with the others. We should discuss our doubts to the expert or friends who are learning
Python. This habit will help to get additional information, tips and tricks, and solution of coding
problems. One of the best advantages of Python, it has a great community. Therefore, we can also
learn from passionate Python enthusiasts.
7. Do small Projects: After understanding Python's basic concept, a beginner should try to work on
small projects. It will help to understand Python more deeply and become more component in it.
Theoretical knowledge is not enough to get command over the Python language. These projects can
be anything as long as they teach you something. You can start with the small projects such as
calculator app, a tic-toc-toe game, an alarm clock app, a to-do list, student or customer management
system, etc.
8. Teach Others: There is a famous saying that "If you want to learn something then you should
teach other". It is also true in case of learning Python. Share your information to other students via
creating blog posts, recording videos or taking classes in local training center. It will help us to
enhance the understanding of Python and explore the unseen loopholes in your knowledge. If you
don't want to do all these, join the online forum and post your answers on Python related questions.
9. Explore Libraries and Frameworks: Python consists of vast libraries and various frameworks.
After getting familiar with Python's basic concepts, the next step is to explore the Python libraries.
Libraries are essential to work with the domain specific projects. In the following section, we describe
the brief introduction of the main libraries.
o TensorFlow - It is an artificial intelligence library which allows us to create large scale AI
based projects.
o Django - It is an open source framework that allows us to develop web applications. It is
easy, flexible, and simple to manage.
o Flask - It is also an open source web framework. It is used to develop lightweight web
applications.

10
Ratnesh Kumar Shukla (Computer Science & Engineering)

o Pandas - It is a Python library which is used to perform scientific computations.


o Keras - It is an open source library, which is used to work around the neural network.
There are many libraries in Python. Above, we have mentioned a few of them.
10. Contribute to Open Source: As we know, Python is an open source language that means it is
freely available for everyone. We can also contribute to Python online community to enhance our
knowledge. Contributing to open source projects is the best way to explore own knowledge. We also
receive the feedback, comments or suggestions for work that we submitted. The feedback will enable
the best practices for Python programming and help us to become a good Python developer.
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. The usage of Python as follows.
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.

Python variables: Variable is a name that is used to refer to memory location. Python variable is also
known as an identifier and used to hold value.
In Python, we don't need to specify the type of variable because Python is a infer language and smart
enough to get variable type.
Variable names can be a group of both the letters and digits, but they have to begin with a letter or an
underscore.
It is recommended to use lowercase letters for the variable name. Rahul and rahul both are two
different variables.

Identifier Naming: Variables are the example of identifiers. An Identifier is used to identify the
literals used in the program. The rules to name an identifier are given below.
 The first character of the variable must be an alphabet or underscore ( _ ).
 All the characters except the first character may be an alphabet of lower-case(a-z), upper-case
(A-Z), underscore, or digit (0-9).
 Identifier name must not contain any white-space, or special character (!, @, #, %, ^, &, *).
 Identifier name must not be similar to any keyword defined in the language.
 Identifier names are case sensitive; for example, my name, and MyName is not the same.
 Examples of valid identifiers: a123, _n, n_9, etc.
 Examples of invalid identifiers: 1a, n%4, n 9, etc.
Declaring Variable and Assigning Values: Python does not bind us to declare a variable before
using it in the application. It allows us to create a variable at the required time.
We don't need to declare explicitly variable in Python. When we assign any value to the variable, that
variable is declared automatically.
The equal (=) operator is used to assign value to a variable.
Python Variable Types:
There are two types of variables in Python - Local variable and Global variable. Let's understand the
following variables.
Local Variable: Local variables are the variables that declared inside the function and have scope
within the function. Let's understand the following example.

Example –
# Declaring a function

11
Ratnesh Kumar Shukla (Computer Science & Engineering)

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
Global Variables: Global variables can be used throughout the program, and its scope is in the entire
program. We can use global variables inside or outside the function.
A variable declared outside the function is the global variable by default. Python provides the global
keyword to use global variable inside the function. If we don't use the global keyword, the function
treats it as a local variable. Let's understand the following example.
Example –
# Declare a variable and initialize it
x = 101
# Global variable in function
def mainFunction():
# printing a global variable
global x
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 assign a value to it. Next, we
defined a function and accessed the declared variable using the global keyword inside the function.
Now we can modify its value. Then, we assigned a new string value to the variable x.
Delete a variable: We can delete the variable using the del keyword. The syntax is given below.
Syntax -
del <variable_name>
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):
print(x)

12
Ratnesh Kumar Shukla (Computer Science & Engineering)

NameError: name 'x' is not defined

Maximum Possible Value of an Integer in Python: Unlike the other programming languages,
Python doesn't have long int or float data types. It treats all integer values as an int data type. Here,
the question arises. What is the maximum possible value can hold by the variable in Python? Consider
the following example.
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 see in the above example, we assigned a large integer value to variable x and checked its
type. It printed class <int> not long int. Hence, there is no limitation number by bits and we can
expand to the limit of our memory.
Python doesn't have any special data type to store larger numbers.
Print Single and Multiple Variables in Python: We can print multiple variables within the single
print statement. Below are the example of single and multiple printing values.
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

Python Operators: The operator is a symbol that performs a specific operation between two
operands, according to one definition. 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. Same as other languages, Python also has some operators, and
these are given below –
 Arithmetic operators
 Comparison operators
 Assignment Operators
 Logical Operators
 Bitwise Operators

13
Ratnesh Kumar Shukla (Computer Science & Engineering)

 Membership Operators
 Identity Operators

Arithmetic Operators: Arithmetic operators used between two operands for a particular operation.
There are many arithmetic operators. It includes the exponent (**) operator as well as the + (addition),
- (subtraction), * (multiplication), / (divide), % (reminder), and // (floor division) operators.

Consider the following table for a detailed explanation of arithmetic operators.

Operator Description

+ (Addition) It is used to add two operands. For example, if a = 10, b = 10 => a+b = 20

- (Subtraction) It is used to subtract the second operand from the first operand. If the first
operand is less than the second operand, the value results negative. For
example, if a = 20, b = 5 => a - b = 15

/ (divide) It returns the quotient after dividing the first operand by the second operand.
For example, if a = 20, b = 10 => a/b = 2.0

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

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

** (Exponent) As it calculates the first operand's power to the second operand, it is an


exponent operator.

// (Floor division) It provides the quotient's floor value, which is obtained by dividing the two
operands.

Program Code:
a = 32 # Initialize the value of a
b=6 # Initialize the value of b
print('Addition of two numbers:',a+b)
print('Subtraction of two numbers:',a-b)
print('Multiplication of two numbers:',a*b)
print('Division of two numbers:',a/b)
print('Reminder of two numbers:',a%b)
print('Exponent of two numbers:',a**b)
print('Floor division of two numbers:',a//b)

Output: Now we compile the above code in Python, and after successful compilation, we run it. Then
the output is given below -
Addition of two numbers: 38
Subtraction of two numbers: 26
Multiplication of two numbers: 192
Division of two numbers: 5.333333333333333
Reminder of two numbers: 2
Exponent of two numbers: 1073741824
Floor division of two numbers: 5

14
Ratnesh Kumar Shukla (Computer Science & Engineering)

Comparison operator: Comparison operators mainly use for comparison purposes. Comparison
operators compare the values of the two operands and return a true or false Boolean value in
accordance. The example of comparison operators are ==, !=, <=, >=, >, <. In the below table, we
explain the works of the operators.

Operator Description

== If the value of two operands is equal, then the condition becomes true.

!= If the value of two operands is not equal, then the condition becomes true.

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

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

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

< If the first operand is less than the 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 = 32 # Initialize the value of a


b=6 # Initialize the value of b
print('Two numbers are equal or not:',a==b)
print('Two numbers are not equal or not:',a!=b)
print('a is less than or equal to b:',a<=b)
print('a is greater than or equal to b:',a>=b)
print('a is greater b:',a>b)
print('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 -

Two numbers are equal or not: False


Two numbers are not equal or not: True
a is less than or equal to b: False
a is greater than or equal to b: True
a is greater b: True
a is less than b: False

Assignment Operators: Using the assignment operators, the right expression's value is assigned to
the left operand. There are some examples of assignment operators like =, +=, -=, *=, %=, **=, //=. In
the below table, we explain the works of the operators.

15
Ratnesh Kumar Shukla (Computer Science & Engineering)

Operator Description

= It assigns the value of the right expression to the left operand.

+= By adding the value of the right operand by the value of the left operand, the left
operand receives a changed value. For example, if a = 10, b = 20 => a+ = b will be
equal to a = a+ b and therefore, a = 30.

-= It decreases the value of the left operand by the value of the right operand and assigns
the modified value back to left operand. For example, if a = 20, b = 10 => a- = b will
be equal to a = a- b and therefore, a = 10.

*= It multiplies the value of the left operand by the value of the right operand and assigns
the modified value back to then the left operand. For example, if a = 10, b = 20 => a*
= b will be equal to a = a* b and therefore, a = 200.

%= It divides the value of the left operand by the value of the right operand and assigns
the reminder back to the left operand. For example, if a = 20, b = 10 => a % = b will
be equal to a = a % b and therefore, a = 0.

**= a**=b will be equal to a=a**b, for example, if a = 4, b =2, a**=b will assign 4**2 =
16 to a.

//= A//=b will be equal to a = a// b, for example, if a = 4, b = 3, a//=b will assign 4//3 = 1
to a.

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

a = 32 # Initialize the value of a


b=6 # Initialize the value of 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)
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=b: False
a+=b: 38
a-=b: 26
a*=b: 192
a%=b: 2
a**=b: 1073741824
a//=b: 5

16
Ratnesh Kumar Shukla (Computer Science & Engineering)

Bitwise Operators: The two operands' values are processed bit by bit by the bitwise operators. The
examples of Bitwise operators are 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

In the below table, we are explaining the works of the bitwise operators.

Operator Description

& (binary and) A 1 is copied to the result if both bits in two operands at the same location are 1. If
not, 0 is copied.

| (binary or) The resulting bit will be 0 if both the bits are zero; otherwise, the resulting bit will
be 1.

^ (binary xor) If the two bits are different, the outcome bit will be 1, else it will be 0.

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

<< (left shift) The number of bits in the right operand is multiplied by the leftward shift of the
value of the left operand.

>> (right shift) The left operand is moved 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 -

17
Ratnesh Kumar Shukla (Computer Science & Engineering)

a=5 # initialize the value of a


b=6 # initialize the value of b
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)

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

a&b: 4
a|b: 7
a^b: 3
~a: -6
a<>b: 0

Logical Operators: The assessment of expressions to make decisions typically uses logical operators.
The examples of logical operators are and, or, and not. In the case of logical AND, if the first one is 0,
it does not depend upon the second one. In the case of logical OR, if the first one is 1, it does not
depend on the second one. Python supports the following logical operators. In the below table, we
explain the works of the logical operators.

Operator Description

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

or The condition will be true if one of the phrases is true. If a and b are the two
expressions, then an or b must be true if and is true and b is false.

not If an expression a is true, then not (a) will be false and vice versa.
Program Code: Now we give code examples of arithmetic operators in Python. The code is given
below -
a=5 # initialize the value of a
print(Is this statement true?:',a > 3 and a < 5)
print('Any one statement is true?:',a > 3 or a < 5)
print('Each statement is true then return False and vice-versa:',(not(a > 3 and a < 5)))
Output:
Now we give code examples of Bitwise operators in Python. The code is given below -
Is this statement true?: False
Any one statement is true?: True
Each statement is true then return False and vice-versa: True

Membership Operators: The membership of a value inside a Python data structure can be verified
using Python membership operators. The result is true if the value is in the data structure; otherwise, it
returns false.

18
Ratnesh Kumar Shukla (Computer Science & Engineering)

Operator Description

in If the first operand cannot be found in the second operand, it is


evaluated to be true (list, tuple, or dictionary).

not in If the first operand is not present in the second operand, the
evaluation is true (list, tuple, or dictionary).
Program Code: Now we give code examples of Membership operators in Python. The code is given
below -
x = ["Rose", "Lotus"]
print(' Is value Present?', "Rose" in x)
print(' Is value not Present?', "Riya" not in x)
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the
output is given below -
Is value Present? True
Is value not Present? True
Identity Operators:

Operator Description

is If the references on both sides point to the same object, it is determined to be true.

is not If the references on both sides do 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 -
a = ["Rose", "Lotus"]
b = ["Rose", "Lotus"]
c=a
print(a is c)
print(a is not c)
print(a is b)
print(a is not b)
print(a == b)
print(a != b)
Output:
Now we compile the above code in python, and after successful compilation, we run it. Then the
output is given below -
True
False
False
True
True
False
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.

Operator Description

** Overall other operators employed in the expression, the exponent operator

19
Ratnesh Kumar Shukla (Computer Science & Engineering)

is given precedence.

~+- the minus, unary plus, and negation.

* / % // the division of the floor, the modules, the division, and the multiplication.

+- Binary plus, and minus

>> << Left shift. and right shift

& Binary and.

^| Binary xor, and or

<= < > >= Comparison operators (less than, less than equal to, greater than, greater
then equal to).

<> == != Equality operators.

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


*= **=

is is not Identity operators

in not in Membership operators

not or and Logical operators

Understanding python blocks: In Python, a block is a group of statements that are indented together.
Blocks are used to define the scope of variables and to control the flow of execution.

if condition:
# This is a block of statements
# indented by four spaces

The statements in a block are executed as a unit. This means that if one statement in the block raises an
exception, the remaining statements in the block will not be executed.
Blocks are also used to define the scope of variables. The scope of a variable is the part of the program
where the variable is accessible. The scope of a variable in a block is limited to the block itself. This
means that a variable defined in a block cannot be accessed outside of the block.

Here are some examples of Python blocks:

def my_function():
# This is a block of statements
# indented by four spaces
x = 10
print(x)

20
Ratnesh Kumar Shukla (Computer Science & Engineering)

if condition:
# This is another block of statements
# indented by four spaces
y = 20
print(y)
In the first example, the function my_function() defines a block of statements. The statements in the
block are indented by four spaces. The variable x is defined in the block and is only accessible within
the block.
In the second example, the if statement defines a block of statements. The statements in the block are
indented by four spaces. The variable y is defined in the block and is only accessible within the block.
Here are some of the rules for Python block syntax:
 Blocks must be indented by four spaces.
 Statements in a block must be indented by the same amount of space.
 The scope of a variable in a block is limited to the block itself.
I hope this article helps you understand Python block syntax.
Here are some additional tips for understanding Python block syntax:
 Use a linter to help you indent your code correctly.
 Use a debugger to step through your code and see how blocks are executed.
 Use the help() function to learn more about the Python block syntax.
I hope these tips help you write more readable and maintainable Python code.

Python Data Types: Every value has a data type, 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
4. Set
5. Dictionary

21
Ratnesh Kumar Shukla (Computer Science & Engineering)

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.

22
Ratnesh Kumar Shukla (Computer Science & Engineering)

Sequence Type:
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:
str = "string using double quotes"
print(str)
s = '''''A multiline
string'''
print(s)
Output:
string using double quotes
A multiline
string
Example -
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: 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)

23
Ratnesh Kumar Shukla (Computer Science & Engineering)

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)
# 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.
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])

24
Ratnesh Kumar Shukla (Computer Science & Engineering)

print (d.keys())
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.
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.
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)
Output:
{3, 'Python', 'James', 2}
{'Python', 'James', 3, 2, 10}
{'Python', 'James', 3, 10}

Python Data Types:

Data Types Classes Description

Numeric int, float, complex holds numeric values

25
Ratnesh Kumar Shukla (Computer Science & Engineering)

String str holds sequence of characters

Sequence list, tuple, range holds collection of items

Mapping dict holds data in key-value pair form

Boolean bool holds either True or False

Set set, frozeenset hold collection of unique items

Python Numeric Data type: In Python, numeric data type is used to hold numeric values.
Integers, floating-point numbers and complex numbers fall under Python numbers category. They are
defined as int, float and complex classes in Python.

 int - holds signed integers of non-limited length.

 float - holds floating decimal points and it's accurate up to 15 decimal places.

 complex - holds complex numbers.

We can use the type() function to know which class a variable or a value belongs to.

Example,

num1 = 5
print(num1, 'is of type', type(num1))

num2 = 2.0
print(num2, 'is of type', type(num2))

num3 = 1+2j
print(num3, 'is of type', type(num3))
Run Code

Output

5 is of type <class 'int'>


2.0 is of type <class 'float'>
(1+2j) is of type <class 'complex'>

In the above example, we have created three variables named num1, num2 and num3 with
values 5, 5.0, and 1+2j respectively.
We have also used the type() function to know which class a certain variable belongs to.
Since,
 5 is an integer value, type() returns int as the class of num1 i.e <class 'int'>
 2.0 is a floating value, type() returns float as the class of num2 i.e <class 'float'>
 1 + 2j is a complex number, type() returns complex as the class of num3 i.e <class 'complex'>

Python List Data Type:

26
Ratnesh Kumar Shukla (Computer Science & Engineering)

List is an ordered collection of similar or different types of items separated by commas and enclosed
within brackets [ ]. For example,

languages = ["Swift", "Java", "Python"]

Here, we have created a list named languages with 3 string values inside it.
Access List Items
To access items from a list, we use the index number (0, 1, 2 ...). For example,
languages = ["Swift", "Java", "Python"]

# access element at index 0


print(languages[0]) # Swift

# access element at index 2


print(languages[2]) # Python
Run Code

In the above example, we have used the index values to access items from the languages list.
 languages[0] - access first item from languages i.e. Swift
 languages[2] - access third item from languages i.e. Python
To learn more about lists, visit Python List.
Python Tuple Data Type: Tuple is an ordered sequence of items same as a list. The only difference
is that tuples are immutable. Tuples once created cannot be modified.
In Python, we use the parentheses () to store items of a tuple. For example,

product = ('Xbox', 499.99)

Here, product is a tuple with a string value Xbox and integer value 499.99.

Access Tuple Items:


Similar to lists, we use the index number to access tuple items in Python . For example,
# create a tuple
product = ('Microsoft', 'Xbox', 499.99)

# access element at index 0


print(product[0]) # Microsoft

# access element at index 1


print(product[1]) # Xbox
Run Code

Python String Data Type: String is a sequence of characters represented by either single or double
quotes. For example,
name = 'Python'
print(name)

message = 'Python for beginners'


print(message)
Run Code

27
Ratnesh Kumar Shukla (Computer Science & Engineering)

Output:

Python
Python for beginners

In the above example, we have created string-type variables: name and message with
values 'Python' and 'Python for beginners' respectively.
Python Set Data Type: Set is an unordered collection of unique items. Set is defined by values
separated by commas inside braces { }. For example,
# create a set named student_id
student_id = {112, 114, 116, 118, 115}

# display student_id elements


print(student_id)

# display type of student_id


print(type(student_id))
Run Code

Output:

{112, 114, 115, 116, 118}


<class 'set'>

Here, we have created a set named student_info with 5 integer values.


Since sets are unordered collections, indexing has no meaning. Hence, the slicing operator [] does not
work.
Python Dictionary Data Type: Python dictionary is an ordered collection of items. It stores elements
in key/value pairs.
Here, keys are unique identifiers that are associated with each value.
Let's see an example,
# create a dictionary named capital_city
capital_city = {'Nepal': 'Kathmandu', 'Italy': 'Rome', 'England': 'London'}

print(capital_city)
Run Code

Output:

{'Nepal': 'Kathmandu', 'Italy': 'Rome', 'England': 'London'}

In the above example, we have created a dictionary named capital_city. Here,


1. Keys are 'Nepal', 'Italy', 'England'
2. Values are 'Kathmandu', 'Rome', 'London'
Access Dictionary Values Using Keys: We use keys to retrieve the respective value. But not the
other way around. For example,
# create a dictionary named capital_city
capital_city = {'Nepal': 'Kathmandu', 'Italy': 'Rome', 'England': 'London'}

28
Ratnesh Kumar Shukla (Computer Science & Engineering)

print(capital_city['Nepal']) # prints Kathmandu

print(capital_city['Kathmandu']) # throws error message


Python Type Conversion: In programming, type conversion is the process of converting data of one
type to another. For example: converting int data to str.
There are two types of type conversion in Python.
 Implicit Conversion - automatic type conversion
 Explicit Conversion - manual type conversion
Python Implicit Type Conversion: In certain situations, Python automatically converts one data type
to another. This is known as implicit type conversion.
Example 1: Converting integer to float
Let's see an example where Python promotes the conversion of the lower data type (integer) to the
higher data type (float) to avoid data loss.
integer_number = 123
float_number = 1.23

new_number = integer_number + float_number

# display new value and resulting data type


print("Value:",new_number)
print("Data Type:",type(new_number))
Run Code

Output:

Value: 124.23
Data Type: <class 'float'>

In the above example, we have created two


variables: integer_number and float_number of int and float type respectively.
Then we added these two variables and stored the result in new_number.
As we can see new_number has value 124.23 and is of the float data type.
It is because Python always converts smaller data types to larger data types to avoid the loss of data.
Note:
 We get TypeError, if we try to add str and int. For example, '12' + 23. Python is not able to use
Implicit Conversion in such conditions.
 Python has a solution for these types of situations which is known as Explicit Conversion.
Explicit Type Conversion: In Explicit Type Conversion, users convert the data type of an object to
required data type.
We use the built-in functions like int(), float(), str(), etc to perform explicit type conversion.
This type of conversion is also called typecasting because the user casts (changes) the data type of the
objects.
Example 2: Addition of string and integer Using Explicit Conversion:
num_string = '12'
num_integer = 23

print("Data type of num_string before Type Casting:",type(num_string))

29
Ratnesh Kumar Shukla (Computer Science & Engineering)

# explicit type conversion


num_string = int(num_string)

print("Data type of num_string after Type Casting:",type(num_string))

num_sum = num_integer + num_string

print("Sum:",num_sum)
print("Data type of num_sum:",type(num_sum))
Run Code

Output:

Data type of num_string before Type Casting: <class 'str'>


Data type of num_string after Type Casting: <class 'int'>
Sum: 35
Data type of num_sum: <class 'int'>

In the above example, we have created two


variables: num_string and num_integer with str and int type values respectively. Notice the code,

num_string = int(num_string)

Here, we have used int() to perform explicit type conversion of num_string to integer type.
After converting num_string to an integer value, Python is able to add these two variables.
Finally, we got the num_sum value i.e 35 and data type to be int.

Key Points to Remember:


1. Type Conversion is the conversion of an object from one data type to another data type.
2. Implicit Type Conversion is automatically performed by the Python interpreter.
3. Python avoids the loss of data in Implicit Type Conversion.
4. Explicit Type Conversion is also called Type Casting, the data types of objects are converted using
predefined functions by the user.
5. In Type Casting, loss of data may occur as we enforce the object to a specific data type.

Interpreter: The Python interpreter works as a computer converter that converts high-level language
to low-level machine language, which is essential for the computer to understand the code written by
a programmer. Python codes are executed by an interpreter called CPython, which is written in C
language and executes instructions in a block of code one line after another.
 Lexing
 Parsing
 Creation of byte code
 Conversion to machine-executable code
 Returning output
Step 1: Lexing: The first step of analyzing a code block in Python starts with Lexing, wherein the
single line of code being executed by the interpreter is converted into smaller parts. Each of these
parts is called a token, and these tokens are generated by the lexer, which is a part of the Python

30
Ratnesh Kumar Shukla (Computer Science & Engineering)

interpreter. Essentially, this can be considered to be a step in which the interpreter breaks down the
user instruction into small pieces, to process it piecewise.
Step 2: Parsing: In this step, another component of the Python interpreter called the Parser performs
the process of Parsing. Now essentially, Parsing is a process in which the tokens generated in the
Lexing stage into a structure called Abstract Syntax Tree. This tree shows the relationship between the
tokens generated from a particular line of code. This is where the Python interpreter also checks for
syntax errors, and if an error is found, the interpreter stops translating code and shows an error
message.

Step 3: Creation of Byte Code: After successful completion of the Parsing stage, the compiler
(another part of Python interpreter) converts the Abstract Syntax Tree into an intermediate language
code, called bytecode . This is a compiled version of the original code which is a low-level, platform
independent representation. This byte code is stored in a file with the same name as the original
source file, but with a „.pyc‟ extension instead of „.py‟ . This is a step completely hidden from the
developer which happens internally, and is performed as executing byte code is much faster than
original code statements.

Step 4: Conversion to Machine-executable Code: One of the most integral parts of the Python
interpreter is the Python Virtual Machine, or PVM. It is this part of the compiler which truly executes
a Python program. The PVM is the actual runtime engine of Python, and can be summarized as a big
loop which iterates through the byte code instructions stored in the file with .pyc extension statement
wise. Then it converts the statements into machine code, that is binary (0s and 1s). It also integrates
and loads the inputs and libraries involved in the program, so that the required instructions can be
carried out successfully. The PVM is the part of the interpreter that truly executes Python scripts.

Step 5: Returning Output: After the code is converted to binary, it is executed by the interpreter. If
there is an error, it displays the message and exits. Such an error is called a runtime error. If there is
no runtime error during program execution, then the interpreter prints the output and exits
successfully.

Text books:

1. Wesley J. Chun, “Core Python Applications Programming”, 3rd Edition, Pearson Education, 2016
2. Lambert, Fundamentals of Python: First Programs with MindTap, 2nd 1st edition, Cengage
Learning publication
3. Charles Dierbach, “Introduction to Computer Science using Python”, Wiley, 2015
4. Jeeva Jose & P.Sojan Lal, “Introduction to Computing and Problem Solving with PYTHON”,
Khanna Publishers, New Delhi,
2016
5. Downey, A. et al., “How to think like a Computer Scientist: Learning with Python”, John Wiley,
2015
6. Mark Lutz, “Learning Python”, 5th edition, Orelly Publication, 2013, ISBN 978- 1449355739
7. John Zelle, “Python Programming: An Introduction to Computer Science”, Second edition, Course
Technology Cengage
Learning Publications, 2013, ISBN 978- 1590282410
8. Michel Dawson, “Python Programming for Absolute Beginers”, Third Edition, Course Technology
Cengage Learning
Publications, 2013, ISBN 978-1435455009
9. David Beazley, Brian Jones., “Python Cookbook”, Third Edition, Orelly Publication, 2013, ISBN
978-1449340377.

31

You might also like