Python Module 1

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

Module I Introduction to Python:

Python Introduction- Features, Identifiers, Reserved words, Indentation, Comments, Built-in Data
types and their Methods: Strings, List, Tuples, Dictionary, and Set - Type Conversion- Operators.
Execution of a Python, Program, Writing Our First Python Program, Statements Precedence of
Operators.
Python Collections (Arrays)

• There are four collection data types in the Python


programming language:
• List is a collection which is ordered and changeable.
Allows duplicate members.
• Tuple is a collection which is ordered and
unchangeable. Allows duplicate members.
• Set is a collection which is unordered, unchangeable*,
and unindexed. No duplicate members.
• Dictionary is a collection which is ordered** and
changeable. No duplicate members.
Tuple
• Tuples are used to store multiple items in a single
variable.
• Tuple is one of 4 built-in data types in Python used to
store collections of data, the other 3 are List, Set,
and Dictionary, all with different qualities and usage.
• A tuple is a collection which is ordered
and unchangeable.
• Tuples are written with round brackets.
• mytuple = ("apple", "banana", "cherry")
• thistuple = ("apple", "banana", "cherry")
print(thistuple)
TUPLE
•Tuple Items
• Tuple items are ordered, unchangeable, and allow duplicate values.
• Tuple items are indexed, the first item has index [0], the second item
has index [1] etc.
• Ordered
• When we say that tuples are ordered, it means that the items have a
defined order, and that order will not change.
• Unchangeable
• Tuples are unchangeable, meaning that we cannot change, add or
remove items after the tuple has been created.
• Allow Duplicates
• Since tuples are indexed, they can have items with the same value:
• thistuple = ("apple", "banana", "cherry", "apple", "cherry")
print(thistuple)
tuple
Tuple Length
 To determine how many items a tuple has, use the len() function:
 thistuple = ("apple", "banana", "cherry")
print(len(thistuple))
• Create Tuple With One Item
• To create a tuple with only one item, you have to add a
comma after the item, otherwise Python will not recognize it
as a tuple. Example One item tuple, remember the comma:
• thistuple = ("apple",)
print(type(thistuple))

#NOT a tuple
thistuple = ("apple")
print(type(thistuple))
Tuple
• Tuple Items - Data Types
• Tuple items can be of any data type:
• Example
• String, int and boolean data types:
• tuple1 = ("apple", "banana", "cherry")
tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False, False)
• A tuple can contain different data types:
• Example
• A tuple with strings, integers and boolean values:
• tuple1 = ("abc", 34, True, 40, "male")
Tuple
• type()
• From Python's perspective, tuples are defined as objects with the
data type 'tuple':
• <class 'tuple'>
• Example
• What is the data type of a tuple?
• mytuple = ("apple", "banana", "cherry")
print(type(mytuple))
• The tuple() Constructor
• It is also possible to use the tuple() constructor to make a tuple.
• Example
• Using the tuple() method to make a tuple:
• thistuple = tuple(("apple", "banana", "cherry")) # note the
double round-brackets
print(thistuple)
Python Collections (Arrays)
• There are four collection data types in the Python
programming language:
• List is a collection which is ordered and changeable. Allows
duplicate members.
• Tuple is a collection which is ordered and unchangeable.
Allows duplicate members.
• Set is a collection which is unordered, unchangeable*, and
unindexed. No duplicate members.
• Dictionary is a collection which is ordered** and
changeable. No duplicate members.
• When choosing a collection type, it is useful to understand
the properties of that type. Choosing the right type for a
particular data set could mean retention of meaning, and, it
could mean an increase in efficiency or security.
tuple
• Access Tuple Items
• You can access tuple items by referring to the index
number, inside square brackets:
• ExampleGet your own Python Server
• Print the second item in the tuple:
• thistuple = ("apple", "banana", "cherry")
print(thistuple[1])
• Negative Indexing
• Negative indexing means start from the end.
• -1 refers to the last item, -2 refers to the second last item
etc.
• Print the last item of the tuple:
• thistuple = ("apple", "banana", "cherry")
print(thistuple[-1])
Tuple
• Range of Indexes
• You can specify a range of indexes by specifying where
to start and where to end the range.
• When specifying a range, the return value will be a new
tuple with the specified items.
• Example
• Return the third, fourth, and fifth item:
• thistuple =
("apple", "banana", "cherry", "orange", "kiwi", "me
lon", "mango")
print(thistuple[2:5])
• Note: The search will start at index 2 (included) and
end at index 5 (not included).
Tuple
• Example
• This example returns the items from the beginning to, but NOT
included, "kiwi":
• thistuple =
("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[:4])
• Range of Negative Indexes
• Specify negative indexes if you want to start the search from the end
of the tuple:
• Example
• This example returns the items from index -4 (included) to index -1
(excluded)
• thistuple =
("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[-4:-1])
Tuple

• Check if Item Exists


To determine if a specified item is present in a tuple use
the in keyword:
• Example
• Check if "apple" is present in the tuple:
• thistuple = ("apple", "banana", "cherry")
if "apple" in thistuple:
print("Yes, 'apple' is in the fruits
tuple")
Python - Update Tuples
• Tuples are unchangeable, meaning that you cannot change, add,
or remove items once the tuple is created.
• Change Tuple Values
• Once a tuple is created, you cannot change its values. Tuples
are unchangeable, or immutable as it also is called.
• But there is a workaround. You can convert the tuple into a list,
change the list, and convert the list back into a tuple.
• Example
• Convert the tuple into a list to be able to change it:
• x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x)
Python - Update Tuples
•Add Items
• Since tuples are immutable, they do not have a built-
in append() method, but there are other ways to add items to a
tuple.
• 1. Convert into a list: Just like the workaround for changing a
tuple, you can convert it into a list, add your item(s), and
convert it back into a tuple.
• Example
• Convert the tuple into a list, add "orange", and convert it
back into a tuple:
• thistuple = ("apple", "banana", "cherry")
y = list(thistuple)
y.append("orange")
thistuple = tuple(y)
Python - Update Tuples

• 2. Add tuple to a tuple. You are allowed to add tuples to


tuples, so if you want to add one item, (or many), create a
new tuple with the item(s), and add it to the existing tuple:
• Example
• Create a new tuple with the value "orange", and add that
tuple:
• thistuple = ("apple", "banana", "cherry")
y = ("orange",)
thistuple += y
print(thistuple)
Python - Remove Items
• Note: You cannot remove items in a tuple.
• Tuples are unchangeable, so you cannot remove items from it, but
you can use the same workaround as we used for changing and adding
tuple items:
• Example
• Convert the tuple into a list, remove "apple", and convert it back into a
tuple:
• thistuple = ("apple", "banana", "cherry")
y = list(thistuple)
y.remove("apple")
thistuple = tuple(y)
• you can delete the tuple completely:
• Example
• The del keyword can delete the tuple completely:
• thistuple = ("apple", "banana", "cherry")
del thistuple
print(thistuple) #this will raise an error because the tuple no
longer exists
Unpacking a Tuple
• When we create a tuple, we normally assign values to it. This is called
"packing" a tuple:
• Example
• Packing a tuple:
• fruits = ("apple", "banana", "cherry")
• But, in Python, we are also allowed to extract the values back into
variables. This is called "unpacking":
• Example
• Unpacking a tuple:
• fruits = ("apple", "banana", "cherry")
(green, yellow, red) = fruits
print(green)
print(yellow)
print(red)

Unpacking a Tuple
Using Asterisk*
If the number of variables is less than the number of values, you can add an * to the variable name and
the values will be assigned to the variable as a list:

Example
Assign the rest of the values as a list called "red":
fruits = ("apple", "banana", "cherry", "strawberry", "raspberry")
(green, yellow, *red) = fruits
print(green)
print(yellow)
print(red)

fruits = ("apple", "mango", "papaya", "pineapple", "cherry")


(green, *tropic, red) = fruits
print(green)
print(tropic)
print(red)
Python - Loop Tuples
• ExampleGet your own Python Serve
• Iterate through the items and print the values:
• thistuple = ("apple", "banana", "cherry")
for x in thistuple:
print(x)
Loop Through the Index Numbers
You can also loop through the tuple items by referring to their
index number.
Use the range() and len() functions to create a suitable iterable.
• Example
• Print all items by referring to their index number:
• thistuple = ("apple", "banana", "cherry")
for i in range(len(thistuple)):
print(thistuple[i])
Python - Loop Tuples
Using a While Loop
• You can loop through the tuple items by using a while loop.
• Use the len() function to determine the length of the tuple,
then start at 0 and loop your way through the tuple items
by referring to their indexes.
• Remember to increase the index by 1 after each iteration.
Example
Print all items, using a while loop to go through all the index
numbers:
thistuple = ("apple", "banana", "cherry")
i = 0
while i < len(thistuple):
print(thistuple[i])
i = i + 1
Join Two Tuples

• Join two tuples:


• tuple1 = ("a", "b" , "c")
tuple2 = (1, 2, 3)
tuple3 = tuple1 + tuple2
print(tuple3)
• Multiply the fruits tuple by 2:
• fruits = ("apple", "banana", "cherry")
mytuple = fruits * 2
print(mytuple)
Strings
• Strings in python are surrounded by either single quotation
marks, or double quotation marks.
• 'hello' is the same as "hello".
• You can display a string literal with the print() function:
• print("Hello")
print('Hello’)
• Assign String to a Variable
• Assigning a string to a variable is done with the variable
name followed by an equal sign and the string:
• a = "Hello"
print(a)
Strings
• Multiline Strings
• You can assign a multiline string to a variable by using three quotes:
• a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)
• a = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.'''
print(a)
• Strings are Arrays
• Like many other popular programming languages, strings in Python are
arrays of bytes representing unicode characters.
• However, Python does not have a character data type, a single
character is simply a string with a length of 1.
• Square brackets can be used to access elements of the string.
Strings
• Strings are Arrays
• Like many other popular programming languages, strings in
Python are arrays of bytes representing unicode characters.
• However, Python does not have a character data type, a
single character is simply a string with a length of 1.
• Square brackets can be used to access elements of the
string.
• Example
• Get the character at position 1 (remember that the first
character has the position 0):
• a = "Hello, World!"
print(a[1])
Strings
• Strings with loops
• Example
• Loop through the letters in the word "banana":
• for x in "banana":
print(x)
• len() function return length
• a = "Hello, World!"
print(len(a))
• Check if "free" is present in the following text:
• txt = "The best things in life are free!"
print("free" in txt)
Strings
• Example
• txt = "The best things in life are free!"
if "free" in txt:
print("Yes, 'free' is present.")
• txt = "The best things in life are free!"
print("expensive" not in txt)
• txt = "The best things in life are free!"
if "expensive" not in txt:
print("No, 'expensive' is NOT present.")
• Slicing
• You can return a range of characters by using the slice syntax.
• Specify the start index and the end index, separated by a colon,
to return a part of the string.
• Get the characters from position 2 to position 5 (not included):
• b = "Hello, World!"
print(b[2:5])
Strings
• Slicing
• Get the characters from the start to position 5 (not
included):
• b = "Hello, World!"
print(b[:5])
• Get the characters from position 2, and all the way to the
end:
• b = "Hello, World!"
print(b[2:])
• Get the characters:
• From: "o" in "World!" (position -5)
• To, but not included: "d" in "World!" (position -2):
• b = "Hello, World!"
print(b[-5:-2])
Strings Update operations
• The upper() method returns the string in upper case:
a = "Hello, World!"
print(a.upper())
• The lower() method returns the string in lower case:
• a = "Hello, World!“
• print(a.lower())
• The strip() method removes any whitespace from the
beginning or the end:
• a = " Hello, World! "
• print(a.strip()) # returns "Hello, World!“
• The replace() method replaces a string with another
string:
• a = "Hello, World!"
• print(a.replace("H", "J"))
Split String
• The split() method returns a list where the text between the specified
separator becomes the list items.
• Example
• The split() method splits the string into substrings if it finds instances
of the separator:
• a = "Hello, World!"
• print(a.split(",")) # returns ['Hello', ' World!']
String Concatenation
• To concatenate, or combine, two strings you can use the + operator.
• Example
• Merge variable a with variable b into variable c:
• a = "Hello"
• b = "World"
• c=a+b
• print(c)
• To add a space between them, add a " ":
• a = "Hello"
• b = "World"
• c=a+""+b
• print(c)
String Format
• As we learned in the Python Variables chapter, we cannot combine strings
and numbers like this
• Example
• age = 36
• txt = "My name is John, I am " + age
• print(txt)
• But we can combine strings and numbers by using the format() method!
• The format() method takes the passed arguments, formats them, and
places them in the string where the placeholders {} are:
• Example
• Use the format() method to insert numbers into strings:
• age = 36
• txt = "My name is John, and I am {}"
• print(txt.format(age))
String Format
• The format() method takes unlimited number of arguments, and are placed into
the respective placeholders:
• Example
• quantity = 3
• itemno = 567
• price = 49.95
• myorder = "I want {} pieces of item {} for {} dollars."
• print(myorder.format(quantity, itemno, price))
• You can use index numbers {0} to be sure the arguments are placed in the correct
placeholders:
• Example
• quantity = 3
• itemno = 567
• price = 49.95
• myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
• print(myorder.format(quantity, itemno, price))
strings
• Escape Character
• To insert characters that are illegal in a string, use an escape
character.
• An escape character is a backslash \ followed by the character you
want to insert.
• Example
• The escape character allows you to use double quotes when you
normally would not be allowed:
• txt = "We are the so-called \"Vikings\" from the north.“
• String Methods
• Python has a set of built-in methods that you can use on strings.
Method Description isalnum() Returns True if all characters in the string are
alphanumeric
capitalize() Converts the first character to upper case

isalpha() Returns True if all characters in the string are


casefold() Converts string into lower case in the alphabet

center() Returns a centered string isascii() Returns True if all characters in the string are
ascii characters
count() Returns the number of times a specified
value occurs in a string

isdecimal() Returns True if all characters in the string are


decimals
encode() Returns an encoded version of the string
isdigit() Returns True if all characters in the string are
digits
endswith() Returns true if the string ends with the
specified value
isidentifier() Returns True if the string is an identifier

expandtabs() Sets the tab size of the string


islower() Returns True if all characters in the string are
find() Searches the string for a specified value and lower case
returns the position of where it was found

isnumeric() Returns True if all characters in the string are


numeric

format() Formats specified values in a string isprintable() Returns True if all characters in the string are
printable

format_map() Formats specified values in a string isspace() Returns True if all characters in the string are
whitespaces

istitle() Returns True if the string follows the rules of


index() Searches the string for a specified value and
a title
returns the position of where it was found

isupper() Returns True if all characters in the string are


upper case
join() Joins the elements of an iterable split() Splits the string at the
to the end of the string specified separator, and
returns a list
ljust() Returns a left justified version of
the string
splitlines() Splits the string at line breaks
lower() Converts a string into lower case
and returns a list
lstrip() Returns a left trim version of the
string startswith() Returns true if the string
starts with the specified
maketrans() Returns a translation table to be value
used in translations
partition() Returns a tuple where the string is
parted into three parts strip() Returns a trimmed version of
the string
replace() Returns a string where a specified
value is replaced with a specified swapcase() Swaps cases, lower case
value becomes upper case and vice
rfind() Searches the string for a specified versa
value and returns the last position
of where it was found title() Converts the first character of
each word to upper case
rindex() Searches the string for a specified
value and returns the last position
of where it was found translate() Returns a translated string

rjust() Returns a right justified version of upper() Converts a string into upper
the string case
rpartition() Returns a tuple where the string is
parted into three parts zfill() Fills the string with a
specified number of 0 values
rsplit() Splits the string at the specified at the beginning
separator, and returns a list

rstrip() Returns a right trim version of the


string
Python Sets
• myset = {"apple", "banana", "cherry"}
• Sets are used to store multiple items in a single variable.
• Set is one of 4 built-in data types in Python used to store collections of
data, the other 3 are List, Tuple, and Dictionary, all with different qualities
and usage.
• A set is a collection which is unordered, unchangeable*, and unindexed.
• * Note: Set items are unchangeable, but you can remove items and add
new items.
• Sets are written with curly brackets.
• Create a Set:
• thisset = {"apple", "banana", "cherry"}
print(thisset)
Python Sets
• Note: Sets are unordered, so you cannot be sure in which order the items will appear.
• Set Items:-
• Set items are unordered, unchangeable, and do not allow duplicate values.
• Unordered:-
• Unordered means that the items in a set do not have a defined order.
• Set items can appear in a different order every time you use them, and cannot be
referred to by index or key.
• Unchangeable:-
• Set items are unchangeable, meaning that we cannot change the items after the set has
been created.
• Once a set is created, you cannot change its items, but you can remove items and add
new items.
• Duplicates Not Allowed:-
• Sets cannot have two items with the same value.
Python Sets
• Example
• Duplicate values will be ignored:
• thisset = {"apple", "banana", "cherry", "apple"}
• print(thisset)
• Output:- {'banana', 'cherry', 'apple'} 'apple’}
• Note: The values True and 1 are considered the same value in sets,
and are treated as duplicates:
• Example
• True and 1 is considered the same value:
• thisset = {"apple", "banana", "cherry", True, 1, 2}
• print(thisset)
Python Sets
• Get the Length of a Set
• To determine how many items a set has, use the len() function.
• Example
• Get the number of items in a set:
• thisset = {"apple", "banana", "cherry"}
• print(len(thisset))
• Set Items - Data Types
• Set items can be of any data type:
• Example
• String, int and boolean data types:
• set1 = {"apple", "banana", "cherry"}
• set2 = {1, 5, 7, 9, 3}
• set3 = {True, False, False}
Python Sets
• A set can contain different data types:
• Example
• A set with strings, integers and boolean values:
• set1 = {"abc", 34, True, 40, "male"}
• type()
• From Python's perspective, sets are defined as objects with the data type 'set':
• <class 'set’>
• Example
• What is the data type of a set?
• myset = {"apple", "banana", "cherry"}
• print(type(myset))
• The set() Constructor
• It is also possible to use the set() constructor to make a set.
• Example
• Using the set() constructor to make a set:
• thisset = set(("apple", "banana", "cherry")) # note the double round-brackets
print(thisset)
Python - Access Set Items
• Access Items
• You cannot access items in a set by referring to an index or a key.
• 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 keyword.
• Loop through the set, and print the values:
• thisset = {"apple", "banana", "cherry"}
for x in thisset:
print(x)
• Example
• Check if "banana" is present in the set:
• thisset = {"apple", "banana", "cherry"}
• print("banana" in thisset)
• Change Items
• Once a set is created, you cannot change its items, but you can add new items.
Python - Add Set Items
• Add Items
• Once a set is created, you cannot change its items, but you can add new items.
• To add one item to a set use the add() method.
• Example
• Add an item to a set, using the add() method:
• thisset = {"apple", "banana", "cherry"}
• thisset.add("orange")
• print(thisset)
• Add Sets
• To add items from another set into the current set, use the update() method.
• Example
• Add elements from tropical into thisset:
• thisset = {"apple", "banana", "cherry"}
• tropical = {"pineapple", "mango", "papaya"}
• thisset.update(tropical)
• print(thisset)
Python - Remove Set Items
• Remove Item
• To remove an item in a set, use the remove(), or the discard() method.
• Example
• Remove "banana" by using the remove() method:
• thisset = {"apple", "banana", "cherry"}
• thisset.remove("banana")
• print(thisset)
• Note: If the item to remove does not exist, remove() will raise an error.
• Example
• Remove "banana" by using the discard() method:
• thisset = {"apple", "banana", "cherry"}
• thisset.discard("banana")
• print(thisset)
• Note: If the item to remove does not exist, discard() will NOT raise an error.
Python - Remove Set Items
• Remove Item
• You can also use the pop() method to remove an item, but this method will remove a random item, so you cannot be sure what
item that gets removed.
• The return value of the pop() method is the removed item.
• Example
• Remove a random item by using the pop() method:
• thisset = {"apple", "banana", "cherry"}
• x = thisset.pop()
• print(x)
• print(thisset)
• Note: Sets are unordered, so when using the pop() method, you do not know which item that gets removed.
• Example
• The clear() method empties the set:
• thisset = {"apple", "banana", "cherry"}
• thisset.clear()
• print(thisset)
• Example
• The del keyword will delete the set completely:
• thisset = {"apple", "banana", "cherry"}
• del thisset
• print(thisset)
Python - Join Sets
• Join Two Sets
• There are several ways to join two or more sets in Python.
• You can use the union() method that returns a new set containing all items from both
sets, or the update() method that inserts all the items from one set into another:
• Example
• The union() method returns a new set with all items from both sets:
• set1 = {"a", "b" , "c"}
• set2 = {1, 2, 3}
• set3 = set1.union(set2)
• print(set3)
• Example
• The update() method inserts the items in set2 into set1:
• set1 = {"a", "b" , "c"}
• set2 = {1, 2, 3}
• set1.update(set2)
• print(set1)
• Note: Both union() and update() will exclude any duplicate items.
Python - Join Sets
• Keep ONLY the Duplicates
• The intersection_update() method will keep only the items that are present in both
sets.
• Example
• Keep the items that exist in both set x, and set y:
• x = {"apple", "banana", "cherry"}
• y = {"google", "microsoft", "apple"}
• x.intersection_update(y)
• print(x)
• The intersection() method will return a new set, that only contains the items that are
present in both sets.
• Example
• Return a set that contains the items that exist in both set x, and set y:
• x = {"apple", "banana", "cherry"}
• y = {"google", "microsoft", "apple"}
• z = x.intersection(y)
• print(z)
Python - Join Sets
• Note: The values True and 1 are considered the same value in sets,
and are treated as duplicates:
• Example
• True and 1 is considered the same value:
• x = {"apple", "banana", "cherry", True}
• y = {"google", 1, "apple", 2}
• z = x.symmetric_difference(y)
• print(z)
• Set Methods
• Python has a set of built-in methods that you can use on sets.
Method Description
add() Adds an element to the set
clear() Removes all the elements from the set
copy() Returns a copy of the set
difference() Returns a set containing the difference between two or more sets

difference_update() Removes the items in this set that are also included in another, specified set

discard() Remove the specified item


intersection() Returns a set, that is the intersection of two other sets
intersection_update() Removes the items in this set that are not present in other, specified set(s)

isdisjoint() Returns whether two sets have a intersection or not


issubset() Returns whether another set contains this set or not
issuperset() Returns whether this set contains another set or not
pop() Removes an element from the set
remove() Removes the specified element
symmetric_difference() Returns a set with the symmetric differences of two sets

symmetric_difference_update() inserts the symmetric differences from this set and another

union() Return a set containing the union of sets


update() Update the set with the union of this set and others
Python Dictionaries
• Dictionary Items
• Dictionary items are ordered, changeable, and does not allow duplicates.
• Dictionary items are presented in key:value pairs, and can be referred to by
using the key name.
• Example
• Print the "brand" value of the dictionary:
• thisdict = {
• "brand": "Ford",
• "model": "Mustang",
• "year": 1964
•}
• print(thisdict["brand"])
Python Dictionaries
• Dictionary
• Dictionaries are used to store data values in key:value pairs.
• A dictionary is a collection which is ordered*, changeable and do not allow duplicates.
• Dictionaries are written with curly brackets, and have keys and values:
• Example
• Create and print a dictionary:
• thisdict = {
• "brand": "Ford",
• "model": "Mustang",
• "year": 1964
• }
• print(thisdict)
• Output:- {'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
Python Dictionaries
• Dictionary
• Dictionaries are used to store data values in key:value pairs.
• A dictionary is a collection which is ordered*, changeable and do not allow duplicates.
• Dictionaries are written with curly brackets, and have keys and values:
• Example
• Create and print a dictionary:
• thisdict = {
• "brand": "Ford",
• "model": "Mustang",
• "year": 1964
• }
• print(thisdict)
• Output:- {'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
Python - Basic Operators
• Operators are the constructs which can manipulate the
value of operands.
• Consider the expression 4 + 5 = 9. Here, 4 and 5 are
called operands and + is called operator.
• Types of Operator
• Python language supports the following types of
operators.
• Arithmetic Operators
• Comparison (Relational) Operators
• Assignment Operators
• Logical Operators
• Bitwise Operators
• Membership Operators
• Identity Operators
Python Arithmetic Operators
Operator Description Example
+ Addition Adds values on either side of the operator. a + b = 30
Subtracts right hand operand from left
- Subtraction a – b = -10
hand operand.
Multiplies values on either side of the
* Multiplication a * b = 200
operator
Divides left hand operand by right hand
/ Division b/a=2
operand
Divides left hand operand by right hand
% Modulus b%a=0
operand and returns remainder
Performs exponential (power) calculation
** Exponent a**b =10 to the power 20
on operators
Floor Division - The division of operands
where the result is the quotient in which
the digits after the decimal point are 9//2 = 4 and 9.0//2.0 = 4.0, -
//
removed. But if one of the operands is 11//3 = -4, -11.0//3 = -4.0
negative, the result is floored, i.e., rounded
away from zero (towards negative infinity) −
Python Arithmetic Operators
a = 21
b = 10
c=0
c=a+b
print ("Line 1 - Value of c is ", c)
c=a-b
print ("Line 2 - Value of c is ", c )
OUTPUT
c=a*b
Line 1 - Value of c is 31
print ("Line 3 - Value of c is ", c )
Line 2 - Value of c is 11
c=a/b
Line 3 - Value of c is 210
print ("Line 4 - Value of c is ", c )
Line 4 - Value of c is 2.1
c=a%b
Line 5 - Value of c is 1
print ("Line 5 - Value of c is ", c)
Line 6 - Value of c is 8
a=2
Line 7 - Value of c is 2
b=3
c = a**b
print ("Line 6 - Value of c is ", c)
a = 10
b=5
c = a//b
print ("Line 7 - Value of c is ", c)
Python Comparison Operators
• These operators compare the values on either sides of them and
decide the relation among them. They are also called Relational
operators.
• Assume variable a holds 10 and variable b holds 20, then −
Python Comparison Operators
Operator Description Example
If the values of two operands are equal, then the condition
== (a == b) is not true.
becomes true.
If values of two operands are not equal, then condition
!= (a != b) is true.
becomes true.
(a <> b) is true. This
If values of two operands are not equal, then condition
<> is similar to !=
becomes true.
operator.

If the value of left operand is greater than the value of right


> (a > b) is not true.
operand, then condition becomes true.

If the value of left operand is less than the value of right


< (a < b) is true.
operand, then condition becomes true.

If the value of left operand is greater than or equal to the


>= (a >= b) is not true.
value of right operand, then condition becomes true.

If the value of left operand is less than or equal to the value


<= (a <= b) is true.
of right operand, then condition becomes true.
Python Comparison Operators
• print ("Both operands are integer")
• a=5
• b=7
• print ("a=",a, "b=",b, "a>b is", a>b)
• print ("a=",a, "b=",b,"a<b is",a<b)
• print ("a=",a, "b=",b,"a==b is",a==b)
• print ("a=",a, "b=",b,"a!=b is",a!=b)

Output :-

Both operands are integer


a= 5 b= 7 a>b is False
a= 5 b= 7 a<b is True
a= 5 b= 7 a==b is False
a= 5 b= 7 a!=b is True
Python Assignment Operators
Operator Description Example
= Assigns values from right side operands to left side operand c = a + b assigns value of a + b into c
It adds right operand to the left operand and assign the result to
+= Add AND c += a is equivalent to c = c + a
left operand
It subtracts right operand from the left operand and assign the
-= Subtract AND c -= a is equivalent to c = c – a
result to left operand
It multiplies right operand with the left operand and assign the
*= Multiply AND c *= a is equivalent to c = c * a
result to left operand
It divides left operand with the right operand and assign the
/= Divide AND c /= a is equivalent to c = c / a
result to left operand
It takes modulus using two operands and assign the result to left
%= Modulus AND c %= a is equivalent to c = c % a
operand

Performs exponential (power) calculation on operators and


**= Exponent AND c **= a is equivalent to c = c ** a
assign value to the left operand

It performs floor division on operators and assign value to the


//= Floor Division c //= a is equivalent to c = c // a
left operand
Python Assignment Operators
a = 21
b = 10
c=0
c=a+b
print ("Line 1 - Value of c is ", c) Output:-
c += a Line 1 - Value of c is 31
print ("Line 2 - Value of c is ", c ) Line 2 - Value of c is 52
c *= a Line 3 - Value of c is 1092
print ("Line 3 - Value of c is ", c ) Line 4 - Value of c is 52.0
Line 5 - Value of c is 2
c /= a
Line 6 - Value of c is 2097152
print ("Line 4 - Value of c is ", c ) Line 7 - Value of c is 99864
c =2
c %= a
print ("Line 5 - Value of c is ", c)
c **= a
print ("Line 6 - Value of c is ", c)
c //= a
print ("Line 7 - Value of c is ", c)
Python Bitwise Operators
• Bitwise operator works on bits and performs bit by bit operation. Assume if
a = 60; and b = 13;
• Now in the binary format their values will be 0011 1100 and 0000 1101
respectively.
• Following table lists out the bitwise operators supported by Python
language with an example each in those, we use the above two variables (a
and b) as operands −
• a = 0011 1100
• b = 0000 1101
• -----------------
• a&b = 0000 1100
• a|b = 0011 1101
• a^b = 0011 0001
• ~a = 1100 0011
Python Bitwise Operators
Operator Description Example

& Binary AND Operator copies a bit to the result if it exists in both operands (a & b) (means 0000 1100)

| Binary OR It copies a bit if it exists in either operand. (a | b) = 61 (means 0011 1101)

^ Binary XOR It copies the bit if it is set in one operand but not both. (a ^ b) = 49 (means 0011 0001)

(~a ) = -61 (means 1100 0011 in


~ Binary Ones
It is unary and has the effect of 'flipping' bits. 2's complement form due to a
Complement
signed binary number.

The left operands value is moved left by the number of bits


<< Binary Left Shift a << 2 = 240 (means 1111 0000)
specified by the right operand.

The left operands value is moved right by the number of bits


>> Binary Right Shift a >> 2 = 15 (means 0000 1111)
specified by the right operand.
Python Logical Operators
Operator Description Example

and Logical AND If both the operands are true then condition becomes true. (a and b) is true.

If any of the two operands are non-zero then condition


or Logical OR (a or b) is true.
becomes true.

not Logical NOT Used to reverse the logical state of its operand. Not(a and b) is false.
Python Membership Operators
Python's membership operators test for membership in a
sequence, such as strings, lists, or tuples. There are two
membership operators.

Operator Description Example

Evaluates to true if it finds a variable in


x in y, here in results in a 1 if
in the specified sequence and false
x is a member of sequence y.
otherwise.

Evaluates to true if it does not finds a x not in y, here not in results


not in variable in the specified sequence and in a 1 if x is not a member of
false otherwise. sequence y.
Python Identity Operators
• Identity operators compare the memory locations of two
objects. There are two Identity operators

Operator Description Example

Evaluates to true if the variables on either


x is y, here is results in 1 if
is side of the operator point to the same
id(x) equals id(y).
object and false otherwise.

Evaluates to false if the variables on either x is not y, here is not results


is not side of the operator point to the same in 1 if id(x) is not equal to
object and true otherwise. id(y).
Python Operators Precedence Example
Operator Description
** Exponentiation (raise to the power)
Complement, unary plus and minus (method names for the last two are +@
~+-
and -@)

* / % // Multiply, divide, modulo and floor division


+- Addition and subtraction
>> << Right and left bitwise shift
& Bitwise 'AND'td>
^| Bitwise exclusive `OR' and regular `OR'
<= < > >= Comparison operators
<> == != Equality operators
= %= /= //= -= += *= **= Assignment operators
is is not Identity operators
in not in Membership operators
not or and Logical operators
Python Operators Precedence Example

• Operator precedence affects how an expression is evaluated.


• For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because
operator * has higher precedence than +, so it first multiplies 3*2 and
then adds into 7.
• Here, operators with the highest precedence appear at the top of the
table, those with the lowest appear at the bottom.
a = 20
b = 10 When you execute the program, it produces the
c = 15 following result −

d=5 Value of (a + b) * c / d is 90
Value of ((a + b) * c) / d is 90
e=0 Value of (a + b) * (c / d) is 90
e = (a + b) * c / d #( 30 * 15 ) / 5 Value of a + (b * c) / d is 50

print ("Value of (a + b) * c / d is ", e)


e = ((a + b) * c) / d # (30 * 15 ) / 5
print ("Value of ((a + b) * c) / d is ", e)
e = (a + b) * (c / d); # (30) * (15/5)
print ("Value of (a + b) * (c / d) is ", e)
e = a + (b * c) / d; # 20 + (150/5)
print ("Value of a + (b * c) / d is ", e)

You might also like