[go: up one dir, main page]

0% found this document useful (0 votes)
4 views75 pages

Python Notes - 1 Unit - 240416 - 143609

Python is a versatile programming language widely used in various fields such as web development and machine learning, known for its ease of use and quick programming cycle. It was created by Guido Van Rossum in the late 1980s, with significant versions released over the years, culminating in Python 3.11.2, which boasts improved speed. The document also contrasts compilers and interpreters, detailing their roles, advantages, and disadvantages in code execution.

Uploaded by

akhilverma9580
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)
4 views75 pages

Python Notes - 1 Unit - 240416 - 143609

Python is a versatile programming language widely used in various fields such as web development and machine learning, known for its ease of use and quick programming cycle. It was created by Guido Van Rossum in the late 1980s, with significant versions released over the years, culminating in Python 3.11.2, which boasts improved speed. The document also contrasts compilers and interpreters, detailing their roles, advantages, and disadvantages in code execution.

Uploaded by

akhilverma9580
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/ 75

Python (Unit 1)

 Python
 Python is one of the most popular programming languages available today. It is widely
used in various sectors of business, such as programming, web development, machine
learning, and data science.
 Python is a programming language that lets you work quickly and integrate systems more
efficiently.
 Python’s programming cycle is dramatically shorter than that of traditional programming
cycle. In Python, there are no compile or link steps. Python programs simply import
modules at runtime and use the objects they contain.
 Because of this, Python programs run immediately after changes are made. 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.
 Although it is a general-purpose language, it is used in various areas of applications such
as Machine Learning, Artificial Intelligence, web development, IoT, and more.
 Additionally, Python's support of modules and packages facilitates modular programs
and reuse of code. Python is an open-source community language, so numerous
independent programmers are continually building libraries and functionality for it.

 What is Python?

 Python is a set of instructions that we give in the form of a Programme to our computer
to perform any specific task. It is a Programming language having properties like it is
interpreted, object-oriented and it is high-level too.
 Due to its beginner-friendly syntax, it became a clear choice for beginners to start their
programming journey. The major focus behind creating it is making it easier for
developers to read and understand, also reducing the lines of code.

 History of Python

Python was invented by a Dutch Programmer Guido Van Rossum in the late 1980s. Python's
first version (0.9.0) was released in 1991. Following are the important stages in the history of
Python

 Python 0.9.0
Python's first published version is 0.9. It was released in February 1991. It consisted of
support for core object-oriented programming principles.

 Python 1.0
In January 1994, version 1.0 was released, armed with functional programming tools,
features like support for complex numbers etc.

 Python 2.0
Next major version Python 2.0 was launched in October 2000. Many new features such as
list comprehension, garbage collection and Unicode support were included with it.

Dr. Yusuf Perwej Page 1


 Python 3.0
Python 3.0, a completely revamped version of Python was released in December 2008. The
primary objective of this revamp was to remove a lot of discrepancies that had crept in
Python 2.x versions. Python 3 was backported to Python 2.6. It also included a utility named
as python 2 to 3 to facilitate automatic translation of Python 2 code to Python 3.

As of date, Python 3.11.2 is the current stable version, released in February 2023. One of the
most important features of Python's version 3.11 is the significant improvement in speed.
According to Python's official documentation, this version is faster than the previous version
(3.10) by up to 60%.

 Compiler vs Interpreter

 Compiler

The Compiler is a translator which takes input i.e., High-Level Language, and produces an
output of low-level language i.e. machine or assembly language. The work of a Compiler is to
transform the codes written in the programming language into machine code (format of 0s and
1s) so that computers can understand.

 A compiler is more intelligent than an assembler it checks all kinds of limits, ranges,
errors, etc.
 But its program run time is more and occupies a larger part of memory. It has a slow
speed because a compiler goes through the entire program and then translates the entire
program into machine codes.
Role of a Compiler
For Converting the code written in a high-level language into machine-level language so that
computers can easily understand, we use a compiler. Converts basically convert high-level
language to intermediate assembly language by a compiler and then assembled into machine
code by an assembler.

Advantages of Compiler
 Compiled code runs faster in comparison to Interpreted code.
 Compilers help in improving the security of Applications.
 As Compilers give Debugging tools, which help in fixing errors easily.

Disadvantages of Compiler
 The compiler can catch only syntax errors and some semantic errors.
 Compilation can take more time in the case of bulky code.

 Interpreter

An Interpreter is a program that translates a programming language into a comprehensible


language. The interpreter converts high-level language to an intermediate language. It contains
pre-compiled code, source code, etc.
 It translates only one statement of the program at a time.
 Interpreters, more often than not are smaller than compilers.

Dr. Yusuf Perwej Page 2


Role of an Interpreter
The simple role of an interpreter is to translate the material into a target language. An Interpreter
works line by line on a code. It also converts high-level language to machine language.

Advantages of Interpreter
 Programs written in an Interpreted language are easier to debug.
 Interpreters allow the management of memory automatically, which reduces memory
error risks.
 Interpreted Language is more flexible than a Compiled language.

Disadvantages of Interpreter
 The interpreter can run only the corresponding Interpreted program.
 Interpreted code runs slower in comparison to Compiled code.

 Difference between Compiler and Interpreter

Here are important difference between Compiler and Interpreter:

Basis of
Compiler Interpreter
difference

 Create the program.


 Compile will parse or
analyses all of the language
statements for its
correctness. If incorrect,  Create the Program
throws an error  No linking of files or machine code
Programming
 If no error, the compiler generation
Steps will convert source code to  Source statements executed line by
machine code. line DURING Execution
 It links different code files
into a runnable program
(known as exe)
 Run the Program

The program code is already


translated into machine code. Interpreters are easier to use, especially for
Advantage Thus, it code execution time is beginners.
less.

You can’t change the program


Interpreted programs can run on computers
Disadvantage without going back to the source
that have the corresponding interpreter.
code.

Store machine language as


Machine code Not saving machine code at all.
machine code on the disk

Dr. Yusuf Perwej Page 3


Basis of
Compiler Interpreter
difference

Running time Compiled code run faster Interpreted code run slower

It is based on language translation


Model It is based on Interpretation Method.
linking-loading model.

Generates output program (in the


Do not generate output program. So they
Program form of exe) which can be run
evaluate the source program at every time
generation independently from the original
during execution.
program.

Program execution is separate


Program Execution is a part of
from the compilation. It performed
Execution Interpretation process, so it is performed
only after the entire output
line by line.
program is compiled.

Target program execute


Memory The interpreter exists in the memory during
independently and do not require
requirement interpretation.
the compiler in the memory.

For web environments, where load times


Bounded to the specific target
are important. Due to all the exhaustive
machine and cannot be ported. C
analysis is done, compiles take relatively
Best suited for and C++ are a most popular
larger time to compile even small code that
programming language which uses
may not be run multiple times. In such
compilation model.
cases, interpreters are better.

The compiler sees the entire code


Code upfront. Hence, they perform lots Interpreters see code line by line, and thus
Optimization of optimizations that make code optimizations are not as robust as compilers
run faster

Difficult to implement as
Dynamic Interpreted languages support Dynamic
compilers cannot predict what
Typing Typing
happens at turn time.

It is best suited for the Production It is best suited for the program and
Usage
Environment development environment.

Compiler displays all errors and


The interpreter reads a single statement and
warning at the compilation time.
Error execution shows the error if any. You must correct the
Therefore, you can’t run the
error to interpret next line.
program without fixing errors

Input It takes an entire program It takes a single line of code.

Dr. Yusuf Perwej Page 4


Basis of
Compiler Interpreter
difference

Compliers generates intermediate Interpreter never generate any intermediate


Output
machine code. machine code.

Display all errors after,


Errors Displays all errors of each line one by one.
compilation, all at the same time.

Pertaining
C, C++, C#, Scala, Java all use
Programming PHP, Perl, Ruby uses an interpreter.
complier.
languages

 FAQs

1. Which is better: Interpreter or Compiler?

The Interpreter is useful in the case of debugging, but it is slower and a Compiler goes for full
code, error resolution becomes challenging. Therefore, which one is better, totally depends on
what work has to be performed by the user.

2. Which is faster: Interpreter or Compiler?

Whenever any process is considered, the interpreter is faster than the compiler. But, whenever
any program is already compiled, in that case, execution of the compiled program is faster than
an interpreted program.

3. List the types of Compilers?

Here are some types of Compilers listed below:

1. Cross-Compiler
2. Native Compiler
3. Bootstrap Compiler
4. DEcompiler
5. Source-to-Source Compiler
6. Language Rewriter
7. Bytecode Compiler
8. Just-in-time Compiler

4. List the types of Interpreters?

Here are some types of Interpreters listed below:

1. Bytecode Interpreter
2. Threaded code Interpreter
3. Abstract syntax tree Interpreter
4. Just-in-time compilation

Dr. Yusuf Perwej Page 5


 Python Code Execution
Python’s traditional runtime execution model: Source code you type is translated to byte
code, which is then run by the Python Virtual Machine (PVM). Your code is automatically
compiled, but then it is interpreted.

The program is converted into byte code. Byte code is a fixed set of instructions that represent
arithmetic, comparison, memory operations, etc. It can run on any operating system and
hardware. The byte code instructions are created in the .pyc file. The .pyc file is not explicitly
created as Python handles it internally but it can be viewed with the following command:

-m and py_compile represent module and module name respectively. This module is responsible
to generate .pyc file. The compiler creates a directory named__pycache__where it stores the
first.cpython-38.pyc file.

 Interpreter

The next step involves converting the byte code (.pyc file) into machine code. This step is
necessary as the computer can understand only machine code (binary code). Python Virtual
Machine (PVM) first understands the operating system and processor in the computer and then
converts it into machine code. Further, these machine code instructions are executed by
processor and the results are displayed.

 Execution of Python Program

However, the interpreter inside the PVM translates the program line by line thereby consuming a
lot of time. To overcome this, a compiler known as Just In Time (JIT) is added to PVM. JIT
compiler improves the execution speed of the Python program. This compiler is not used in all
Python environments like CPython which is standard Python software.

 Python Modes
In the Python programming language, there are two ways in which we can run our code:

1. Interactive mode

Dr. Yusuf Perwej Page 6


2. Script mode

 Interactive Mode
 Interactive etymologically means “working simultaneously and creating impact of our work
on the other’s work”. Interactive mode is based on this ideology only. In the interactive
mode as we enter a command and press enter, the very next step we get the output.

 The output of the code in the interactive mode is influenced by the last command we give.
Interactive mode is very convenient for writing very short lines of code.

 In python it is also known as REPL which stands for Read Evaluate Print Loop. Here, the
read function reads the input from the user and stores it in memory. Eval function evaluates
the input to get the desired output. Print function outputs the evaluated result.

 The loop function executes the loop during the execution of the entire program and
terminates when our program ends. This mode is very suitable for beginners in
programming as it helps them evaluate their code line by line and understand the execution
of code well.

 How to run python code in Interactive mode

In order to run our program in the interactive mode, we can use command prompt in windows,
terminal in Linux, and macOS.

Example 1:

To run python in command prompt type “python”. Then simply type the Python statement on
>>> prompt. As we type and press enter, we can see the output in the very next line.

# Python program to display "Hello GFG"

print("Hello GFG")

Output:

Dr. Yusuf Perwej Page 7


Example 2:

Let us take another example in which we need to perform addition on two numbers and we want
to get its output. We will declare two variables a and b and store the result in a third variable c.
We further print c. All this is done in the command prompt.

# Python program to add two numbers


a=2
b=3

# Adding a and b and storing result in c


c=a+b

# Printing value of c
print(c)

Output:

We can see the desired output on the screen. This kind of program is a very short program and
can be easily executed in interactive mode.

Example 3:

In this example, we will multiply two numbers and take the numbers as an input for two users.
You will see that when you execute the input command, you need to give input in the very next
line, i.e. code is interpreted line by line.

# Python program to take input from user

# Taking input from user


a = int(input())

# Taking input from user


b = int(input())

# Multiplying and storing result


c=a*b

Dr. Yusuf Perwej Page 8


# Printing the result
print(c)

Output:

 Advantages of Interactive Mode

The interactive mode is great for testing out commands and getting immediate feedback. It can
also be used to quickly execute commands on a remote server.

 Disadvantages of Interactive Mode

 The main disadvantage of interactive mode is that it can be difficult to automate tasks.
 The interactive mode is not suitable for large programs.
 The interactive mode doesn’t save the statements. Once we make a program it is for that
time itself, we cannot use it in the future. In order to use it in the future, we need to
retype all the statements.
 Editing the code written in interactive mode is a tedious task. We need to revisit all our
previous commands and if still, we could not edit we need to type everything again.

 Script Mode
In the script mode, a python program can be written in a file. This file can then be saved and
executed using the command prompt. We can view the code at any time by opening the file and
editing becomes quite easy as we can open and view the entire code as many times as we want.
Script mode is very suitable for writing long pieces of code. It is much preferred over interactive
mode by experts in the program. The file made in the script mode is by default saved in the
Python installation folder and the extension to save a python file is “.py”.

 How to run python code in script mode?

In order to run a code in script mode follow the following steps.

Step 1: Make a file using a text editor. You can use any text editor of your choice (Here I use
notepad).
Step 2: After writing the code save the file using “.py” extension.
Step 3: Now open the command prompt and command directory to the one where your file is
stored.
Step 4: Type python “filename.py” and press enter.
Step 5: You will see the output on your command prompt.

Dr. Yusuf Perwej Page 9


Example 1:

In order to execute “Hello gfg” using script mode we first make a file and save it.

Now we use the command prompt to execute this file.

Output:

Example 2:

Our second example is the same addition of two numbers as we saw in the interactive mode. But
in this case, we first make a file and write the entire code in that file. We then save it and execute
it using the command prompt.

Output:

Dr. Yusuf Perwej Page 10


Example 3:

In this example, we write the code for multiplying two numbers. And the numbers which are to
be multiplied are taken by the user as an input. In the interactive mode, we saw that as we write
the command so does it asks for the input in the very next line.

But in script mode we first code the entire program saves and then run it in command prompt.
The python interpreter executes the code line by line and gives us the result accordingly.

In this example, we see that the whole program is compiled and the code is executed line by line.
The output on the shell is entirely different from the interactive mode.

 Advantages of Script Mode

Script mode is a great way to automate tasks and run commands on a remote server. Script mode
can also be used to create files that will execute certain commands when they are run. This can
be very helpful in automating tasks or setting up a development environment.

Dr. Yusuf Perwej Page 11


 Disadvantages of Script Mode

There are some disadvantages to using script mode, however.

 First, if something goes wrong with the script, it can be difficult to troubleshoot.
 Second, if you are not familiar with scripting languages, it can be difficult to write a
script that does what you want it to do.
 Finally, scripts can be slow because they have to execute all of their commands serially.

 Difference between Interactive mode and Script mode

Interactive Mode Script Mode


It is a way of executing a Python In the script mode, the Python program is written in a
program in which statements are written file. Python interpreter reads the file and then executes
in command prompt and result is it and provides the desired result. The program is
obtained on the same. compiled in the command prompt,

The interactive mode is more suitable Script mode is more suitable for writing long
for writing very short programs. programs.

Editing of code can be done but it is a


Editing of code can be easily done in script mode.
tedious task.

We get output for every single line of


code in interactive mode i.e. result is In script mode entire program is first compiled and
obtained after execution of each line of then executed.
code.

Code cannot be saved and used in the


Code can be saved and can be used in the future.
future.

It is more preferred by experts than the beginners to


It is more preferred by beginners.
use script mode.

 Features of Python
 Easy to use and Read - Python's syntax is clear and easy to read, making it an ideal language for
both beginners and experienced programmers. This simplicity can lead to faster development and
reduce the chances of errors.
 Dynamically Typed - The data types of variables are determined during run-time. We do not
need to specify the data type of a variable during writing codes.
 Python is Interpreted − Python is processed at runtime by the interpreter. You do not
need to compile your program before executing it. This is similar to PERL and PHP.
 Python is Interactive − You can actually sit at a Python prompt and interact with the
interpreter directly to write your programs.
 Python is Object-Oriented − Python supports Object-Oriented style or technique of
programming that encapsulates code within objects.
 High-level - High-level language means human readable code.
Dr. Yusuf Perwej Page 12
 Compiled and Interpreted - Python code first gets compiled into bytecode, and then interpreted
line by line. When we download the Python in our system form org we download the default
implement of Python known as CPython. CPython is considered to be Complied and Interpreted
both.
 Garbage Collected - Memory allocation and de-allocation are automatically managed.
Programmers do not specifically need to manage the memory.
 Cross-platform Compatibility - Python can be easily installed on Windows, macOS, and
various Linux distributions, allowing developers to create software that runs across different
operating systems.
 Rich Standard Library - Python comes with several standard libraries that provide ready-to-use
modules and functions for various tasks, ranging from web development and data manipulation
to machine learning and networking.
 Open Source - Python is an open-source, cost-free programming language. It is utilized in
several sectors and disciplines as a result.

 Why Learn 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.
 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.

Dr. Yusuf Perwej Page 13


 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.
 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 HTML and
CSS.
 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 SpeechRecognition 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.
 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.

Dr. Yusuf Perwej Page 14


 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.

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


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

 Python IDEs

 The term "IDE" refers for "Integrated Development Environment," which is a coding tool
that aids in automating the editing, compiling, testing, and other steps of an SDLC while
making it simple for developers to execute, write, and debug code.
 It is specifically made for software development and includes a number of tools that are
used in the creation and testing of the software. There are some Python IDEs which are
as follows.

 PyCharm

The Jet Brains created PyCharm, a cross-platform Integrated Development Environment (IDE)
created specifically for Python. It is the most popular IDE and is accessible in both a premium
and a free open-source version. By handling everyday duties, a lot of time is saved.

It is a full-featured Python IDE with a wealth of features including auto code completion, easy
project navigation, quick error checking and correction, support for remote development,
database accessibility, etc.

Dr. Yusuf Perwej Page 15


Features
 Smart code navigation
 Errors Highlighting
 Powerful debugger
 Supports Python web development frameworks, i.e., Angular JS, Javascript

 Spyder

Spyder is a well-known open-source IDE that is best suited for data research and has a high level
of recognition in the industry. Scientific Python Development Environment is Spyder's full
name. It supports all popular operating systems, including Windows, MacOS X, and Linux.
A number of features are offered by it, including a localised code editor, a document viewer, a
variable explorer, an integrated console, etc. It also supports a number of scientific modules,
including SciPy and NumPy.
Features
 Proper syntax highlighting and auto code completion
 Integrates strongly with IPython console
 Performs well in multi-language editor and auto code completion mode

 PyDev

As an external plugin for Eclipse, PyDev is one of the most popular Python IDEs. The Python
programmers who have a background in Java naturally gravitate towards this Python interpreter
because it is so well-liked by users.
In 2003-2004, Aleksandar Totic, who is well known for his work on the Mosaic browser,
contributed to the Pydev project.
Django integration, code auto-completion, smart and block indents, among other features, are
features of Pydev.
Features
 Strong Parameters like refactoring, debugging, code analysis, and code coverage
function.
 It supports virtual environments, Mypy, and black formatter.
 Also supports PyLint integration, remote debugger, Unit test integration, etc.

 Atom

GitHub, a company that was first founded as an open-source, cross-platform project, is the
company that creates Atom. It is built on the Electron framework, which enables cross-platform
desktop applications utilising Chromium and Node.js and is dubbed the "Hackable Text Editor
for the 21st Century."
Features
 Visualize the results on Atom without open any other window.
 A plugin named "Markdown Preview Plus" provides built-in support for editing and
visualizing Markdown files.

Dr. Yusuf Perwej Page 16


 Wing

It's described as a cross-platform IDE with a tonne of useful features and respectable
development support. It is free to use in its personal edition. The 30-day trial period for the pro
version is provided for the benefit of the developers.
Features
 Customizable and can have extensions as well.
 Supports remote development, test-driven development along with the unit test.

 Jupyter Notebook

Jupyter is one of the most used Python notebook editors that is used across the Data Science
industry. You can create and edit notebook documents using this web application, which is based
on the server-client architecture. It utilises Python's interpretive nature to its fullest potential.
Features
 Supports markdowns
 Easy creation and editing of codes
 Ideal for beginners in data science

 Thonny

Thonny is a Python IDE (Integrated Development Environment) that is open-source, free, and
geared towards beginners. Since its initial release in 2016, it has grown to be a well-liked option
for novice Python coders.
Thonny's user-friendly interface is one of its most distinguishing qualities. It makes it simple for
beginners to learn Python and debug their programmes because it incorporates a code editor,
debugger, and REPL (Read-Eval-Print-Loop) in a single window. To assist users with writing
proper code, Thonny also has tools like code completion, syntax highlighting, and error
highlighting.
Thonny IDE that works well for teaching and learning programming is Thonny. Software that
highlights syntax problems and aids code completion was created at the University of Tartu.
Features
 Simple debugger
 Supports highlighting errors and auto code completion

 Rodeo

When it comes to gathering data and information from many sources for data science projects,
Rodeo is considered one of the top Python IDEs.
It offers code auto-completion and cross-platform capability.

Dr. Yusuf Perwej Page 17


Features
 Allows the functions for comparing data, interact, plot, and inspect data.
 Auto code completion, syntax highlighter, visual file navigator, etc.

 Microsoft Visual Studio

Microsoft Visual Studio is an open-source code editor which was best suited for development
and debugging of latest web and cloud projects. It has its own marketplace for extensions.
An integrated development environment (IDE) called Microsoft Visual Studio is used to create
software for the Windows, Android, and iOS operating systems. Since its initial release in 1997,
it has grown to be a well-liked software development tool.
Code editing, debugging, and code analysis are just a few of the capabilities and tools that are
included in the IDE. It supports a variety of programming languages, including Python, C++,
C#, Visual Basic, and others. Additionally, Microsoft Visual Studio comes with a variety of
project templates that make it simpler for developers to get started on their projects right away.
Microsoft Visual Studio 2022, the most recent release, comes with new features like improved
debugging and testing capabilities, improved Git integration, and a revamped user interface. The
enhanced performance of the IDE makes it quicker and more effective to construct complicated
software projects.
Features
 Supports Python Coding in Visual studio
 Available in both paid and free version

 Eric Python

The Eric Python is a Python-based editor that may be used for both professional and non-
professional tasks.
Since its initial release in 2000, Eric IDE (Integrated Development Environment) has been a free
and open-source Python IDE. It offers programmers a setting in which to efficiently write, test,
and debug Python programmes since it is user-friendly and simple to use.
Python 2 and 3 are among the Python versions that are supported by Eric IDE, which also offers
features like code highlighting, code completion, and syntax checking. Additionally, it contains
an integrated debugger that enables programmers to effectively debug their programmes.
The Eric IDE's plugin system, which enables developers to increase its capabilities, is one of its
primary features. An integrated version control system, a database browser, and a Python
profiler are just a few of the plugins that are available for the Eric IDE.

Features
 Provides customizable editors, source code folding, and window layouts.
 Advanced version control and project management capabilities
 Built-in debugger and task management support.

 Programming Cycle of Python


The Python programming life cycle is comparatively shorter and easier than the life cycles of traditional
programming languages. Python is an interpreted language i.e. it executes the program line by line and

Dr. Yusuf Perwej Page 18


stops at the first place it finds an error. Hence, it is easy to debug code. There are no compile or link
steps. In Python, we can simply import modules at runtime.

Steps involved in programming cycle

1. Firstly, identify the problem and start building the solution. Write the source code for
implementing the solution.
2. After implementing, we will test the code. The program should be kept static while testing (i.e.
no changes made). Testing helps to check whether the code provides the correct solution for our
problem or not.
3. If we find any syntax or logical errors during testing, we will correct them by editing the source
code.
4. Finally, the program is ready. We can update it from time to time.

 Python’s programming cycle is dramatically shorter than that of traditional programming


cycle.
 In Python, there are no compile or link steps.
 Python programs simply import modules at runtime and use the objects they contain.
Because of this, Python programs run immediately after changes are made.
 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.

 Tools that help to find bugs or perform static analysis

Dr. Yusuf Perwej Page 19


1. Pychecker:-
 Pychecker is an open source tool for static analysis that detects the bugs from source
code and warns about the style and complexity of the bug.

2. Pyflakes:-
 Pyflakes is a lightweight static analysis tool focused on identifying errors in Python code.
 It’s fast and efficient, providing quick feedback during development. It’s also simple to
use and suitable for integration into various workflows.
 Pyflakes doesn’t focus on style. Instead, it focuses on logical code issues, errors in a
program that do not cause syntax errors but result in incorrect or unintended behavior due
to flawed logic or reasoning in the code.

3. Pylint:-
 Pylint is highly configurable and it acts like special programs to control warnings and
errors, it is an extensive configuration file
 It is an open-source tool for static code analysis and it looks for programming errors and
is used for coding standard.
 It also integrates with Python IDEs such as Pycharm, Spyder, Eclipse, and Jupyter.

4. mypy:-
 mypy is a Python static type checker. It aims to enforce more disciplined coding
practices by checking and inferring variable types, helping catch potential bugs early in
development.
 It also integrates with most popular integrated development environments (IDEs) to
provide real-time feedback.
 Mypy also supports gradual typing, allowing developers to adopt it incrementally.

 Python Decorators

 A decorator is a design pattern in Python that allows a user to add new functionality to an
existing object without modifying its structure. Decorators are typically applied to
functions, and they play a crucial role in enhancing or modifying the behaviour of
functions.
 Decorators are a very powerful and useful tool in Python since it allows programmers to
modify the behaviour of a function or class.
 Decorators allow us to wrap another function in order to extend the behaviour of
wrapped function, without permanently modifying it.
 In Decorators, functions are taken as the argument into another function and then called
inside the wrapper function.

Example:

def my_function(x):
print("The number is=",x)

def my_decorator(some_function,num):
def wrapper(num):
print("Inside wrapper to check odd/even")
if num%2 == 0:
ret= "Even"
else:

Dr. Yusuf Perwej Page 20


ret= "Odd!"
some_function(num)
return ret
print ("wrapper function is called")
return wrapper

no=10
my_function = my_decorator(my_function, no)
print ("It is ",my_function(no))

Output

wrapper function is called


Inside wrapper to check odd/even
The number is= 10
It is Even

The my_function() just prints out the received number. However, its behaviour is modified by
passing it to a my_decorator. The inner function receives the number and returns whether it is
odd/even.

Example:

#-------- orig_func already given ----------


def orig_func():
print("Wheee!")

#------ write decorator ------------


def my_decorator(some_function):
def my_wrapper():
print ("do something before") #do something before, if you want to
some_function()
print ("do something after") #do something after, if you want to
return my_wrapper

#------ create decorator and call orig func --------


orig_func = my_decorator(orig_func) #create decorator, modify functioning
orig_func() #call modified orig_func

Output

do something before
Wheee!
do something after

 Python Comments

Comments in Python are the lines in the code that are ignored by the interpreter during the
execution of the program. Comments enhance the readability of the code and help the

Dr. Yusuf Perwej Page 21


programmers to understand the code very carefully. It also helps in collaborating with other
developers as adding comments makes it easier to explain the code.

# sample comment
name = "GITM"
print(name)

 Why are Comments Used in Python

Comments have been an integral part of programming languages, and every language have
different ways of using comments.

1. Enhance code readability


2. Explaining code to other
3. Understanding code if studied after some time
4. Documenting the steps and needs for a function
5. Sharing code with fellow developers
6. Collaborating with multiple people.

 Types of Comments in Python

1. Single-Line Comments

 Python single-line comment starts with the hashtag symbol (#) with no white spaces and
lasts till the end of the line.

 If the comment exceeds one line then put a hashtag on the next line and continue the
Python Comment.

 Python’s single-line comments are proved useful for supplying short explanations for
variables, function declarations, and expressions.

# Program to take the user's name

name = input('Enter your name')


print(name)

2. Multi-Line Comments

Python does not provide the option for multiline comments. However, there are different ways
through which we can write multiline comments.

a) Multiline comments using multiple hashtags (#)

We can multiple hashtags (#) to write multiline comments in Python. Each and every line will be
considered as a single-line comment.

# Python program to demonstrate


# multiline comments

print("Multiline comments")

Dr. Yusuf Perwej Page 22


3. String Literals

Python ignores the string literals that are not assigned to a variable so we can use these string
literals as Python Comments.

a) Single-line comments using string literals

On executing the above code we can see that there will not be any output so we use the strings
with triple quotes(“””) as multiline comments.

'This will be ignored by Python'

b) Multiline comments using string literals

""" Python program to demonstrate


multiline comments"""
print("Multiline comments")

4. Docstring

 Python docstring is the string literals with triple quotes that are appeared right after the function.

 It is used to associate documentation that has been written with Python modules, functions,
classes, and methods.

 It is added right below the functions, modules, or classes to describe what they do. In Python, the
docstring is then made available via the __doc__ attribute.

def Adding(a, b):


"""Adding the value of a and b"""
return a+b
# Print the docstring of multiply function
print(Adding.__doc__)

Note- Some of the tips you can follow, to make your comments effective are:

 Comments should be short and precise.


 Use comments only, when necessary, don’t clutter your code with comments.
 Comment should have some meaning.
 Avoid writing generic or basic comments.
 Write comments that are self-explanatory.

 Python Keywords and Identifiers

 Every language contains words and a set of rules that would make a sentence meaningful.
 Similarly, in Python programming language, there are a set of predefined words, called
Keywords which along with Identifiers will form meaningful sentences when used together.
 Python keywords cannot be used as the names of variables, functions, and classes.

 Keywords in Python

Dr. Yusuf Perwej Page 23


Python Keywords are some predefined and reserved words in Python that have special
meanings. Keywords are used to define the syntax of the coding. The keyword cannot be used as
an identifier, function, or variable name. All the keywords in Python are written in lowercase
except True and False. There are 35 keywords in Python

 List of Python Keywords

Keywords Description
This is a logical operator which returns true if both the operands are true
 and
else returns false.
This is also a logical operator which returns true if anyone operand is true
 or
else returns false.
This is again a logical operator it returns True if the operand is false else
 not
returns false.
 if This is used to make a conditional statement.
Elif is a condition statement used with an if statement. The elif statement is
 elif
executed if the previous conditions were not true.
Else is used with if and elif conditional statements. The else block is
 else
executed if the given condition is not true.
 for This is used to create a loop.
 while This keyword is used to create a while loop.
 break This is used to terminate the loop.
 as This is used to create an alternative.
 def It helps us to define functions.
 lambda It is used to define the anonymous function.
 pass This is a null statement which means it will do nothing.
 return It will return a value and exit the function.
 True This is a Boolean value.
 False This is also a Boolean value.
 try It makes a try-except statement.
 with The with keyword is used to simplify exception handling.
This function is used for debugging purposes. Usually used to check the
 assert
correctness of code
 class It helps us to define a class.
 continue It continues to the next iteration of a loop
 del It deletes a reference to an object.
 except Used with exceptions, what to do when an exception occurs
finally is used with exceptions, a block of code that will be executed no
 finally
matter if there is an exception or not.
 from It is used to import specific parts of any module.
 global This declares a global variable.
 import This is used to import a module.
 in It’s used to check whether a value is present in a list, range, tuple, etc.
 is This is used to check if the two variables are equal or not.
 none This is a special constant used to denote a null value or avoid. It’s important

Dr. Yusuf Perwej Page 24


Keywords Description
to remember, 0, any empty container (e.g empty list) do not compute to
None
 nonlocal It’s declared a non-local variable.
 raise This raises an exception.
 yield It ends a function and returns a generator.
 async It is used to create asynchronous coroutine.
 await It releases the flow of control back to the event loop.

[Note- In Python, there is an inbuilt keyword module that provides an iskeyword() function that
can be used to check whether a given string is a valid keyword or not. Furthermore, we can
check the name of the keywords in Python by using the kwlist attribute of the keyword module.]

# 1st code
import keyword

print(keyword.kwlist)

# 2nd code
# Program to check whether a given
# word is a Python keyword or not

import keyword

s ="if"
t ="in"
u ="Goel"

# using iskeyword() function to check


print(s, "is a keyword in Python:",
keyword.iskeyword(s))

print("lambda is a keyword in Python:",


keyword.iskeyword("lambda"))

print("print is a keyword in Python:",


keyword.iskeyword("print"))

print(t, "is a keyword in Python:",


keyword.iskeyword(t))

print(u, "is a keyword in Python:",


keyword.iskeyword(u))

Output
if is a keyword in Python: True
lambda is a keyword in Python: True
print is a keyword in Python: False
in is a keyword in Python: True
Goel is a keyword in Python: False

Dr. Yusuf Perwej Page 25


 Identifiers in Python

Python Identifier is the name we give to identify a variable, function, class, module or other
object. That means whenever we want to give an entity a name, that’s called identifier.

A python identifier is a name given to various entities like variables, functions, and classes. It
helps a programmer to distinguish one entity from another entity. Below are a few rules to be
kept in mind while naming an identifier-

An identifier can be a composition of alphabets (a-z) and numbers (0-9). The alphabets can be in
uppercase or lowercase. An underscore can also be used in an identifier. However, we must note
that Python is a case-sensitive language. Hence, “testing” will not be the same as “Testing”.

 Rules for Naming Python Identifiers

 It cannot be a reserved python keyword.


 It should not contain white space.
 It can be a combination of A-Z, a-z, 0-9, or underscore.
 It should start with an alphabet character or an underscore ( _ ).
 It should not contain any special character other than an underscore ( _ ).

 Examples of Python Identifiers

 Valid identifiers:
 gitm1
 _ gitm 1
 _1_ gitm
 gitm_1
 Invalid Identifiers:
 !gitm1
 1gitm
 1_ gitm
 gitm#1
 gitm 1

 Things to Remember

Always give the identifiers a name that makes sense. While c = 10 is a valid name, writing count =
10 would make more sense, and it would be easier to figure out what it represents when you look
at your code after a long gap.

Multiple words can be separated using an underscore, like this_is_a_long_variable.

Q: What are Keywords and Identifiers in Python?

Answer: Keywords in Python are predefined words that have a special meaning to the
interpreter. They are reserved words that are used to perform a specific task in Python
programming.

Dr. Yusuf Perwej Page 26


Identifiers in Python are names given to different parts of a Python program like variables,
functions, classes, etc. They are user-defined and the users must follow a set of rules to define
them in a python program.

Q: What is the difference between a Keyword and an Identifier in Python?

Answer: A Keyword in Python is a predefined reserved word that is meaningful to the


interpreter and performs a specific task. Whereas, an identifier is a userdefined word given to
different parts of python programming. An identifier can be a name given to a variable, function
or a class.

 Example

Example 1: Example of and, or, not, True, False keywords.

print("example of True, False, and, or, not keywords")

# compare two operands using and operator


print(True and True)

# compare two operands using or operator


print(True or False)

# use of not operator


print(not True)

Output

example of True, False, and, or, not keywords


True
True
False

Example 2: Example of a break, continue keywords and identifier.

# execute for loop


for i in range(1, 11):

# print the value of i


print(i)

# check the value of i is less than 5


# if i less than 5 then continue loop
if i < 5:
continue

# if i greater than 5 then break loop


else:
break
Output

1
2
3
4

Dr. Yusuf Perwej Page 27


5

Example 3: example of for, in, if, elif, and else keywords.

# run for loop


for t in range(1, 5):
# print one of t ==1
if t == 1:
print('One')
# print two if t ==2
elif t == 2:
print('Two')
else:
print('else block execute')
Output

One
Two
else block execute
else block execute

Example 4: Example of def, if, and else keywords.

# define GFG() function using def keyword


def GFG():
i=20
# check i is odd or not
# using if and else keyword
if(i % 2 == 0):
print("given number is even")
else:
print("given number is odd")

# call GFG() function


GFG()
Output

given number is even

Example 5: Example of try, except, raise.

def fun(num):
try:
r = 1.0/num
except:
print('Exception raises')
return
return r

print(fun(10))
print(fun(0))
Output

0.1
Exception raises
None

Dr. Yusuf Perwej Page 28


Example 6: Example of a lambda keyword.

# define a anonymous using lambda keyword


# this lambda function increment the value of b
a = lambda b: b+1

# run a for loop


for i in range(1, 6):
print(a(i))
Output

2
3
4
5
6

Example 7: use of return keyword.

# define a function
def fun():
# declare a variable
a=5
# return the value of a
return a
# call fun method and store
# it's return value in a variable
t = fun()
# print the value of t
print(t)
Output

Example 8: use of a del keyword.

# create a list
l = ['a', 'b', 'c', 'd', 'e']

# print list before using del keyword


print(l)

del l[2]

# print list after using del keyword


print(l)
Output

['a', 'b', 'c', 'd', 'e']


['a', 'b', 'd', 'e']

Example 9: use of global keyword.

# declare a variable
gvar = 10

# create a function

Dr. Yusuf Perwej Page 29


def fun1():
# print the value of gvar
print(gvar)

# declare fun2()
def fun2():
# declare global value gvar
global gvar
gvar = 100

# call fun1()
fun1()

# call fun2()
fun2()
Output

10

Example 10: example of yield keyword.

def Generator():
for i in range(6):
yield i+1

t = Generator()
for i in t:
print(i)
Output

1
2
3
4
5
6

Example 11: Use of finally keyword

def divide(a, b):


try:
c = a/b
print("Inside try block")
except:
print("Inside Exception block")
finally:
print("Inside finally block")
divide(3,2)
divide(3,0)
Output

Inside try block


Inside finally block
Inside Exception block
Inside finally block

Dr. Yusuf Perwej Page 30


Example 12: Use of import keyword

import math
print("factorial of 5 is :", math.factorial(5))
Output

factorial of 5 is : 120

Example 13: Use of is keyword

x = 10
y = 20
z=x
print(x is z)
print(x is y)
Output

True
False

Example 14: Use of from keyword

from math import gcd


print("gcd of 345 and 675 is : ", gcd(345, 675))
Output

gcd of 345 and 675 is : 15

Example 15: Use of async and await keyword

# code
import asyncio

async def factorial(n):


if n == 0:
return 1
return n * await factorial(n - 1)

def main():
result = asyncio.run(factorial(5))
print(result)

if __name__ == "__main__":
main()
Output

120

 Python Variables

 Python Variables

 A variable is the name given to a memory location. A value-holding Python variable is


also known as an identifier.

Dr. Yusuf Perwej Page 31


 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.

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


 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).
 White space and special characters (!, @, #, %, etc.) are not allowed in the identifier
name. ^, &, *).
 Identifier name should not be like any watchword characterized in the language.
 Names of identifiers are case-sensitive; for instance, my name, and MyName isn't
something very similar.
 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 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.
 In Python, we don't have to explicitly declare variables. The variable is declared
automatically whenever a value is added to it.
 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.

1. print("Goel")

Output:

Goel

The Python object makes a integer object and shows it to the control centre. 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.

1. print("Goel")

print(type("Goel"))
Dr. Yusuf Perwej Page 32
Output:

<class 'str'>

2. x = 10
print(type(x))

Output:
<class 'int'>

In Python, factors are a 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 point to because Python does not create another
object.

The 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))
# Reassigned variable a
a = 500
print(id(a))

Output:

Dr. Yusuf Perwej Page 33


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

. 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 = "Amit"
age = 25
marks = 82.50
print(name)
print(age)
print(marks)

Output:

Amit
25
82.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.

Dr. Yusuf Perwej Page 34


 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.
 Pascal Case - It is the same as the Camel Case, but here the first word is also capital. For
example - NameOfStudent, etc.
 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.

1. Assigning single value to multiple variables

x=y=z=50
print(x)
print(y)
print(z)

Output:

50
50
50

2. Assigning multiple values to multiple variables:

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.

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

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

Output:

<class 'str'>

Dr. Yusuf Perwej Page 35


 Python Variable Types

There are two types of variables in Python - Local variable and Global variable.

 Python Global variables are those which are not defined inside any function and have a
global scope whereas Python local variables are those which are defined inside a
function and their scope is limited to that function only.
 In other words, we can say that local variables are accessible only inside the function in
which it was initialized whereas the global variables are accessible throughout the
program and inside every function.

 Python Local Variables

Local variables in Python are those which are initialized inside a function and belong only to that
particular function. It cannot be accessed anywhere outside the function

Creating local variables in Python

Defining and accessing local variables

def f():

# local variable
s = "I love Goel"
print(s)
# Driver code
f()
Output

I love Goel

Can a local variable be used outside a function?

If we will try to use this local variable outside the function then let’s see what will happen.

def f():

# local variable
s = "I love Goel"
print("Inside Function:", s)

# Driver code
f()
print(s)

Output:
NameError: name 's' is not defined

 Python Global Variables

These are those which are defined outside any function and which are accessible throughout the
program, i.e., inside and outside of every function.

Dr. Yusuf Perwej Page 36


Create a global variable in Python

Defining and accessing Python global variables.

# This function uses global variable s


def f():
print("Inside Function", s)

# Global scope
s = "I love Goel"
f()
print("Outside Function", s)

Output

Inside Function I love Goel


Outside Function I love Goel

The variable s is defined as the global variable and is used both inside the function as well as
outside the function.

Note: As there are no locals, the value from the globals will be used but make sure both the local
and the global variables should have same name.

Why do we use Local and Global variables in Python?

Now, what if there is a Python variable with the same name initialized inside a function as well
as globally? Now the question arises, will the local variable will have some effect on the global
variable or vice versa, and what will happen if we change the value of a variable inside of the
function f()? Will it affect the global as well? We test it in the following piece of code:

Example

If a variable with the same name is defined inside the scope of the function as well then it will
print the value given inside the function only and not the global value.

# This function has a variable with


# name same as s.
def f():
s = "Me too."
print(s)

# Global scope
s = "I love Goel"
f()
print(s)

Output

Me too.
I love Goel

Now, what if we try to change the value of a global variable inside the function? Let’s see it
using the below example.

Dr. Yusuf Perwej Page 37


# This function uses global variable s
def f():
s += 'GOEL'
print("Inside Function", s)

# Global scope
s = "I love Gitm"
f()

Output:
UnboundLocalError: local variable 's' referenced before assignment

To make the above program work, we need to use the “global” keyword in Python. Let’s see
what this global keyword is.

 The global Keyword

We only need to use the global keyword in a function if we want to do assignments or change
the global variable. global is not needed for printing and accessing. Python “assumes” that we
want a local variable due to the assignment to s inside of f(), so the first statement throws the
error message. Any variable which is changed or created inside of a function is local if it hasn’t
been declared as a global variable. To tell Python, that we want to use the global variable, we
have to use the keyword “global”, as can be seen in the following example:

Example 1: Using Python global keyword

# This function modifies the global variable 's'


def f():
global s
s += ' GOEL'
print(s)
s = "Look for Goel"
print(s)

# Global Scope
s = "Goel is great!"
f()
print(s)

Output
Goel is great! GOEL
Look for Goel
Look for Goel
Now there is no ambiguity.

Example 2: Using Python global and local variables


a=1

# Uses global because there is no local 'a'


def f():
print('Inside f() : ', a)

# Variable 'a' is redefined as a local


def g():
a=2
print('Inside g() : ', a)

Dr. Yusuf Perwej Page 38


# Uses global keyword to modify global 'a'
def h():
global a
a=3
print('Inside h() : ', a)

# Global scope
print('global : ', a)
f()
print('global : ', a)
g()
print('global : ', a)
h()
print('global : ', a)
Output
global : 1
Inside f() : 1
global : 1
Inside g() : 2
global : 1
Inside h() : 3
global : 3

 Difference b/w Local Variable Vs. Global Variables


Comparisons
Global Variable Local Variable
Basis

Definition declared outside the functions declared within the functions

They are created the execution of the They are created when the function
Lifetime program begins and are lost when the starts its execution and are lost when
program is ended the function ends

Data Sharing Offers Data Sharing It doesn’t offers Data Sharing

Scope Can be access throughout the code Can access only inside the function

Parameters
parameter passing is not necessary parameter passing is necessary
needed

A fixed location selected by the


Storage They are kept on the stack
compiler

Once the value changes it is reflected once changed the variable don’t affect
Value
throughout the code other functions of the program

 Delete a variable

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

Syntax -

Dr. Yusuf Perwej Page 39


1. 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 -

1. # Assigning a value to x
2. x = 6
3. print(x)
4. # deleting a variable.
5. del x
6. 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.

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.

Dr. Yusuf Perwej Page 40


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.

ii) Comments

a)Tokens:

 The tokens can be defined as a punctuator mark, reserved words, and each word in a
statement.
 The token is the smallest unit inside the given program.

There are following tokens in Python:

 Keywords.
 Identifiers.
 Literals.
 Operators.

Dr. Yusuf Perwej Page 41


 Python Data Types

 Numeric Data Types in Python

The numeric data type in Python represents the data that has a numeric value. A numeric value
can be an integer, a floating number, or even a complex number. These values are defined as
Python int, Python float, and Python complex classes in Python.

 Integers – This value is represented by int class. It contains positive or negative whole numbers
(without fractions or decimals). In Python, there is no limit to how long an integer value can be.

 Float – This value is represented by the float class. It is a real number with a floating-point
representation. It is specified by a decimal point. Optionally, the character e or E followed by a
positive or negative integer may be appended to specify scientific notation.

 Complex Numbers – A complex number is represented by a complex class. It is specified as


(real part) + (imaginary part)j. For example – 2+3j

Note – type() function is used to determine the type of Python data type.

Example: This code demonstrates how to determine the data type of variables in Python using
the type() function. It prints the data types of three variables: a (integer), b (float), and c
(complex). The output shows the respective Python data types for each variable.

a=5
print("Type of a: ", type(a))
b = 5.0
print("\nType of b: ", type(b))
c = 2 + 4j
print("\nType of c: ", type(c))
Output:
Type of a: <class 'int'>
Type of b: <class 'float'>
Type of c: <class 'complex'>

a=10
b="Hi Python"
c = 10.5
print(type(a))
print(type(b))
print(type(c))
Output:
<type 'int'>
<type 'str'>

Dr. Yusuf Perwej Page 42


<type 'float'>

 Sequence Data Type in Python

The sequence Data Type in Python is the ordered collection of similar or different Python data
types. Sequences allow storing of multiple values in an organized and efficient fashion. There
are several sequence types in Python

 Python String
 Python List
 Python Tuple

 String Data Type

Strings in Python are arrays of bytes representing Unicode characters. A string is a collection of
one or more characters put in a single quote, double-quote, or triple-quote. In Python there is no
character data type, a character is a string of length one. It is represented by str class.

Creating String

Strings in Python can be created using single quotes, double quotes, or even triple quotes.

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

String1 = 'Welcome to the GOEL World'

print("String with the use of Single Quotes: ")

print(String1)

String1 = "I'm a Goel"

print("\nString with the use of Double Quotes: ")

print(String1)

print(type(String1))

String1 = '''I'm a Gitm and I live in a world of "Goel"'''

print("\nString with the use of Triple Quotes: ")

print(String1)

print(type(String1))

String1 = '''Gitm

For

Life'''

Dr. Yusuf Perwej Page 43


print("\nCreating a multiline String: ")

print(String1)

Output:

String with the use of Single Quotes:


Welcome to the GOEL World

String with the use of Double Quotes:


I'm a Goel
<class 'str'>

String with the use of Triple Quotes:


I'm a Gitm and I live in a world of "Goel"
<class 'str'>

Creating a multiline String:


Gitm
For
Life

Accessing elements of String

In Python programming, individual characters of a String can be accessed by using the method
of Indexing. Negative Indexing allows negative address references to access characters from the
back of the String, e.g. -1 refers to the last character, -2 refers to the second last character, and so
on.

Example: This Python code demonstrates how to work with a string named ‘String1′. It
initializes the string with “GoelsForGitms” and prints it. It then showcases how to access the
first character (“G”) using an index of 0 and the last character (“s”) using a negative index of -1.

String1 = "GoelsForGitms"

print("Initial String: ")

print(String1)

print("\nFirst character of String is: ")

print(String1[0])

print("\nLast character of String is: ")

print(String1[-1])

Output:

Initial String:
GoelsForGitms
First character of String is:
G
Last character of String is:
s

Dr. Yusuf Perwej Page 44


 List Data Type

Lists are just like arrays, declared in other languages which is an ordered collection of data. It is
very flexible as the items in a list do not need to be of the same type.

Creating a List in Python

Lists in Python can be created by just placing the sequence inside the square brackets[].

Example: This Python code demonstrates list creation and manipulation. It starts with an empty
list and prints it. It creates a list containing a single string element and prints it. It creates a list
with multiple string elements and prints selected elements from the list. It creates a multi-
dimensional list (a list of lists) and prints it. The code showcases various ways to work with lists,
including single and multi-dimensional lists.

List = []

print("Initial blank List: ")

print(List)

List = [' GoelsForGitms']

print("\nList with the use of String: ")

print(List)

List = ["Goels", "For", "Gitms"]

print("\nList containing multiple values: ")

print(List[0])

print(List[2])

List = [['Goels', 'For'], ['Gitms']]

print("\nMulti-Dimensional List: ")

print(List)

Output:

Initial blank List:


[]
List with the use of String:
[' GoelsForGitms']
List containing multiple values:
Goels
Gitms
Multi-Dimensional List:
[['Goels', 'For'], ['Gitms']]

 Python Access List Items

In order to access the list items refer to the index number. Use the index operator [ ] to access an
item in a list. In Python, negative sequence indexes represent positions from the end of the array.

Dr. Yusuf Perwej Page 45


Instead of having to compute the offset as in List[len(List)-3], it is enough to just write List[-3].
Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the
second-last item, etc.

List = ["Goels", "For", "Gitms"]

print("Accessing element from the list")

print(List[0])

print(List[2])

print("Accessing element using negative indexing")

print(List[-1])

print(List[-3])

Output:

Accessing element from the list


Goels
Gitms
Accessing element using negative indexing
Gitms
Goels

 Tuple Data Type

Just like a list, a tuple is also an ordered collection of Python objects. The only difference
between a tuple and a list is that tuples are immutable i.e. tuples cannot be modified after it is
created. It is represented by a tuple class.

Creating a Tuple in Python

In Python Data Types, tuples are created by placing a sequence of values separated by a
‘comma’ with or without the use of parentheses for grouping the data sequence. Tuples can
contain any number of elements and of any datatype (like strings, integers, lists, etc.). Note:
Tuples can also be created with a single element, but it is a bit tricky. Having one element in the
parentheses is not sufficient, there must be a trailing ‘comma’ to make it a tuple.

Example: This Python code demonstrates different methods of creating and working with
tuples. It starts with an empty tuple and prints it. It creates a tuple containing string elements and
prints it. It converts a list into a tuple and prints the result. It creates a tuple from a string using
the tuple() function. It forms a tuple with nested tuples and displays the result.

Tuple1 = ()

print("Initial empty Tuple: ")

print(Tuple1)

Tuple1 = ('Goels', 'For')

print("\nTuple with the use of String: ")

Dr. Yusuf Perwej Page 46


print(Tuple1)

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

print("\nTuple using List: ")

print(tuple(list1))

Tuple1 = tuple('Gitms')

print("\nTuple with the use of function: ")

print(Tuple1)

Tuple1 = (0, 1, 2, 3)

Tuple2 = ('python', 'goel')

Tuple3 = (Tuple1, Tuple2)

print("\nTuple with nested tuples: ")

print(Tuple3)

Output:

Initial empty Tuple:


()
Tuple with the use of String:
('Goels', 'For')
Tuple using List:
(1, 2, 4, 5, 6)
Tuple with the use of function:
('G', 'i', 't', 'm', 's')
Tuple with nested tuples:
((0, 1, 2, 3), ('python', 'goel'))

Note – The creation of a Python tuple without the use of parentheses is known as Tuple Packing.

Access Tuple Items

In order to access the tuple items refer to the index number. Use the index operator [ ] to access
an item in a tuple. The index must be an integer. Nested tuples are accessed using nested
indexing.

The code creates a tuple named ‘tuple1′ with five elements: 1, 2, 3, 4, and 5. Then it prints the
first, last, and third last elements of the tuple using indexing.

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

print("First element of tuple")

print(tuple1[0])

print("\nLast element of tuple")

print(tuple1[-1])

Dr. Yusuf Perwej Page 47


print("\nThird last element of tuple")

print(tuple1[-3])

Output:

First element of tuple


1
Last element of tuple
5
Third last element of tuple
3

 Boolean Data Type in Python

Python Data type with one of the two built-in values, True or False. Boolean objects that are
equal to True are truthy (true), and those equal to False are falsy (false). However non-Boolean
objects can be evaluated in a Boolean context as well and determined to be true or false. It is
denoted by the class bool.

Note – True and False with capital ‘T’ and ‘F’ are valid booleans otherwise python will throw an
error.

Example: The first two lines will print the type of the boolean values True and False, which
is <class ‘bool’>. The third line will cause an error, because true is not a valid keyword in
Python. Python is case-sensitive, which means it distinguishes between uppercase and lowercase
letters. You need to capitalize the first letter of true to make it a boolean value.

print(type(True))

print(type(False))

print(type(true))

Output:

<class 'bool'>
<class 'bool'>

Traceback (most recent call last):


File "/home/7e8862763fb66153d70824099d4f5fb7.py", line 8, in
print(type(true))
NameError: name 'true' is not defined

 Set Data Type in Python

In Python Data Types, a Set is an unordered collection of data types that is iterable, mutable, and
has no duplicate elements. The order of elements in a set is undefined though it may consist of
various elements.

Dr. Yusuf Perwej Page 48


Create a Set in Python

Sets can be created by using the built-in set() function with an iterable object or a sequence by
placing the sequence inside curly braces, separated by a ‘comma’. The type of elements in a set
need not be the same, various mixed-up data type values can also be passed to the set.

Example: The code is an example of how to create sets using different types of values, such as
strings, lists, and mixed values

set1 = set()

print("Initial blank Set: ")

print(set1)

set1 = set("GoelsForGitms")

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

print(set1)

set1 = set(["Goels", "For", "Gitms"])

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

print(set1)

set1 = set([1, 2, 'Goels', 4, 'For', 6, 'Gitms'])

print("\nSet with the use of Mixed Values")

print(set1)

Output:

Initial blank Set:


set()
Set with the use of String:
{'m', 't', 'F', 'r', 'i', 'l', 's', 'G', 'e', 'o'}
Set with the use of List:
{'Goels', 'For', 'Gitms'}
Set with the use of Mixed Values
{'Goels', 1, 2, 4, 6, 'Gitms', 'For'}

Access Set Items

Set items cannot be accessed by referring to an index, since sets are unordered the items have no
index. But you can loop through the set items using a for loop, or ask if a specified value is
present in a set, by using the in the keyword.

Example: This Python code creates a set named set1 with the
values “Goels”, “For” and “Gitms”. The code then prints the initial set, the elements of the set
in a loop, and checks if the value “Goels” is in the set using the ‘in’ operator

set1 = set(["Goels", "For", "Gitms"])

Dr. Yusuf Perwej Page 49


print("\nInitial set")

print(set1)

print("\nElements of set: ")

for i in set1:

print(i, end=" ")

print("Goels" in set1)

Output:

Initial set
{'Goels', 'For', 'Gitms'}

Elements of set:
Goels For Gitms True

 Dictionary Data Type in Python

A dictionary in Python is an unordered collection of data values, used to store data values like a
map, unlike other Python Data Types that hold only a single value as an element, a Dictionary
holds a key: value pair. Key-value is provided in the dictionary to make it more optimized. Each
key-value pair in a Dictionary is separated by a colon: , whereas each key is separated by a
‘comma’.

Create a Dictionary in Python

In Python, a Dictionary can be created by placing a sequence of elements within curly {} braces,
separated by ‘comma’. Values in a dictionary can be of any datatype and can be duplicated,
whereas keys can’t be repeated and must be immutable. The dictionary can also be created by
the built-in function dict(). An empty dictionary can be created by just placing it in curly
braces{}. Note – Dictionary keys are case sensitive, the same name but different cases of Key
will be treated distinctly.

Example: This code creates and prints a variety of dictionaries. The first dictionary is empty.
The second dictionary has integer keys and string values. The third dictionary has mixed keys,
with one string key and one integer key. The fourth dictionary is created using the dict()
function, and the fifth dictionary is created using the [(key, value)] syntax

Dict = {}

print("Empty Dictionary: ")

print(Dict)

Dict = {1: 'Goels', 2: 'For', 3: 'Gitms'}

print("\nDictionary with the use of Integer Keys: ")

print(Dict)

Dict = {'Name': 'Goels', 1: [1, 2, 3, 4]}

Dr. Yusuf Perwej Page 50


print("\nDictionary with the use of Mixed Keys: ")

print(Dict)

Dict = dict({1: 'Goels', 2: 'For', 3: 'Gitms'})

print("\nDictionary with the use of dict(): ")

print(Dict)

Dict = dict([(1, 'Goels'), (2, 'For')])

print("\nDictionary with each item as a pair: ")

print(Dict)

Output:

Empty Dictionary:
{}

Dictionary with the use of Integer Keys:


{1: 'Goels', 2: 'For', 3: 'Gitms'}

Dictionary with the use of Mixed Keys:


{'Name': 'Goels', 1: [1, 2, 3, 4]}

Dictionary with the use of dict():


{1: 'Goels', 2: 'For', 3: 'Gitms'}

Dictionary with each item as a pair:


{1: 'Goels', 2: 'For'}

Accessing Key-value in Dictionary

In order to access the items of a dictionary refer to its key name. Key can be used inside square
brackets. There is also a method called get() that will also help in accessing the element from a
dictionary.

Example: The code in Python is used to access elements in a dictionary. Here’s what it does, It
creates a dictionary Dict with keys and values as {1: ‘Goels’, ‘name’: ‘For’, 3: ‘Gitms’}. It
prints the value of the element with the key ‘name’, which is ‘For’. It prints the value of the
element with the key 3, which is ‘Goels’.

Dict = {1: 'Goels', 'name': 'For', 3: 'Gitms'}

print("Accessing a element using key:")

print(Dict['name'])

print("Accessing a element using get:")

print(Dict.get(3))

Output:

Accessing a element using key:

Dr. Yusuf Perwej Page 51


For
Accessing a element using get:
Gitms

 Type Conversion in Python

In programming, type conversion is the process of converting data of one type to another. For
example: converting int data to str. The act of changing an object’s data type is known as type
conversion. The Python interpreter automatically performs Implicit Type Conversion. Python
prevents Implicit Type Conversion from losing data.

The user converts the data types of objects using specified functions in explicit type conversion,
sometimes referred to as type casting. When type casting, data loss could happen if the object is
forced to conform to a particular data type. There are two types of Type Conversion in Python:

 Python Implicit Type Conversion


 Python Explicit Type Conversion

 Implicit Type Conversion in Python

In Implicit type conversion of data types in Python, the Python interpreter automatically converts
one data type to another without any user involvement. To get a more clear view of the topic see
the below examples.

Example

As we can see the data type of ‘z’ got automatically changed to the “float” type while one
variable x is of integer type while the other variable y is of float type. The reason for the float
value not being converted into an integer instead is due to type promotion that allows performing
operations by converting data into a wider-sized data type without any loss of information. This
is a simple case of Implicit type conversion in Python.

x = 20

print("x is of type:",type(x))

y = 20.7
print("y is of type:",type(y))

z=x+y

print(z)
print("z is of type:",type(z))

Output

x is of type: <class 'int'>


y is of type: <class 'float'>
40.7
z is of type: <class 'float'>

 Explicit Type Conversion in Python

Dr. Yusuf Perwej Page 52


In Explicit Type Conversion in Python, the data type is manually changed by the user as per
their requirement. With explicit type conversion, there is a risk of data loss since we are forcing
an expression to be changed in some specific data type. Various forms of explicit type
conversion are explained below:

 Converting integer to float

int(a, base): This function converts any data type to an integer. ‘Base’ specifies the base in
which the string is if the data type is a string.
float(): This function is used to convert any data type to a floating-point number.

# initializing string
s = "10010"

# printing string converting to int base 2


c = int(s,2)
print ("After converting to integer base 2 : ", end="")
print (c)

# printing string converting to float


e = float(s)
print ("After converting to float : ", end="")
print (e)

Output:

After converting to integer base 2 : 18


After converting to float : 10010.0

 Python Type conversion using ord(), hex(), oct()

ord(): This function is used to convert a character to an integer.


hex(): This function is to convert an integer to a hexadecimal string.
oct(): This function is to convert an integer to an octal string.

# initializing integer

s = '4'

# printing character converting to integer

c = ord(s)

print ("After converting character to integer : ",end="")

print (c)

# printing integer converting to hexadecimal string

c = hex(56)

print ("After converting 56 to hexadecimal string : ",end="")

print (c)

Dr. Yusuf Perwej Page 53


# printing integer converting to octal string

c = oct(56)

print ("After converting 56 to octal string : ",end="")

print (c)

Output:

After converting character to integer : 52


After converting 56 to hexadecimal string : 0x38
After converting 56 to octal string : 0o70

 Python Type conversion using tuple(), set(), list()

tuple(): This function is used to convert to a tuple.


set(): This function returns the type after converting to set.
list(): This function is used to convert any data type to a list type.

# initializing string
s = 'goels'

# printing string converting to tuple


c = tuple(s)
print ("After converting string to tuple : ",end="")
print (c)

# printing string converting to set


c = set(s)
print ("After converting string to set : ",end="")
print (c)

# printing string converting to list


c = list(s)
print ("After converting string to list : ",end="")
print (c)

Output:

After converting string to tuple : ('g', 'o', 'e', 'l', 's')


After converting string to set : {'l', 's', 'g', 'o', 'e'}
After converting string to list : ['g', 'o', 'e', 'l', 's']

 Python code to demonstrate Type conversion using dict(), complex(), str()

dict(): This function is used to convert a tuple of order (key, value) into a dictionary.
str(): Used to convert an integer into a string.
complex(real,imag) : This function converts real numbers to complex(real,imag) number.

# initializing integers
a=1
b=2

# initializing tuple
tup = (('a', 1) ,('f', 2), ('g', 3))

# printing integer converting to complex number

Dr. Yusuf Perwej Page 54


c = complex(1,2)
print ("After converting integer to complex number : ",end="")
print (c)

# printing integer converting to string


c = str(a)
print ("After converting integer to string : ",end="")
print (c)

# printing tuple converting to expression dictionary


c = dict(tup)
print ("After converting tuple to dictionary : ",end="")
print (c)

Output:

After converting integer to complex number : (1+2j)


After converting integer to string : 1
After converting tuple to dictionary : {'a': 1, 'f': 2, 'g': 3}

 Convert ASCII value to characters

chr(number): This function converts a number to its corresponding ASCII character.

a = chr(76)

b = chr(77)

print(a)

print(b)

Output:

L
M

 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.

 Expression

A combination of operands and operators is called an expression. The expression in Python


produces some value or result after being interpreted by the Python interpreter. An expression in
Python is a combination of operators and operands.

An example of expression can be : x=x+10. In this expression, the first 10 is added to the
variable x. After the addition is performed, the result is assigned to the variable x.

x = 25 # a statement

Dr. Yusuf Perwej Page 55


x = x + 10 # an expression

print(x)
Output :
35

An expression in Python is very different from statements in Python. A statement is not


evaluated for some results. A statement is used for creating variables or for displaying values.

Example :
a = 25 # a statement
print(a) # a statement
Output :
25

An expression in Python can contain identifiers, operators, and operands.

An identifier is a name that is used to define and identify a class, variable, or function in
Python.

An operand is an object that is operated on. On the other hand, an operator is a special symbol
that performs the arithmetic or logical computations on the operands. There are many types of
operators in Python, some of them are :

 + : add (plus).
 - : subtract (minus).
 x : multiply.
 / : divide.
 ** : power.
 % : modulo.
 << : left shift.
 >> : right shift.
 & : bit-wise AND.
 | : bit-wise OR.
 ^ : bit-wise XOR.
 ~ : bit-wise invert.
 < : less than.
 > : greater than.
 <= : less than or equal to.
 >= : greater than or equal to.
 == : equal to.
 != : not equal to.
 and : boolean AND.
 or : boolean OR.
 not : boolean NOT.

The expression in Python can be considered as a logical line of code that is evaluated to obtain
some result. If there are various operators in an expression then the operators are resolved based
on their precedence. We have various types of expression in Python, refer to the next section for
a more detailed explanation of the types of expression in Python.

 Assignment Statement

Dr. Yusuf Perwej Page 56


Assignment statements are used to create new variables, assign values, and change values.

Syntax of assignment statement:

# LHS <=> RHS

Variable = Expression

There are three types of assignment statements:

 Value-based expression on RHS


 Current variable on RHS
 Operation on RHS

1. Value-based expression on RHS : In this type, Python allocates a new memory location to
the newly assigned variable.
For example :
test1 = “Hello”
id(test1)
Output :
2524751071304

2. Current variable on RHS : In this type, Python does not allocate a new memory location.
For example :
current_var = “It’s Quantum Series”
print(id(current_var))
new_var = current_var
print(id(new_var))
Output :
24751106240
2524751106240

3. Operation on RHS : In this type, we have an operation on the RHS of the statement, which is
the defining factor of the type of our statement.
For example :
test1 = 7 * 2 / 10
type(test1)
Output :
float

 Types of Expression in Python

We have various types of expression in Python, let us discuss them along with their respective
examples.

1. Constant Expressions

A constant expression in Python that contains only constant values is known as a constant
expression. In a constant expression in Python, the operator(s) is a constant. A constant is a
value that cannot be changed after its initialization.

Example :

Dr. Yusuf Perwej Page 57


x = 10 + 15

# Here both 10 and 15 are constants but x is a variable.

print("The value of x is: ", x)

Output :

The value of x is: 25

2. Arithmetic Expressions

An expression in Python that contains a combination of operators, operands, and sometimes


parenthesis is known as an arithmetic expression. The result of an arithmetic expression is also
a numeric value just like the constant expression discussed above. Before getting into the
example of an arithmetic expression in Python, let us first know about the various operators used
in the arithmetic expressions.

Operator Syntax Working

+ x+y Addition or summation of x and y.

- x-y Subtraction of y from x.

x xxy Multiplication or product of x and y.

/ x/y Division of x and y.

// x // y Quotient when x is divided by y.

% x%y Remainder when x is divided by y.

** x ** y Exponent (x to the power of y).

Example :

x = 10
y=5

addition = x + y
subtraction = x - y
product = x * y
division = x / y
power = x**y

print("The sum of x and y is: ", addition)


print("The difference between x and y is: ", subtraction)
print("The product of x and y is: ", product)
print("The division of x and y is: ", division)

Dr. Yusuf Perwej Page 58


print("x to the power y is: ", power)

Output :
The sum of x and y is: 15
The difference between x and y is: 5
The product of x and y is: 50
The division of x and y is: 2.0
x to the power y is: 100000
3. Integral Expressions

An integral expression in Python is used for computations and type conversion (integer to
float, a string to integer, etc.). An integral expression always produces an integer value as a
resultant.

Example :

x = 10 # an integer number
y = 5.0 # a floating point number

# we need to convert the floating-point number into an integer or vice versa for summation.
result = x + int(y)

print("The sum of x and y is: ", result)

Output :

The sum of x and y is: 15

4. Floating Expressions

A floating expression in Python is used for computations and type conversion (integer to float,
a string to integer, etc.). A floating expression always produces a floating-point number as a
resultant.

Example :

x = 10 # an integer number
y = 5.0 # a floating point number

# we need to convert the integer number into a floating-point number or vice versa for
summation.
result = float(x) + y
print("The sum of x and y is: ", result)

Output :

The sum of x and y is: 15.0

Dr. Yusuf Perwej Page 59


5. Relational Expressions

A relational expression in Python can be considered as a combination of two or more


arithmetic expressions joined using relational operators. The overall expression results in either
True or False (boolean result). We have four types of relational operators in Python
(i.e.>,<,>=,<=)(i.e.>,<,>=,<=).

A relational operator produces a boolean result so they are also known as Boolean Expressions.

For example :
10+15>20

In this example, first, the arithmetic expressions (i.e. 10+15 and 20) are evaluated, and then the
results are used for further comparison.

Example :

a = 25
b = 14
c = 48
d = 45

# The expression checks if the sum of (a and b) is the same as the difference of (c and d).
result = (a + b) == (c - d)
print("Type:", type(result))
print("The result of the expression is: ", result)

Output :

Type: <class 'bool'>

The result of the expression is: False

6. Logical Expressions

As the name suggests, a logical expression performs the logical computation, and the overall
expression results in either True or False (boolean result). We have three types of logical
expressions in Python, let us discuss them briefly.

Operator Syntax Working

and xx and yy The expression return True if both xx and yy are true, else it returns False.

or xx or yy The expression return True if at least one of xx or yy is True.

not not xx The expression returns True if the condition of xx is False.

Note :
In the table specified above, xx and yy can be values or another expression as well.

Example :

from operator import and_

Dr. Yusuf Perwej Page 60


x = (10 == 9)
y = (7 > 5)

and_result = x and y
or_result = x or y
not_x = not x

print("The result of x and y is: ", and_result)


print("The result of x or y is: ", or_result)
print("The not of x is: ", not_x)

Output :

The result of x and y is: False


The result of x or y is: True
The not of x is: True

7. Bitwise Expressions

The expression in which the operation or computation is performed at the bit level is known as a
bitwise expression in Python. The bitwise expression contains the bitwise operators.

Example :

x = 25
left_shift = x << 1
right_shift = x >> 1

print("One right shift of x results: ", right_shift)


print("One left shift of x results: ", left_shift)

Output :

One right shift of x results: 12

One left shift of x results: 50

8. Combinational Expressions

As the name suggests, a combination expression can contain a single or multiple expressions
which result in an integer or boolean value depending upon the expressions involved.

Example :

x = 25
y = 35

result = x + (y << 1)

print("Result obtained : ", result)

Output :

Result obtained: 95

Dr. Yusuf Perwej Page 61


Whenever there are multiple expressions involved then the expressions are resolved based on
their precedence or priority. Let us learn about the precedence of various operators in the
following section.

 Multiple Operators in Expression (Operator Precedence)

The operator precedence is used to define the operator's priority i.e. which operator will be
executed first. The operator precedence is similar to the BODMAS rule that we learned in
mathematics. Refer to the list specified below for operator precedence.

Precedence Operator Name

1. ()[]{} Parenthesis

2. ** Exponentiation

3. -value , +value , ~value Unary plus or minus, complement

4. / * // % Multiply, Divide, Modulo

5. +– Addition & Subtraction

6. >> << Shift Operators

7. & Bitwise AND

8. ^ Bitwise XOR

9. pipe symbol Bitwise OR

10. >= <= > < Comparison Operators

11. == != Equality Operators

12. = += -= /= *= Assignment Operators

13. is, is not, in, not in Identity and membership operators

14. and, or, not Logical Operators

Let us take an example to understand the precedence better :

x = 12
y = 14
z = 16

result_1 = x + y * z
print("Result of 'x + y + z' is: ", result_1)

result_2 = (x + y) * z
print("Result of '(x + y) * z' is: ", result_2)

result_3 = x + (y * z)

Dr. Yusuf Perwej Page 62


print("Result of 'x + (y * z)' is: ", result_3)

Output :

Result of 'x + y + z' is: 236

Result of '(x + y) * z' is: 416

Result of 'z + (y * z)' is: 236

 Difference between Statements and Expressions in Python

Statement in Python Expression in Python

A statement in Python is used for creating The expression in Python produces some value or result
variables or for displaying values. after being interpreted by the Python interpreter.

A statement in Python is not evaluated for


An expression in Python is evaluated for some results.
some results.

The execution of a statement changes the The expression evaluation does not result in any state
state of the variable. change.

A statement can be an expression. An expression is not a statement.

Example : x=3 Example: x=3+6


Output : 3 Output : 9

 Python Operator
 In Python programming, Operators in general are used to perform operations on values and
variables.
 Operators in Python are special symbols that facilitate operations on variables and values.
 They allow you to manipulate data, perform mathematical calculations, compare values, and
control the flow of your program.
 An operator is a symbol that represents an operation that may be performed on one or more
operands.
 Operators are constructs used to modify the values of operands.
 Operators that take one operand are called unary operators.
 Operators that take two operands are called binary operators.
 Python operators are divided into several types, each serving a distinct purpose.

i. Arithmetic operators.
ii. Assignment operators.
iii. Bitwise operators.
iv. Comparison operators.
v. Identity operators.
vi. Logical operators.
vii. Membership operators
viii. Ternary operator.

Dr. Yusuf Perwej Page 63


 Arithmetic operators: These operators are used to perform arithmetic operation such as
addition, subtraction, multiplication and division.

a=7
b=2
# addition
print ('Sum: ', a + b)
# subtraction
print ('Subtraction: ', a - b)
# multiplication
print ('Multiplication: ', a * b)
# division
print ('Division: ', a / b)
# floor division
print ('Floor Division: ', a // b)
# modulo
print ('Modulo: ', a % b)
# a to the power b
print ('Power: ', a ** b)
Output
Sum: 9
Subtraction: 5
Multiplication: 14
Division: 3.5
Floor Division: 3
Modulo: 1
Power: 49

 Comparison operators: These operators are used to compare values. It is also called relational
operators. The result of these operator is always a Boolean value i.e., true or false.

Dr. Yusuf Perwej Page 64


Example: The code compares the values of ‘a’ and ‘b’ using various comparison Python
operators and prints the results. It checks if ‘a’ is greater than, less than, equal to, not equal to,
greater than, or equal to, and less than or equal to ‘b’.

a = 13
b = 33

print(a > b)
print(a < b)
print(a == b)
print(a != b)
print(a >= b)
print(a <= b)

Output
False
True
False
True
False
True

 Assignment operators: This operator is used to store right side operands in the left side
operand.

Example: The code starts with ‘a’ and ‘b’ both having the value 10. It then performs a series of
operations: addition, subtraction, multiplication, and a left shift operation on ‘b’. The results of
each operation are printed, showing the impact of these operations on the value of ‘b’.

a = 10
b=a
print(b)
b += a
print(b)
b -= a
print(b)
b *= a
print(b)
b <<= a
Dr. Yusuf Perwej Page 65
print(b)

Output
10
20
10
100
102400
 Bitwise operators: These operators perform bit level operation on operands. Let us take two
operand x = 10 and y = 12. In binary format this can be written as x = 1010 and y = 1100.

Example: The code demonstrates various bitwise operations with the values of ‘a’ and ‘b’. It
performs bitwise AND (&), OR (|), NOT (~), XOR (^), right shift (>>), and left shift (<<)
operations and prints the results. These operations manipulate the binary representations of the
numbers.

a = 10
b=4
print(a & b)
print(a | b)
print(~a)
print(a ^ b)
print(a >> 2)
print(a << 2)

Output
0
14
-11
14
2
40
 Logical operators: These operators are used to check two or more conditions. The resultant of
this operator is always a Boolean value. Here x and y are two operands that store either true of
false Boolean values.

Dr. Yusuf Perwej Page 66


Example: The code performs logical operations with Boolean values. It checks if both ‘a’ and
‘b’ are true (‘and’), if at least one of them is true (‘or’), and negates the value of ‘a’ using ‘not’.
The results are printed accordingly.

a = True
b = False
print(a and b)
print(a or b)
print(not a)

Output
False
True
False

 Identity operators: These operator are used to check whether both operands are same or not.
Suppose x stores a value 20 and y stores a value 40. Then x is y returns false and x not is y return
true.

Example: The code uses identity operators to compare variables in Python. It checks if ‘a’ is not
the same object as ‘b’ (which is true because they have different values) and if ‘a’ is the same
object as ‘c’ (which is true because ‘c’ was assigned the value of ‘a’).

Python

a = 10
b = 20
c=a

print(a is not b)
print(a is c)

Output
True
True

Dr. Yusuf Perwej Page 67


 Membership operators:
 These operators are used to check an item or an element that is part of a string, a list or a
tuple.
 A membership operator reduces the effort of searching an element in the list.
 Suppose x stores a value 20 and y is the list containing items 10, 20, 30, and 40. Then x
is a part of the list y because the value 20 is in the list y.

Example: The code checks for the presence of values ‘x’ and ‘y’ in the list. It prints whether or
not each value is present in the list. ‘x’ is not in the list, and ‘y’ is present, as indicated by the
printed messages. The code uses the ‘in’ and ‘not in’ Python operators to perform these checks.

x = 24
y = 20
list = [10, 20, 30, 40, 50]

if (x not in list):
print("x is NOT present in given list")
else:
print("x is present in given list")

if (y in list):
print("y is present in given list")
else:
print("y is NOT present in given list")

Output
x is NOT present in given list
y is present in given list

 Ternary operator: Ternary operators also known as conditional expressions are operators that
evaluate something based on a condition being true or false. It was added to Python in version
2.5. It simply allows testing a condition in a single line replacing the multiline if-else making the
code compact.

Syntax : [on_true] if [expression] else [on_false]

Examples : The code assigns values to variables ‘a’ and ‘b’ (10 and 20, respectively). It then
uses a conditional assignment to determine the smaller of the two values and assigns it to the
variable ‘min’. Finally, it prints the value of ‘min’, which is 10 in this case.

a, b = 10, 20
min = a if a < b else b

print(min)
Dr. Yusuf Perwej Page 68
Output:

10

 Operator Precedence

In Python, operators have different levels of precedence, which determine the order in which
they are evaluated. When multiple operators are present in an expression, the ones with
higher precedence are evaluated first. In the case of operators with the same precedence,
their associativity comes into play, determining the order of evaluation.

Precedence Operators Description Associativity

()
1 Parentheses Left to right

x[index], x[index:index]
2 Subscription, slicing Left to right

await x
3 Await expression N/A

**
4 Exponentiation Right to left

+x, -x, ~x
5 Positive, negative, bitwise NOT Right to left

*, @, /, //, % Multiplication, matrix, division, floor division,


6 Left to right
remainder
+, –
7 Addition and subtraction Left to right

<<, >>
8 Shifts Left to right

&
9 Bitwise AND Left to right

^
10 Bitwise XOR Left to right

|
11 Bitwise OR Left to right

in, not in, is, is not, <, <=, >, >=, !=,
12 == Comparisons, membership tests, identity tests Left to Right

not x
13 Boolean NOT Right to left

and
14 Boolean AND Left to right

or
15 Boolean OR Left to right

if-else
16 Conditional expression Right to left
lambda
17 Lambda expression N/A

18 := Assignment expression (walrus operator) Right to left

 Operators Precedence Rule - PEMDAS

Dr. Yusuf Perwej Page 69


Operator precedence in python follows the PEMDAS rule for arithmetic expressions. The
precedence of operators is listed below in a high to low manner.

Firstly, parentheses will be evaluated, then exponentiation and so on.

 P – Parentheses
 E – Exponentiation
 M – Multiplication
 D – Division
 A – Addition
 S – Subtraction

In the case of tie means, if two operators whose precedence is equal appear in the expression,
then the associativity rule is followed.

Example
10 + 20 * 30

10 + 20 * 30 is calculated as 10 + (20 * 30)


and not as (10 + 20) * 30

# Precedence of '+' & '*'


expr = 10 + 20 * 30

print(expr)

Output
610

In the given code, the ‘if‘ block is executed even if the age is 0. Because the precedence of logical ‘and‘ is greater
than the logical ‘or‘.

# Precedence of 'or' & 'and'


name = "Goel"
age = 0
if name == "Goel" or name == "Gitm" and age >= 2:
print("Hello! Welcome.")
else:
print("Good Bye!!")

Output
Hello! Welcome.

Hence, To run the ‘else‘ block we can use parenthesis( ) as their precedence is highest among all the operators.
# Precedence of 'or' & 'and'
name = "Alex"

Dr. Yusuf Perwej Page 70


age = 0

if (name == "Alex" or name == "John") and age >= 2:


print("Hello! Welcome.")
else:
print("Good Bye!!")

Output
Good Bye!!

 Associativity Rule

All the operators, except exponentiation (**) follow the left to right associativity. It means the
evaluation will proceed from left to right, while evaluating the expression.

Example- (43+13−9/3∗7)

In this case, the precedence of multiplication and division is equal, but further, they will be
evaluated according to the left to right associativity.

 Interpreter encounters the parenthesis (. Hence it will be evaluated first.


 Later there are four operators +, −, ∗ and /.
 Precedence of (/, and ∗)>Precedence of (+,−).
 We can use the only operator precedence if all operators belong to different-different
levels from the hierarchy table, which is not the case in our example.
 Associativity rule will be followed for operators with the same precedence.
 This expression will be evaluated from left to right, 9/3∗7 = 3∗7= 21.
 Now, our expression has become 43+13−21.
 Left to right Associativity rule will be followed again. So, our final value of expression
will be, 43+13−21 = 56−21= 35.

Example:

In this code, ‘*’ and ‘/’ have the same precedence and their associativity is Left to Right, so
the expression “100 / 10 * 10” is treated as “(100 / 10) * 10”.

Dr. Yusuf Perwej Page 71


# Left-right associativity
# 100 / 10 * 10 is calculated as
# (100 / 10) * 10 and not
# as 100 / (10 * 10)
print(100 / 10 * 10)

# Left-right associativity
# 5 - 2 + 3 is calculated as
# (5 - 2) + 3 and not
# as 5 - (2 + 3)
print(5 - 2 + 3)

# left-right associativity
print(5 - (2 + 3))

# right-left associativity
# 2 ** 3 ** 2 is calculated as
# 2 ** (3 ** 2) and not
# as (2 ** 3) ** 2
print(2 ** 3 ** 2)

Output

100
6
0
512

 Comparison Operators

All comparison operations, such as <, >, ==, >=, <=, !=, is, and in, have the same priority, which
is lower than arithmetic, shifting, and bitwise operations. Unlike in C, Python follows the
conventional mathematical interpretation for expressions like a < b < c.

Comparisons in Python produce boolean values, either True or False.

Python allows chaining of comparisons, such as x < y <= z, which is equivalent to x < y and y
<= z. It's important to note that while y is only evaluated once in the chain, z is not evaluated at
all if x < y is found to be false.

a = 100
b = 80
c = 80
d = 19
print(a > b == c >= d)

Output:

True

Dr. Yusuf Perwej Page 72


Explanation: Before evaluating the expression a > b == c >= d, it's important to note that
comparison operators in Python have equal precedence and are evaluated from left to right. The
expression is transformed based on the comparison chaining rule:

The expression a > b == c >= d is equivalent to (a > b) and (b == c) and (c >= d).

 The expression is evaluated from left to right. The first comparison a > b is performed.
Since a is 100 and b is 80, the result is True.
 Next, the second comparison b == c is evaluated. Both b and c have the value 80, so this
comparison is also True.
 Finally, the last comparison c >= d is checked. Since c is 80 and d is 19, the condition
holds True.
 Evaluating the chained comparisons in order, we have True and True and True, which
results in the final output of True.

Note that comparisons, membership tests, and identity tests, all have the same precedence and
have a left-to-right chaining feature.

 Boolean Expression

Python Boolean type is one of the built-in data types provided by Python, which represents
one of the two values i.e. True or False. Generally, it is used to represent the truth values of
the expressions.

Example
Input: 1==1
Output: True

Input: 2<1
Output: False

Example

# Declaring variables
a = 10
b = 20

# Comparing variables
print(a == b)

Output:

False

Dr. Yusuf Perwej Page 73


 Memory is managed in Python

 Memory management in Python involves a private heap containing all Python objects
and data structures. The management of this private heap is ensured internally by the
Python memory manager.
 The Python memory manager has different components which deal with various dynamic
storage management aspects, like sharing, segmentation, preallocation or caching.
 At the lowest level, a raw memory allocator ensures that there is enough room in the
private heap for storing all Python-related data by interacting with the memory manager
of the operating system.
 On top of the raw memory allocator, several object-specific allocators operate on the
same heap and implement distinct memory management policies adapted to the
peculiarities of every object type.
 For example, integer objects are managed differently within the heap than strings, tuples
or dictionaries because integers imply different storage requirements and speed/space
tradeoffs.
 The Python memory manager thus delegates some of the work to the object-specific
allocators, but ensures that the latter operate within the bounds of the private heap.
 It is important to understand that the management of the Python heap is performed by the
interpreter itself and that the user has no control over it, even if they regularly manipulate
object pointers to memory blocks inside that heap.
 The allocation of heap space for Python objects and other internal buffers is performed
on demand by the Python memory manager through the Python API functions.

 Python Enhancement Proposal (PEP)

PEP stands for Python Enhancement Proposal. A PEP is a design document providing
information to the Python community, or describing a new feature for Python or its processes or
environment. The PEP should provide a concise technical specification of the feature and a
rationale for the feature.

PEPs to be the primary mechanisms for proposing major new features, for collecting community
input on an issue, and for documenting the design decisions that have gone into Python. The PEP
author is responsible for building consensus within the community and documenting dissenting
opinions.

Because the PEPs are maintained as text files in a versioned repository, their revision history is
the historical record of the feature proposal. This historical record is available by the normal git
commands for retrieving older revisions, and can also be browsed on GitHub.

 PEP Audience

The typical primary audience for PEPs are the core developers of the CPython reference
interpreter and their elected Steering Council, as well as developers of other implementations of
the Python language specification.

However, other parts of the Python community may also choose to use the process to document
expected API conventions and to manage complex design coordination problems that require
collaboration across multiple projects.

 PEP Types
Dr. Yusuf Perwej Page 74
There are three kinds of PEP:

1. A Standards Track PEP describes a new feature or implementation for Python. It may
also describe an interoperability standard that will be supported outside the standard
library for current Python versions before a subsequent PEP adds standard library support
in a future version.
2. An Informational PEP describes a Python design issue, or provides general guidelines
or information to the Python community, but does not propose a new feature.
Informational PEPs do not necessarily represent a Python community consensus or
recommendation, so users and implementers are free to ignore Informational PEPs or
follow their advice.
3. A Process PEP describes a process surrounding Python, or proposes a change to (or an
event in) a process. Process PEPs are like Standards Track PEPs but apply to areas other
than the Python language itself. They may propose an implementation, but not to
Python’s codebase; they often require community consensus; unlike Informational PEPs,
they are more than recommendations, and users are typically not free to ignore them.
Examples include procedures, guidelines, changes to the decision-making process, and
changes to the tools or environment used in Python development. Any meta-PEP is also
considered a Process PEP.

Dr. Yusuf Perwej Page 75

You might also like