python unit 1
python unit 1
Python
Python is a popular programming language which was created by Guido van Rossum and
released in 1991.
Python works on different platforms (Windows, Mac, Linux, Raspberry Pi etc).
Python has a simple syntax similar to the English language.
Python has syntax that allows developers to write programs with fewer lines than some other
programming languages
Python code can connect to database systems.
Python is also versatile and widely used in every technical field, such as Machine Learning,
Artificial Intelligence, Web Development, Mobile Application, Desktop Application,
Scientific Calculation.
Data Analysis and Processing, Artificial Intelligence, Games, Sensor/Robots are the general
areas where Python is widely used.
History of python
There is a fact behind choosing the name of python.
Guido van Rossum was reading the script of a popular BBC comedy series "Monty
Python's Flying Circus" which was late on-air 1970s.
Van Rossum wanted to select a name which unique, sort, and little-bit mysterious, So he
decided to select naming Python after the "Monty Python's Flying Circus" for their newly
created programming language.
The implementation of Python was started in December 1989 by Guido Van Rossum at CWI
in Netherland.
In February 1991, Guido Van Rossum published the code (labeled version 0.9.0) to
alt.sources.
In 1994, Python 1.0 was released with new features like lambda, map, filter, and reduce.
Python 2.0 added new features such as list comprehensions, garbage collection systems.
On December 3, 2008, Python 3.0 (also called "Py3K") was released and much more comes.
ANKUR 1
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA
Features of python
1. Easy to learn and use
Python is easy to learn as compared to other programming languages.
Its syntax is straightforward and much the same as the English language.
There is no use of the semicolon or curly-bracket, the indentation defines the code block.
It is the recommended programming language for beginners.
3. Expressive Language
Python can perform complex tasks using a few lines of code.
A simple example, the hello world program you simply type print("Hello World"), In which
it will take only one line to execute, while Java or C takes multiple lines.
4. Object-Oriented Language
Python supports object-oriented language and concepts of classes and objects.
It supports inheritance, polymorphism, and encapsulation, etc.
The object-oriented procedure helps to programmer to write reusable code and develop
applications in less code.
5. Portable language
Python language is also a portable language. For example, if we have python code for
windows and if we want to run this code on other platforms such as Linux, Unix, and Mac
then we do not need to change it, we can run this code on any platform.
6. Integrated language
It can be easily integrated with languages like C, C++, and JAVA.
Python code runs line by line like C, C++, and JAVA which makes easy to debug the code.
7. Interpreted Language
Python program is executed one line at a time.
The advantage of being interpreted language, it makes debugging easy and portable.
8. High-Level Language
Programmers write in high-level languages because they are easier to understand and are less
complex than machine code.
ANKUR 2
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA
They allow the programmer to focus on what needs to be done, rather than on how the
computer actually works.
9. Extensible
It implies that other languages such as C/C++ can be used to compile the code and thus it can
be used further in our Python code.
It converts the program into byte code, and any platform can use that byte code.
ANKUR 3
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA
Following Figure shows the role of virtual machine in converting byte code instructions into
machine code:
The Python source code goes through the following to generate an executable code :
STEP 1: The python compiler reads a python source code or instruction. Then it verifies
that the instruction is well-formatted, i.e. it checks the syntax of each line. If it encounters
an error, it immediately halts the translation and shows an error message.
STEP 2: If there is no error, i.e. if the python instruction or source code is well-formatted
then the compiler translates it into its equivalent form in an intermediate language called
“Byte code”.
STEP 3: Byte code is then sent to the Python Virtual Machine(PVM) which is the python
interpreter. PVM converts the python byte code into machine-executable code. If an error
occurs during this interpretation then the conversion is halted with an error message.
ANKUR 4
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA
Indentation in Python
Most of the programming languages like C, C++ and Java use braces { } to define a block of
code, But Python uses indentation.
A code block (body of a function, loop, etc.) starts with indentation and ends with the first
unindented line.
The amount of indentation is up to you, but it must be consistent throughout that block.
Generally, four whitespaces are used for indentation and are preferred over tabs.
Indentation can be ignored in line continuation, but it's always a good idea to indent.
Incorrect indentation will result in IndentationError.
Here is an example of indentation which displays hii Daksh as output..
name = ‘Daksh’
if name == ‘Daksh’ :
print(‘hii Daksh….’)
else:
print(‘string not match’)
Python comments
Comments are very important while writing a program.
They describe what is going on inside a program, so that a person looking at the source code
does not have a hard time figuring it out.
In Python, we use the hash (#) symbol to start writing a comment.
Comments are for programmers to better understand a program.
Python Interpreter ignores comments.
#This is a comment
#print out Hello
print('Hello')
Another way of doing this is to use triple quotes, either ''' or """.
These triple quotes are used as a multi-line comment.
"""This is also a
perfect example of
multi-line comments"""
ANKUR 5
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA
Memory management is
Memory Memory management needs to be
automatically handled in Python. by
Management done manually in C.
the Garbage Collector provided by it.
ANKUR 6
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA
Built-in The number of built-in functions in C There are a lot of built-in functions
functions are very limited. in Python.
ANKUR 7
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA
Compilation & C is only compiled and not Java is both compiled and
Interpretation interpreted. interpreted.
Pointers C has support for pointers. Java does not support pointers.
Free( ) is used for freeing the A compiler will free up the memory
Free the memory in C. internally by calling the garbage
Memory collector.
ANKUR 8
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA
File Extension C codes are stored with the .c file Java codes are stored with the .java
extension. file extension.
datatypes Union and structure datatypes are Java does not supports union and
supported by C. structures.
Members Default members of C are public. Java’s default members are private.
ANKUR 9
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA
ANKUR 10
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA
ANKUR 11
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA
1. Reference counting
The references are always counted and stored in memory.
In the example below, we assign c to 50. Even if we assign a new variable with same value,
the reference count increases by 1!
Every object has its own ID, we print the IDs of objects to check they are same or different.
ANKUR 12
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA
As you can see above, del() statement doesn’t delete objects, it removes the name (and
reference) to the object.
When the reference count is zero, the object is deleted from the system by the garbage
collection.
There are advantages and disadvantages of garbage collection by reference counting.
For example, Programmers don’t have to worry about deleting objects when they are no
longer used.
The most important issue in reference counting garbage collection is that it doesn’t work
in cyclical references which is a situation in which an object refers to itself.
The simplest cyclical reference is appending a list to itself as shown below.
ANKUR 13
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA
Reference counting alone can not destroy objects with cyclic references.
If the reference count is not zero, the object cannot be deleted.
The solution to this problem is the second garbage collection method.
ANKUR 14
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA
In JAVA Language
class Addition
{
public static void main(String args[ ])
{
int a,b;
a = 10;
b = 20;
System.out.println("The Sum : "+(a+b));
}
}
In PYTHON Language
a =b= 10 = 20
print("The Sum : ",(a+b))
ANKUR 15
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA
Python variable
In Python, 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 variable is a name given to a memory location.
It is the basic unit of storage in a program.
The value stored in a variable can be changed during program execution.
A variable is only a name given to a memory location, all the operations done on the variable
effects that memory location.
print(age) #output : 45
print(salary) #output : 1456.8
print(name) #output : Daksh
ANKUR 16
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA
# display
print("Before declare: ", Number) # Before declare: 100
a = "Daksh"
b = "Parmar"
print(a+b) #output : Daksh Parmar
ANKUR 17
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA
Multi-line statement
In Python, the end of a statement is marked by a newline character. But we can make a
statement extend over multiple lines with the line continuation character (\) which is called
an explicit line continuation.
For example:
a = 1 + 2 + 3 + \
4 + 5 + 6 + \
7 + 8 + 9
We can also put multiple statements in a single line using semicolons, as follows:
a = 1; b = 2; c = 3
ANKUR 18
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA
1. Local Variable
Local variables are the variables that declared inside the function and have scope within the
function.
Let's understand the following example.
Example -
# Declaring a function
def add():
# Calling a function
add()
2. Global Variables
Global variables can be used throughout the program, and its scope is in the entire program.
We can use global variables inside or outside the function.
A variable declared outside the function is the global variable by default.
Python provides the global keyword to use global variable inside the function.
If we don't use the global keyword, the function treats it as a local variable.
Let's understand the following example.
# Declare a variable and initialize it
x = 101
ANKUR 19
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA
print(x)
Output: 101
Welcome Friend
Welcome Friend
change()
print("Value of x outside a function :", x)
ANKUR 20
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA
Output:
Value of x inside a function : 20
Value of x outside a function : 20
Delete a variable
We can delete the variable using the del keyword.
The syntax is as : del <variable_name>
# Assigning a value to x
x = 6
print(x)
# deleting a variable.
del x
print(x)
Output:
6
ANKUR 21
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA
print("datatype of num_int:",type(num_int))
print("datatype of num_flo:",type(num_flo))
print("Value of num_new:",num_new)
print("datatype of num_new:",type(num_new))
Output :
datatype of num_int: <class 'int'>
datatype of num_flo: <class 'float'>
Now, let's try adding a string and an integer, and see how Python deals with it.
Example : Addition of string(higher) data type and integer(lower) datatype
num_int = 123
num_str = "456"
ANKUR 22
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA
Output :
Data type of num_int: <class 'int'>
Data type of num_str: <class 'str'>
num_str = int(num_str)
print("Data type of num_str after Type Casting:",type(num_str))
Output :
Data type of num_int: <class 'int'>
Data type of num_str before Type Casting: <class 'str'>
ANKUR 23
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA
keywords in python
Keywords are the reserved words in Python.
We cannot use a keyword as a variable name, function name or any other identifier.
They are used to define the syntax and structure of the Python language.
In Python, keywords are case sensitive.
There are 35 keywords in Python, this number can vary slightly over the course of time.
All the keywords except True, False and None are in lowercase and they must be written as
they are.
Keyword in Python
False await else import pass
None break except in raise
True class finally is return
and continue for lambda try
as def from nonlocal while
assert del global not with
async elif if or yield
ANKUR 24
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA
Datatypes in python
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.
Type Which type of Value stored?
Text str
Numeric int, float, complex
Sequence list, tuple, range
Mapping dict
Set set, frozenset
Boolean bool
Binary bytes, bytearray, memoryview
ANKUR 25
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA
s = "This is a string"
print(s)
s = '''A multiline
string'''
print(s)
Output :
This is a string
A multiline
String
Just like a list and tuple, the slicing operator [ ] can be used with strings.
String index will be start with zero and all the white spaces will be count in a string while
slicing.
Strings, however, are immutable(unchangeable) means once created it can’t be modified.
s = 'Hello world!'
print("s[4] = ", s[4])
print("s[6:11] = ", s[6:11])
Output :
s[4] = o
s[6:11] = 'world'
ANKUR 26
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA
1. Integer
This value is represented by int class.
It contains positive or negative whole numbers (without fraction or decimal).
In Python there is no limit to how long an integer value can be.
a = 12345
print(“a = ”, a)
Output :
12345
2. Float
This value is represented by float class.
It is a real number with floating point representation.
A floating-point number is accurate up to 15 decimal places.
Integer and floating points are separated by decimal points.
1 is an integer, 1.0 is a floating-point number.
b = 0.12345
print(“b = ”, b)
Output :
0.12345
3. Complex
Complex number is represented by complex class.
It is specified as (real part) + (imaginary part)j. For example – 2+3j
Complex numbers are written in the form, x + yj, where x is the real part and y is the
imaginary part.
c = 1+2j
print(“c = ”, c)
Output :
(1+2j)
ANKUR 27
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA
1. Python List
In Python, a list is created by placing elements inside square brackets [], separated by
commas.
List is an ordered sequence of items.
All the items in a list do not need to be of the same type and can have any number of items..
my_list = [1, "Hello", 3.4]
A list can also have another list as an item. This is called a nested list.
my_list = ["mouse", [8, 4, 6], ['a']]
Lists are mutable(changeable), means, the value of elements of a list can be altered.
a = [1, 2, 3]
a[2] = 4
print(a)
Output :
[1, 2, 4]
We can use the slicing operator [ ] to extract an item or a range of items from a list.
a = [5,10,15,20,25,30,35,40]
print("a[2] = ", a[2])
print("a[0:3] = ", a[0:3])
print("a[5:] = ", a[5:])
Output :
a[2] = 15
a[0:3] = [5, 10, 15]
a[5:] = [30, 35, 40]
ANKUR 28
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA
2. Python Tuple
A tuple is created by placing all the items (elements) inside parentheses (), separated by
commas.
A tuple in Python is similar to a list.
The difference between the two is that we cannot change the elements of a tuple once it is
assigned whereas we can change the elements of a list.
Tuple is also an ordered sequence of items same as a list.
A tuple can have any number of items and they may be of different types (integer, float, list,
string, etc.).
my_tuple = (1, "Hello", 3.4)
A tuple can also have another tuple as an item. This is called a nested tuple.
my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
A tuple can also be created without using parentheses which is known as tuple packing and
tuple unpacking is also possible.
my_tuple = 3, 4.6, "dog"
print(my_tuple)
Output :
(3, 4.6, 'dog')
3
4.6
Dog
ANKUR 29
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA
# Parentheses is optional
my_tuple = "hello",
print(type(my_tuple))
Output :
<class 'str'>
<class 'tuple'>
<class 'tuple'>
We can use the slicing operator [ ] to extract items but we cannot change its value.
a = (5,'program', 1+3j)
print("a[1] = ", a[1])
print("a[0:3] = ", a[0:3])
3. Python Range
Range in python is mainly used with loops in python.
It returns a sequence of numbers specified in the function arguments.
Following are the range function parameters that we use in python:
Start – This specifies the start of the sequence of numbers in a range function.
Stop – It is the ending point of the sequence, the number will stop as soon as it reaches
the stop parameter.
Step – The steps or the number of increments before each number in the sequence is
decided by step parameter.
ANKUR 30
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA
The range function in python only works with integers or whole numbers.
Arguments passed in the range function cannot be any other data type other than an integer
data type.
All three arguments passed can be either positive or negative integers.
Step argument value cannot be zero otherwise it will throw a ValueError exception.
You can access the elements in a range function using index values, just like a list data type.
Output : 2
4
6
8
10
12
14
16
18
# using range(stop)
print(list(range(10)))
Output :
[]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
ANKUR 31
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA
Output :
5, 4, 3, 2, 1, 0
Output :
[2, 4, 6, 8, 10, 12]
ANKUR 32
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA
1. set type
A set is basically a data type consisting of a collection of unordered elements.
Sets are mutable(changeable) and do not have repeated copies of elements.
The values of a set are unindexed, so, indexing operations cannot be performed on sets.
Sets in Python are used when
The order of data does not matter
You do not need any repetitions in the data elements
You need to perform mathematical operations such as union, intersection, etc.
Below is the program whose output shows all the elements present My_Set.
My_Set={1,'s',7.8}
print(My_Set)
Output: set( )
ANKUR 33
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA
The update() function is used when you want to add more than one element to the
existing set.
As you can see in the output, the update() function is taking a list of 4 values and all
values except 1 are added to My_Set. This is because 1 is already present in the set
and therefore, it cannot be added again.
My_Set={1,'s',7.8}
My_Set.update([2,4.6,1,'r'])
print(My_Set)
2. discard( ) function
If you want to remove some element from the set, and if you are not sure whether that
element is actually present in the set or not, you can use the discard() function.
ANKUR 34
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA
This function will take the element to be removed from the set as a parameter but in case
the element is not present, it does not throw an error.
The output shows that 4.6 has been removed from My_Set but discard() has not thrown
an error when you used My_Set.discard(‘i’) even though ‘i’ is not present in my set.
My_Set={1, 2, 4.6, 7.8, 'r', 's'}
My_Set.discard(4.6)
My_Set.discard('i')
print(My_Set)
3. pop( ) function
The pop() function also removes set elements, but since a set is unordered, you will not
know which element has been removed.
The output shows that, using pop() some random element has been removed, which in
this case is 1.
My_Set={1, 2, 4.6, 7.8, 'r', 's'}
My_Set.pop()
print(My_Set)
Now, in case you want to delete all elements present in a set, you can use the clear() method.
As you can see in the output, My_Set is an empty set.
My_Set={1, 2, 4.6, 7.8, 'r', 's'}
My_Set.clear()
print(My_Set)
Output: set()
In case you want to completely delete the set, you can use the del keyword.
When you run the code, it will throw an error because My_Set is deleted.
My_Set={1, 2, 4.6, 7.8, 'r', 's'}
del My_Set
print(My_Set)
ANKUR 35
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA
2. frozenset type
Frozenset has the characteristics of a set, but its elements cannot be changed once assigned.
Being immutable, it does not have methods that add or remove elements.
The frozenset() function takes a single Parameters
The syntax of frozenset() function is: frozenset([iterable])
Iterable can be set, dictionary, tuple, etc.
# initialize A and B in Frozenset
A = frozenset([1, 2, 3, 4])
B = frozenset([3, 4, 5, 6])
Output :
The frozen set is: frozenset({'a', 'o', 'u', 'i', 'e'})
The empty frozen set is: frozenset()
Traceback (most recent call last):
File "<string>, line 8, in <module>
fSet.add('v')
AttributeError: 'frozenset' object has no attribute 'add'
ANKUR 36
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA
Frozenset operations
Like normal sets, frozenset can also perform different operations like copy, difference,
intersection, symmetric_difference, and union.
# initialize A and B in Frozenset
A = frozenset([1, 2, 3, 4])
B = frozenset([3, 4, 5, 6])
# copying a frozenset
C = A.copy() # Output: frozenset({1, 2, 3, 4})
print(C)
# union
print(A.union(B)) # Output: frozenset({1, 2, 3, 4, 5, 6})
# intersection
print(A.intersection(B)) # Output: frozenset({3, 4})
# difference
print(A.difference(B)) # Output: frozenset({1, 2})
# symmetric_difference
print(A.symmetric_difference(B)) # Output: frozenset({1, 2, 5, 6})
Similarly, other set methods like isdisjoint, issubset, and issuperset are also available.
# initialize A, B and C in Frozenset
A = frozenset([1, 2, 3, 4])
B = frozenset([3, 4, 5, 6])
C = frozenset([5, 6])
# isdisjoint() method
print(A.isdisjoint(C)) # Output: True
# issubset() method
print(C.issubset(B)) # Output: True
# issuperset() method
print(B.issuperset(C)) # Output: True
ANKUR 37
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA
# using dict()
my_dict = dict({1:'apple', 2:'ball'})
ANKUR 38
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA
my_dict['add'] = 'Downtown'
print(my_dict) # Output: {'name': 'Jack', 'age': 27, 'add': 'Downtown'}
ANKUR 39
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA
# Output: {}
print(squares)
# Throws Error
print(squares)
Output :
16
{1: 1, 2: 4, 3: 9, 5: 25}
{}
ANKUR 40
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA
b = False
type(b)
Output : <class 'bool'>
Note the keywords True and False must have an Upper Case first letter. Using a lowercase
true returns an error.
c = true
Output : Traceback (most recent call last):
File "<input>", line 1, in <module>
NameError: name 'true' is not defined
d = false
Output : Traceback (most recent call last):
File "<input>", line 1, in <module>
NameError: name 'false' is not defined
Boolean Arithmetic
Boolean arithmetic is the arithmetic of true and false logic.
A boolean or logical value can either be True or False.
Boolean values can be manipulated and combined with boolean operators.
Boolean operators in Python include and, or, and not.
The common boolean operators in Python are below:
or
and
not
== (equivalent)
!= (not equivalent)
ANKUR 41
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA
In the code section below, two variables are assigned the boolean values True and False.
Then these boolean values are combined and manipulated with boolean operators.
A = True
B = False
A or B
Output : True
A and B
Output : False
not A
Output : False
not B
Output : True
A == B
Output : False
A != B
Output : True
ANKUR 42
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA
x = b'char_data'
x = b"char_data"
y = bytearray(5)
z = memoryview(bytes(5))
print(x) # b'char_data'
print(y) # bytearray(b'\x00\x00\x00\x00\x00')
print(z) # <memory at 0x014CE328>
ANKUR 43
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA
average= 92.5
type(average)
Output : <class 'float'>
student1= "Mark"
type(student1)
Output : <class 'str'>
ANKUR 44
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA
Operators in python
Operators are special symbols in Python that carry out arithmetic or logical computation.
The value that the operator operates on is called the operand.
For example: 2+3 will be provide output as 5
Here, + is the operator that performs addition. 2 & 3 are the operands and 5 is the output.
1. Arithmetic operators
Arithmetic operators are used to perform mathematical operations like addition, subtraction,
multiplication, etc.
Operator Meaning Example
+ Add two operands x+y
- Subtract right operand from the left x-y
* Multiply two operands x*y
Divide left operand by the right one
/ x/y
(always results into float)
Modulus - remainder of the division
% x % y (remainder of x/y)
of left operand by the right
Floor division - division that results
// into whole number adjusted to the x // y
left in the number line
Exponent - left operand raised to the
** x**y (x to the power y)
power of right
ANKUR 45
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA
2. Comparison operators
Comparison operators are used to compare values. It returns either True or False according to
the condition.
Operator Meaning Example
Greater than - True if left operand is
> x>y
greater than the right
Less than - True if left operand is
< x<y
less than the right
Equal to - True if both operands are
== x == y
equal
Not equal to - True if operands are
!= x != y
not equal
Greater than or equal to - True if left
>= operand is greater than or equal to x >= y
the right
Less than or equal to - True if left
<= operand is less than or equal to the x <= y
right
3. Logical operators
Logical operators are the and, or, not operators.
Operator Meaning Example
and True if both the operands are true x and y
or True if either of the operands is true x or y
True if operand is false
not not x
(complements the operand)
ANKUR 46
COLLEGE ==> MATRUSHRI L.J. GANDHI BCA COLLEGE, MODASA
A B A and B
True True True
True False False
False True False
False False False
Truth Table : or
or will result into True if any of the operand is True.
A B A or B
True True True
True False True
False True True
False False False
A not A
True False
False True
ANKUR 47