Python Notes - 1 Unit - 240416 - 143609
Python Notes - 1 Unit - 240416 - 143609
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.
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
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.
Basis of
Compiler Interpreter
difference
Running time Compiled code run faster Interpreted code run slower
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.
Pertaining
C, C++, C#, Scala, Java all use
Programming PHP, Perl, Ruby uses an interpreter.
complier.
languages
FAQs
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.
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.
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
1. Bytecode Interpreter
2. Threaded code Interpreter
3. Abstract syntax tree Interpreter
4. Just-in-time compilation
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.
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
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.
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.
print("Hello GFG")
Output:
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.
# 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.
Output:
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.
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”.
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.
In order to execute “Hello gfg” using script mode we first make a file and save it.
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:
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.
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.
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.
The interactive mode is more suitable Script mode is more suitable for writing long
for writing very short programs. programs.
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.
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.
Python has wide range of libraries and frameworks widely used in various fields such as
machine learning, artificial intelligence, web applications, etc. We define some popular
frameworks and libraries of Python as follows.
Python 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.
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.
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.
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.
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.
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:
no=10
my_function = my_decorator(my_function, no)
print ("It is ",my_function(no))
Output
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:
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
# sample comment
name = "GITM"
print(name)
Comments have been an integral part of programming languages, and every language have
different ways of using comments.
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.
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.
We can multiple hashtags (#) to write multiline comments in Python. Each and every line will be
considered as a single-line comment.
print("Multiline comments")
Python ignores the string literals that are not assigned to a variable so we can use these string
literals as Python Comments.
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.
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.
Note- Some of the tips you can follow, to make your comments effective are:
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
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
[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"
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
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”.
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.
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.
Example
Output
1
2
3
4
One
Two
else block execute
else block execute
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
2
3
4
5
6
# 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
# create a list
l = ['a', 'b', 'c', 'd', 'e']
del l[2]
# declare a variable
gvar = 10
# create a function
# declare fun2()
def fun2():
# declare global value gvar
global gvar
gvar = 100
# call fun1()
fun1()
# call fun2()
fun2()
Output
10
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
import math
print("factorial of 5 is :", math.factorial(5))
Output
factorial of 5 is : 120
x = 10
y = 20
z=x
print(x is z)
print(x is y)
Output
True
False
# code
import asyncio
def main():
result = asyncio.run(factorial(5))
print(result)
if __name__ == "__main__":
main()
Output
120
Python Variables
Python 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.
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.
a = 50
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:
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
name = "A"
Name = "B"
naMe = "C"
NAME = "D"
n_a_m_e = "E"
_name = "F"
name_ = "G"
_name_ = "H"
na56me = "I"
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.
Multiple Assignment
Multiple assignments, also known as assigning values to multiple variables in a single statement,
is a feature of Python.
x=y=z=50
print(x)
print(y)
print(z)
Output:
50
50
50
a,b,c=5,10,15
print a
print b
print c
Output:
5
10
15
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'>
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.
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
def f():
# local variable
s = "I love Goel"
print(s)
# Driver code
f()
Output
I love Goel
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
These are those which are defined outside any function and which are accessible throughout the
program, i.e., inside and outside of every function.
# Global scope
s = "I love Goel"
f()
print("Outside Function", s)
Output
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.
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.
# 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.
# 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.
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:
# 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.
# 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
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
Scope Can be access throughout the code Can access only inside the function
Parameters
parameter passing is not necessary parameter passing is necessary
needed
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 -
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
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 = 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.
We can print numerous factors inside the single print explanation. The examples of single and
multiple printing values are provided below.
Output:
5
5
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
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.
Keywords.
Identifiers.
Literals.
Operators.
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.
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'>
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
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.
print(String1)
print(String1)
print(type(String1))
print(String1)
print(type(String1))
String1 = '''Gitm
For
Life'''
print(String1)
Output:
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(String1)
print(String1[0])
print(String1[-1])
Output:
Initial String:
GoelsForGitms
First character of String is:
G
Last character of String is:
s
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.
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(List)
print(List)
print(List[0])
print(List[2])
print(List)
Output:
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.
print(List[0])
print(List[2])
print(List[-1])
print(List[-3])
Output:
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.
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(Tuple1)
list1 = [1, 2, 4, 5, 6]
print(tuple(list1))
Tuple1 = tuple('Gitms')
print(Tuple1)
Tuple1 = (0, 1, 2, 3)
print(Tuple3)
Output:
Note – The creation of a Python tuple without the use of parentheses is known as Tuple Packing.
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.
print(tuple1[0])
print(tuple1[-1])
print(tuple1[-3])
Output:
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'>
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.
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(set1)
set1 = set("GoelsForGitms")
print(set1)
print(set1)
print(set1)
Output:
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
print(set1)
for i in set1:
print("Goels" in set1)
Output:
Initial set
{'Goels', 'For', 'Gitms'}
Elements of set:
Goels For Gitms True
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’.
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(Dict)
print(Dict)
print(Dict)
print(Dict)
print(Dict)
Output:
Empty 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’.
print(Dict['name'])
print(Dict.get(3))
Output:
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:
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
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"
Output:
# initializing integer
s = '4'
c = ord(s)
print (c)
c = hex(56)
print (c)
c = oct(56)
print (c)
Output:
# initializing string
s = 'goels'
Output:
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))
Output:
a = chr(76)
b = chr(77)
print(a)
print(b)
Output:
L
M
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
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
print(x)
Output :
35
Example :
a = 25 # a statement
print(a) # a statement
Output :
25
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
Variable = Expression
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
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 :
Output :
2. Arithmetic Expressions
Example :
x = 10
y=5
addition = x + y
subtraction = x - y
product = x * y
division = x / y
power = x**y
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)
Output :
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 :
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 :
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.
and xx and yy The expression return True if both xx and yy are true, else it returns False.
Note :
In the table specified above, xx and yy can be values or another expression as well.
Example :
and_result = x and y
or_result = x or y
not_x = not x
Output :
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
Output :
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)
Output :
Result obtained: 95
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.
1. ()[]{} Parenthesis
2. ** Exponentiation
8. ^ Bitwise XOR
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)
Output :
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.
The execution of a statement changes the The expression evaluation does not result in any state
state of the variable. change.
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.
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.
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.
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
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.
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.
()
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
<<, >>
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
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
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‘.
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"
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.
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”.
# 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.
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
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
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.
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.