Python Chapter 01
What is Python?
● Python is a very popular general-purpose, interpreted,
interactive, object-oriented, and high-level programming
language.
● Python is dynamically-typed and garbage-collected programming
language.
● It supports procedural, object-oriented, and functional
programming.
● It was created by Guido van Rossum during 1985- 1990.
● Like Perl, Python source code is also available under the GNU
General Public License (GPL).
Python is a high-level, general-purpose, and very popular
programming language. Python programming language (latest Python
3) is being used in web development, and Machine Learning
applications, along with all cutting-edge technology in the Software
Industry. Python language is being used by almost all tech-giant
companies like – Google, Amazon, Facebook, Instagram, Dropbox,
Uber… etc.
Use of Python
It is used for:
● software development,
● system scripting.
● Python can be used on a server to create web applications.
● Python can be used alongside software to create workflows.
● Python can connect to database systems. It can also read and
modify files.
● Python can be used to handle big data and perform complex
mathematics.
● Python can be used for rapid prototyping, or for
production-ready software development.
NumPy, Pandas, and Matplotlib.
● Data Visualization : Python is used in Data Visualization to
create plots and graphical representations. Data visualization is
thrt of representing information and data through visual
elements like charts, graphs, and maps.
● Data Analytics : Python helps in Data Analytics to analyze
and understand raw data for insights and trends.
● Artificial intelligence and Machine Learning: It is used in
AI and Machine Learning to simulate human behavior and to
learn from past data without hard coding. 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 development : 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.
● Database management : It can be used to handle
databases. I SQLite3 , SQLAlchemy are useful libraries
● Business and accounting : It is used in business and
accounting to perform complex mathematical operations along
with quantitative and qualitative analysis.
● 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.
● 3D CAD Applications: Python can be used for 3D
computer-aided design (CAD) applications through libraries
such as Blender.
● IoT: Python is used in IoT for developing scripts and
applications for devices like Raspberry Pi, Arduino, and others.
● 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.
Data Science and Machine Learning: Python's libraries like
NumPy, Pandas, and Scikit-learn make it a go-to language for data
analysis, machine learning algorithms and data visualization.
Datascience / Machine Learning
Db management
Web dev.
Audio and music
Cad applications
Computer vision or Image processing activities
Features of Python
● Simple ,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.
● Interpreted - Python code first gets compiled into bytecode,
and then interpreted line by line making debugging easier.
● High-level - High-level language means human readable code.
● Purely Object-Oriented - It refers to everything as an object,
including numbers and strings.
● 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.
● Garbage Collected - Memory allocation and deallocation are
automatically managed. Programmers do not specifically need to
manage the memory.
● Open Source - Python is an open-source, cost-free
programming language. It is utilized in several sectors and
disciplines as a result.
● Platform Independent / 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. Some of
the popular libraries include NumPy, Tensorflow, Selenium,
OpenCV, etc.
● Case Sensitive : Python is a case-sensitive language, which
means that uppercase and lowercase letters are treated
differently. For example, 'name' and 'Name' are two different
variables in Python.
1. Simple, easy to use and learn
2. High level language
3. Object oriented
4. Interpreted
5. Dynamically typed
6. Garbage collected
7. Open source
8. Platform independent / cross platform compatibility
9. Rich standard library
10. Case sensitive
History of Python
Python was created by a Dutch programmer Guido van Rossum.
In the late 1980s, Guido van Rossum, a Dutch programmer, began
working on Python while at the Centrum Wiskunde & Informatica
(CWI) in the Netherlands. It was started as a hobby project because
he was looking for an interesting project to keep him occupied during
Christmas.
He wanted to create a successor to the ABC programming language
which had interfacing with the Amoeba Operating System and had the
feature of exception handling. He had already helped create ABC
earlier in his career and had seen some issues with ABC but liked most
of the features. After that what he did was very clever. He had taken
the syntax of ABC, and some of its good features. It came with a lot of
complaints too, so he fixed those issues completely and created a good
scripting language that had removed all the flaws. He wanted to create
a programming language that would be easy to read and efficient.
In February 1991, the first public version of Python, version 0.9.0, was
released. This marked the official birth of Python as an open-source
project. The language was named after the British comedy series
"Monty Python's Flying Circus".
Python development has gone through several stages. In January
1994, Python 1.0 was released as a usable and stable programming
language. This version included many of the features that are still
present in Python today.
From the 1990s to the 2000s, Python gained popularity for its
simplicity, readability, and versatility. In October 2000, Python 2.0 was
released. Python 2.0 introduced list comprehensions, garbage
collection, and support for Unicode.
In December 2008, Python 3.0 was released. Python 3.0 introduced
several backward-incompatible changes to improve code readability
and maintainability.
Throughout the 2010s, Python's popularity increased, particularly in
fields like data science, machine learning, and web development. Its
rich ecosystem of libraries and frameworks made it a favorite among
developers.
The Python Software Foundation (PSF) was established in 2001 to
promote, protect, and advance the Python programming language and
its community.
https://www.geeksforgeeks.org/history-of-python/
https://www.tutorialspoint.com/python/python_history.htm
https://www.javatpoint.com/python-history
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.
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 print() Function:
Python print() function is used to display output to the console or terminal.
It allows us to display text, variables and other data in a human readable
format.
Syntax:
print(object(s), sep=separator, end=end, file=file, flush=flush)
It takes one or more arguments separated by comma(,) and adds a 'newline'
at the end by default.
Parameters:
○ object(s) - As many as you want data to display, will first converted
into string and printed to the console.
○ sep - Separates the objects by a separator passed, default value = " ".
○ end - Ends a line with a newline character
○ file - a file object with write method, default value = sys.stdout
Example:
1. # Displaying a string
2. print("Hello, World!")
3.
4. # Displaying multiple values
5. name = "Aman"
6. age = 21
7. print("Name:", name, "Age:", age)
8.
9. # Printing variables and literals
10. x=5
11. y=7
12. print("x =", x, "y =", y, "Sum =", x + y)
13.
14. # Printing with formatting
15. percentage = 85.75
16. print("Score: {:.2f}%".format(percentage))
Output:
Hello, World!
Name: Aman Age: 21
X = 5 y = 7 Sum = 12
Score: 85.75%
In this example, the print statement is used to print string, integer, and float
values in a human readable format.
The print statement can be used for debugging, logging and to provide
information to the user.
Python Indentation
Indentation refers to the spaces at the beginning of a code line.
Where in other programming languages the indentation in code is
for readability only, the indentation in Python is very important.
Python uses indentation to indicate a block of code.The number of
spaces is up to you as a programmer, but it has to be at least one.
Python indentation is a way of telling a Python interpreter that
the group of statements which statements belong together and
are part of the same conditional statement, loop, or function.
Example :
Python will give you an error if you skip the indentation:
if 5 > 2:
print("Five is greater than two!")
Output : Error
You need to use Indentation to define the block of code
if 5 > 2:
print("Five is greater than two!")
You have to use the same number of spaces in the same
block of code, otherwise Python will give you an error:
Example :
if 5 > 2:
print("Five is greater than two!")
print("Five is greater than two!")
Output : Error
Example of Python Indentation
Statement (line 1), if condition (line 2), and statement (last
line) belongs to the same block which means that after
statement 1, if condition will be executed. and suppose the
if condition becomes False then the Python will jump to the
last statement for execution.
The nested if-else belongs to block 2 which means that if
nested if becomes False, then Python will execute the
statements inside the else condition.
Statements inside nested if-else belong to block 3 and only
one statement will be executed depending on the if-else
condition.
Python Comments
Comments in Python are the lines in the code that are ignored by the interpreter
during the execution of the program.
# I am single line comment
""" Multi-line comment used
print("Python Comments") """
Comments enhance the readability of the code and help the 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.
Comments can be used to prevent execution when testing code.
Types of Comments in Python
There are three types of comments in Python:
● Single line Comments
● Multiline Comments
● String Literals
● Docstring Comments
Creating a Comment
Comments starts with a #, and Python will ignore them:
#This is a comment
print("Hello, World!")
Comments can be placed at the end of a line, and Python will
ignore the rest of the line:
print("Hello, World!") #This is a comment
A comment does not have to be text that explains the code, it can
also be used to prevent Python from executing code:
#print("Hello, World!")
print("Cheers, Mate!")
Multiline Comments
Python does not really have a syntax for multiline comments.
To add a multiline comment you could insert a # for each line:
Example
#This is a comment
#written in
#more than just one line
print("Hello, World!")
Or, not quite as intended, you can use a multiline string.
Since Python will ignore string literals that are not assigned to a
variable, you can add a multiline string (triple quotes) in your
code, and place your comment inside it:
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")
As long as the string is not assigned to a variable, Python will
read the code, but then ignore it, and you have made a multiline
comment.
Why are Comments Used in Python?
Comments have been an integral part of programming languages, and every language
have different ways of using comments.
Just like any other language, comments in Python serve following purpose:
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.
https://www.google.com/amp/s/www.geeksforgeeks.org/python-
comments/amp/
https://www.javatpoint.com/python-comments
Python Variables
Variables
● Variables are containers for storing data values.
● Python is not “statically typed”. It's a dynamically typed
language.We do not need to declare variables before using
them or declare their type.
● A variable is created the moment we first assign a value to
it. A Python variable is a name given to a memory location.
● It is the basic unit of storage in a program.
● An Example of a Variable in Python is a representational
name that serves as a pointer to an object.
● Once an object is assigned to a variable, it can be referred
to by that name. In layman’s terms, we can say that
Variable in Python is containers that store values.
Creating Variables
Python has no command for declaring a variable.
A variable is created the moment you first assign a value to it.
Example:
x=5
y = "John"
print(x)
print(y)
Here, x is a variable which stores 5 and a y is a variable which stores
“John”and when we call its name the stored information will get
printed.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)
The value stored in a variable can be changed during program
execution.
A Variables in Python is only a name given to a memory location,
all the operations done on the variable effects that memory
location.
Casting
If you want to specify the data type of a variable, this can be
done with casting.
Example
x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0
Get the Type
You can get the data type of a variable with the type() function.
Example:
x=5
y = "John"
print(type(x))
print(type(y))
Single or Double Quotes?
String variables can be declared either by using single or double
quotes:
Example
x = "John"
# is the same as
x = 'John'
Case-Sensitive
Variable names are case-sensitive.
Example :
a = 4
A = "Sally"
#A will not overwrite a
Variable Names
A variable can have a short name (like x and y) or a more descriptive
name (age, carname, total_volume). Rules for Python variables:
● A variable name must start with a letter or the underscore
character
● A variable name cannot start with a number
● A variable name can only contain alpha-numeric characters
and underscores (A-z, 0-9, and _ )
● Variable names are case-sensitive (age, Age and AGE are
three different variables)
● A variable name cannot be any of the python keywords.
Example:
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"
Illegal Variable names
2myvar = "John"
my-var = "John"
my var = "John"
Remember that variable names are case-sensitive.
Multi Words Variable Names
Variable names with more than one word can be difficult to read.
There are several techniques you can use to make them more
readable:
Camel Case
Each word, except the first, starts with a capital letter:
myVariableName = "John"
Pascal Case
Each word starts with a capital letter:
MyVariableName = "John"
Snake Case
Each word is separated by an underscore character:
my_variable_name = "John"
Many Values to Multiple Variables
Python allows you to assign values to multiple variables in one
line:
Example
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
Note: Make sure the number of variables matches the number of
values, or else you will get an error.
One Value to Multiple Variables
And you can assign the same value to multiple variables in one
line:
Example
x = y = z = "Orange"
print(x)
print(y)
print(z)
Unpack a Collection
If you have a collection of values in a list, tuple etc. Python allows
you to extract the values into variables. This is called unpacking.
Example
Unpack a list:
fruits = ["apple", "banana", "cherry"]
x, y, z = fruits
print(x)
print(y)
print(z)
Output :
Apple
Banana
Cherry
Output Variables
The Python print() function is often used to output variables.
Example
Get your own Python Server
x = "Python is awesome"
print(x)
In the print() function, you output multiple variables, separated
by a comma:
Example:
x = "Python"
y = "is"
z = "awesome"
print(x, y, z)
Output :
Python is awesome
Try it Yourself »
You can also use the + operator to output multiple variables:
Example
x = "Python "
y = "is "
z = "awesome"
print(x + y + z)
Output : Python is awesome
Try it Yourself »
Notice the space character after "Python " and "is ", without them the
result would be "Pythonisawesome".
x = "Python"
y = "is"
z = "awesome"
print(x + y + z)
Output : Pythonisawesome
For numbers, the + character works as a mathematical operator:
Example
x=5
y = 10
print(x + y)
Try it Yourself »
In the print() function, when you try to combine a string and a
number with the + operator, Python will give you an error:
Example
x=5
y = "John"
print(x + y)
Try it Yourself »
The best way to output multiple variables in the print() function is
to separate them with commas, which even support different data
types:
Example
x=5
y = "John"
print(x, y)
Output : 5 John
Global and Local Python Variables
Local variables in Python are the ones that are defined and
declared inside a function. We can not call this variable outside
the function.
Python3
# This function uses global variable s
def f():
s = "Welcome geeks"
print(s)
f()
Output:
Welcome geeks
Global variables in Python are the ones that are defined and
declared outside a function, and we need to use them inside a
function.
Python3
# This function has a variable with
# name same as s
def f():
print(s)
# Global scope
s = "I love Geeksforgeeks"
f()
Output:
I love Geeksforgeeks
Global keyword in Python
Python global is a keyword that allows a user to modify a variable
outside of the current scope. It is used to create global variables
from a non-global scope i.e inside a function. Global keyword is
used inside a function only when we want to do assignments or
when we want to change a variable. Global is not needed for
printing and accessing.
LEARN : Rules of global keyword
● If a variable is assigned a value anywhere within the
function’s body, it’s assumed to be local unless explicitly
declared as global.
● Variables that are only referenced inside a function are
implicitly global.
● We use a global in Python to use a global variable inside a
function.
● There is no need to use a global keyword in Python
outside a function.
Example: Python program to modify a global value inside a
function.
Output :
Initial counter value: 0
Counter value after increment: 1
Python Keywords
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.
Python has a set of keywords that are reserved words that cannot
be used as variable names, function names, or any other
identifiers:
Keyword Description
and A logical operator
as To create an alias
assert For debugging
break To break out of a loop
class To define a class
continue To continue to the next iteration of a loop
def To define a function
del To delete an object
elif Used in conditional statements, same as else if
else Used in conditional statements
except Used with exceptions,
what to do when an exception occurs
False Boolean value, result of comparison operations
finally Used with exceptions,a block of code that will
be executed no matter if an exception occurs
Or not
for To create a for loop
from To import specific parts of a module
global To declare a global variable
if To make a conditional statement
import To import a module
in To check if a value is
present in a list, tuple, etc.
is To test if two variables are equal
lambda To create an anonymous function
None Represents a null value
nonlocal To declare a non-local variable
not A logical operator
or A logical operator
pass A null statement, a statement that will do nothing
raise To raise an exception
return To exit a function and return a value
True Boolean value, result of comparison operations
try To make a try...except statement
while To create a while loop
with Used to simplify exception handling
yield To return a list of values from a generator
True, False, None Keyword in Python
● True: This keyword is used to represent a boolean true. If a
statement is true, “True” is printed.
● False: This keyword is used to represent a boolean false. If a
statement is false, “False” is printed.
● None: This is a special constant used to denote a null value or a
void. It’s important to remember, 0, any empty container(e.g. empty
list) does not compute to None.
It is an object of its datatype – NoneType. It is not possible to create
multiple None objects and can assign them to variables.
True, False, and None Use in Python
● False is 0, and True is 1.
● True + True + True is 3.
● True + False + False is 1.
● None isn’t equal to 0 or an empty list ([]).
print(False == 0)
print(True == 1)
print(True + True + True)
print(True + False + False)
print(None == 0)
print(None == [])
Output
True
True
False
False
https://www.geeksforgeeks.org/python-keywords/
Identifiers in Python
Identifier is a user-defined name given to a variable, function,
class, module, etc. The identifier is a combination of character
digits and an underscore. They are case-sensitive i.e., ‘num’ and
‘Num’ and ‘NUM’ are three different identifiers in python. It is a
good programming practice to give meaningful names to
identifiers to make the code understandable.
We can also use the Python string isidentifier() method to check
whether a string is a valid identifier or not.
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.
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:
● var1
● _var1
● _1_var
● var_1
Invalid Identifiers
● !var1
● 1var
● 1_var
● var#1
● var 1
Python Datatypes
Built-in Data Types
In programming, data type is an important concept.
Variables can store data of different types, and different types can do different
things.
Python has the following data types built-in by default, in these categories:
Text Type: str
Numeric Types: int, float, complex
Sequence Types: list, tuple, range
Mapping Type: dict
Set Types: set, frozenset
Boolean Type: bool
Binary Types: bytes, bytearray,
memoryview
None Type: NoneType
Numeric , text , sequence , boolean , mapping ,
noneType ,set , binary
Getting the Data Type
You can get the data type of any object by using the type()
function:
x=5
print(type(x))
https://www.w3schools.com/python/python_numbers.asp
https://www.geeksforgeeks.org/python-data-types/
In Python, the bytes datatype is used to handle binary data. It's essentially a
sequence of bytes, which are 8-bit numbers ranging from 0 to 255. Here’s a basic
example of how to use the bytes datatypeThe b prefix in byte_data = b'hello world'
is used to denote that the string is a bytes literal
byte_data = b'hello world’ #o/p : b'hello world’
In Python, a bytearray is a mutable sequence of bytes, similar to a bytes object,
but it can be modified after creation. You can think of a bytearray as a list of bytes
that you can change, whereas a bytes object is immutable.
Byte_array = bytearray(b'hello world')
Python Operators
https://www.geeksforgeeks.org/python-operators/
In Python programming, Operators in general are used to perform
operations on values and variables. These are standard symbols
used for logical and arithmetic operations. In this article, we will
look into different types of Python operators.
● OPERATORS: These are the special symbols. Eg- + , * , /,
etc.
● OPERAND: It is the value on which the operator is applied.
Operators are used to perform operations on variables and
values.
Python divides the operators in the following groups:
● Arithmetic operators
● Assignment operators
● Comparison operators
● Logical operators
● Identity operators
● Membership operators
● Bitwise operators
Arithmetic Operators in Python
Python Arithmetic operators are used to perform basic mathematical
operations like addition, subtraction, multiplication, and division.
In Python 3.x the result of division is a floating-point while in Python 2.x
division of 2 integers was an integer. To obtain an integer result in Python 3.x
floored (// integer) is used.
Operator Description Syntax
Addition: adds two
+ x+y
operands
Subtraction: subtracts
– x–y
two operands
Multiplication:
* multiplies two x*y
operands
Division (float): divides
/ the first operand by x/y
the second
Division (floor): divides
// the first operand by x // y
the second
Modulus: returns the
remainder when the
% x%y
first operand is divided
by the second
Power: Returns first
** x ** y
raised to power second