3.FPP Class Note Unit-I
3.FPP Class Note Unit-I
3.FPP Class Note Unit-I
Python 2.1
October 16, 2000
How to execute the python code: In Python, we can apply comments using the # hash character. The Python interpreter
1) Using interactive mode: entirely ignores the lines followed by a hash character. A good programmer always uses
In >>> prompt we can type individual code the comments to make code under stable. Let's see the following example of a
2) Script mode: comment.
Here we can write a program using some editor Notepad and then we can
execute the program from commands prompt. name = "Thomas" # Assigning string value to the name variable
3) Using IDE: We can add comment in each line of the Python code.
Here we can write a program, save, debug, and execute programs.
Fees = 10000 # defining course fees is 10000
Python Basic Syntax Fees = 20000 # defining course fees is 20000
There is no use of curly braces or semicolon in Python programming language. It is Types of Comment
English-like language. But Python uses the indentation to define a block of code.
Indentation is nothing but adding whitespace before the statement when it is Python provides the facility to write comments in two ways- single line comment and
needed. For example - multi-line comment.
def func():
statement 1 Single-Line Comment - Single-Line comment starts with the hash # character followed
statement 2 by text for further explanation.
…………………
………………… 1. # defining the marks of a student
statement N 2. Marks = 90
Example -
list1 = [1, 2, 3, 4, 5] We can also write a comment next to a code statement. Consider the following
for i in list1: example.
print(i)
if i==4: 1. Name = "James" # the name of a student is James
break 2. Marks = 90 # defining student's marks
print("End of for loop")
3. Branch = "Computer Science" # defining student branch
Output:
Multi-Line Comments - we can use “ “ “ character to the multiple lines.
1
For example -
2
# Calling a function
2. Assigning multiple values to multiple variables:
add()
#print(a+b) # it is invalid as a,b are local for function add()
Eg:
Ex2: Ex2:
def add(): a,b=10,20
# Defining local variables. They has scope only within a function
a = 20 def add():
b = 30 # ReDefining global variables.
Murali Krishna Senapaty
Date: 18-04-2022
global a,b As we can see in the above example, we assigned a large integer value to
a = 20 variable x and checked its type. It printed class <int> not long int. Hence, there is no
b = 30 limitation number by bits and we can expand to the limit of our memory.
c=a+b
print("The sum is:", c) Python doesn't have any special data type to store larger numbers.
Output: 6 Example:
Traceback (most recent call last):
File "C:/Users/DEVANSH SHARMA/PycharmProjects/Hello/multiprocessing.py", line "Aman" , '12345'
389, in Types of Strings:
print(x)
NameError: name 'x' is not defined There are two types of Strings supported in Python:
a) Single-line String- Strings that are terminated within a single-line are known as
Maximum Possible Value of an Integer in Python Single line Strings.
Example:
Unlike the other programming languages, Python doesn't have long int or float data text1='hello'
types. It treats all integer values as an int data type
b) Multi-line String - A piece of text that is written in multiple lines is known as
multiple lines string.
Murali Krishna Senapaty
Date: 18-04-2022
There are two ways to create multiline strings:
1) Adding black slash at the end of each line. III. Boolean literals:
Example: A Boolean literal can have any of the two values: True or False.
text1='hello\ Example - Boolean Literals
user' x = (1 == True)
print(text1) y = (2 == False)
'hellouser' z = (3 == True)
a = True + 10
2) Using triple quotation marks:- b = False + 10
Example: print("x is", x)
str2='''''welcome print("y is", y)
to print("z is", z)
SSSIT''' print("a:", a)
print str2 print("b:", b)
Output: Output:
welcome x is True
to y is False
SSSIT z is False
a: 11
II. Numeric literals: b: 10
Numeric Literals are immutable. Numeric literals can belong to following four
different numerical types. IV. Special literals.
Integer Python contains one special literal i.e., None.
Long Integer None is used to specify to that field that is not created. It is also used for the end of
Float lists in Python.
Complex
Example - Special Literals
Example: val1=10
x = 0b10100 #Binary Literals val2=None
y = 100 #Decimal Literal print(val1)
z = 0o215 #Octal Literal print(val2)
u = 0x12d #Hexadecimal Literal Output:
10
#Float Literal None
float_1 = 100.5
float_2 = 1.5e2 V. Literal Collections.
Python provides the four types of literal collection such as List literals, Tuple literals,
#Complex Literal Dict literals, and Set literals.
a = 5+3.14j
print(x, y, z, u) List:
print(float_1, float_2) List contains items of different data types. Lists are mutable i.e., modifiable.
print(a, a.imag, a.real) The values stored in List are separated by comma(,) and enclosed within square
Output: brackets([]). We can store different types of data in a List.
Example - List literals
20 100 141 301 list=['John',678,20.4,'Peter']
100.5 150.0 list1=[456,'Andrew']
(5+3.14j) 3.14 5.0 print(list)
Murali Krishna Senapaty
Date: 18-04-2022
print(list + list1) int
Output:
['John', 678, 20.4, 'Peter']
['John', 678, 20.4, 'Peter', 456, 'Andrew']
datatypes are 6 types:
Numbers
Dictionary: String
Python dictionary stores the data in the key-value pair. List
It is enclosed by curly-braces {} and each pair is separated by the commas(,). Tuple
Example
dict = {'name': 'Pater', 'Age':18,'Roll_nu':101}
Dictionary
print(dict) Set
Output: Boolean
{'name': 'Pater', 'Age': 18, 'Roll_nu': 101}
Numbers type:
Tuple: Python allows
Python tuple is a collection of different data-type. It is immutable which means it int,
cannot be modified after creation. float,
It is enclosed by the parentheses () and each element is separated by the comma(,). long,
Example complex
tup = (10,20,"Dev",[2,3,4]) *Here we can store a large integer value as per the memory available.
print(tup) *float type supports by default up to 15 decimal points.
Output: *long supports up to python 2.x and after that it is merged with int type
(10, 20, 'Dev', [2, 3, 4])
Example: Assignment of data
Set: x=10; //single assignment
Python set is the collection of the unordered dataset. x=y=z=40; //multiple assignments
It is enclosed by the {} and each element is separated by the comma(,). x,y,z=20,30,40; //multiple assignment with different values.
Example: - Set Literals x=5+7j
set = {'apple','grapes','guava','papaya'} print(type(x))
print(set) o/p: <class, ‘complex’>
Output:
{'guava', 'apple', 'papaya', 'grapes'}
Operators:
Example
Operators: x = 1 # int
The operators are the symbols which are responsible for particular operations between
y = 2.8 # float
operands. Python provides many types of operators.
z = 1j # complex
Floats: find() Searches the string for a specified value and returns the
x = 1.10 position of where it was found
y = 1.0
format() Formats specified values in a string
z = -35.59
print(type(x)) format_map() Formats specified values in a string
print(type(y))
print(type(z)) index() Searches the string for a specified value and returns the
position of where it was found
Python has a set of built-in methods that you can use on strings. isspace() Returns True if all characters in the string are whitespaces
Note: All string methods returns new values. They do not change the original string. istitle() Returns True if the string follows the rules of a title
isupper() Returns True if all characters in the string are upper case
Method Description
join() Joins the elements of an iterable to the end of the string
capitalize() Converts the first character to upper case
ljust() Returns a left justified version of the string
casefold() Converts string into lower case
partition() Returns a tuple where the string is parted into three parts my_string = "Hello"
print(my_string)
replace() Returns a string where a specified value is replaced with a
specified value my_string = '''Hello'''
print(my_string)
rfind() Searches the string for a specified value and returns the last
position of where it was found # triple quotes string can extend multiple lines
my_string = """Hello, welcome to
rindex() Searches the string for a specified value and returns the last the world of Python"""
position of where it was found print(my_string)
Example Example
The upper() method returns the string in upper case: x="python"
x=x.capitalize()
a = "Hello, World!" print(x)
print(a.upper())
o/p: Python
Example
The lower() method returns the string in lower case: Example
x="python"
a = "Hello, World!" x=x.upper()
print(a.lower()) print(x)
Example o/p: PYTHON
Murali Krishna Senapaty
Date: 18-04-2022
print(len(a))
a.upper()
String Format
Example
But we can combine strings and numbers by using the format() method! # index must be in range
my_string=”hello”
The format() method takes the passed arguments, formats them, and places them in the >>> print(my_string[15])
string where the placeholders {} are: ...
IndexError: string index out of range
Example
Use the format() method to insert numbers into strings: Example
age = 36 x="hello"
txt = "My name is John, and I am {}" print(x[20:])
print(txt.format(age)) o/p: NO OUTPUT as out of range
Example Example
quantity = 3 # index must be an integer
itemno = 567 >>> my_string[1.5]
price = 49.95 ...
myorder = "I want {} pieces of item {} for {} dollars." TypeError: string indices must be integers
print(myorder.format(quantity, itemno, price))
Example
Example
quantity = 3 Loop through the letters in the word "banana":
itemno = 567 for x in "banana":
price = 49.95 print(x)
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price)) o/p:
b
* With string we can use + and * operators
a
+ is used for concatenation n
And * is used for repetition a
Ex3:
>>>a= “Manohar” n
>>>b= “Singh” a
>>>print(a+b)
o/p: ManoharSingh
Example
Ex4:
>>>print(a*3) Check if "free" is present in the following text:
o/p: ManoharManoharManohar txt = "The best things in life are free!"
print("free" in txt)
ex: o/p: True
a="manohar"
Murali Krishna Senapaty
Date: 18-04-2022
Example Example
>>> word='python'
Print only if "free" is present: >>> word[0]='q'
txt = "The best things in life are free!" TypeError: 'str' object does not support item assignment
if "free" in txt:
print("Yes, 'free' is present.")
o/p: Yes, 'free' is present.
Escape Characters
Code Result
Example
# Iterating through a string \' Single Quote
count = 0
for letter in 'Hello World': \\ Backslash
if(letter == 'l'):
count += 1 \n New Line
print(count,'letters found')
\r Carriage Return
In Python the strings can be manipulated with index positions or subscripts.
\t Tab
Example
>>>word=”python” \b Backspace
Ex:
>>>word[-1] \f Form Feed
o/p: ‘n’
\ooo Octal value
Example
>>>word[-6] \xhh Hex value
o/p: ‘p’
We can even interact with a range of characters:
>>>word[2:5] Python Collections (Arrays)
o/p: ‘tho’
* In string type in the range specification, the starting and ending position is optional. There are four collection data types in the Python programming language:
Ex:
>>>word[:2]
o/p: ‘py’
List is a collection which is ordered and changeable. Allows duplicate
members.
Ex: Tuple is a collection which is ordered and unchangeable. Allows
>>>word[2:] duplicate members.
o/p: ‘thon’ Set is a collection which is unordered, unchangeable*, and
ex: >>>word[:2]+word[2:]
unindexed. No duplicate members.
o/p: ‘python’ Dictionary is a collection which is ordered** and changeable. No
duplicate members.
>>> word[:] ++++++++++++++++++++++++++++++++++++++++++++++
'python'
As string is immutable so we cannot modify the content, if we do then it shows error as:
LIST DATA TYPE:
===========================
It is a compound data type.
Murali Krishna Senapaty
Date: 18-04-2022
So, we can store different type of data here. >>> print(list1)
The list type can be indexed similar to string type. The list type is mutable or [1, 2, 3, 4]
changeable.
Example2:
List Methods >>> l1=['a', "murali", 10, 20, 1.23]
>>> l1
Python has a set of built-in methods that you can use on lists. ['a', 'murali', 10, 20, 1.23]
Method Description
Example3: concatenation using +
append() Adds an element at the end of the list >>> l1+l1
['a', 'murali', 10, 20, 1.23, 'a', 'murali', 10, 20, 1.23]
clear() Removes all the elements from the list Example4: repetition using *
>>> list1=[1, 2, 3, 4]
copy() Returns a copy of the list >>> list1*3
[1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]
count() Returns the number of elements with the specified value
Example4: concatenating two lists
extend() Add the elements of a list (or any iterable), to the end of >>> l1=['a', "murali", 10, 20, 1.23]
the current list >>> l2=[10,20, 'a', 'b']
>>> l1+l2
index() Returns the index of the first element with the specified ['a', 'murali', 10, 20, 1.23, 10, 20, 'a', 'b']
value
Example5:
>>> print(l1[0])
insert() Adds an element at the specified position
a
>>> print(l1[2])
pop() Removes the element at the specified position 10
>>> print(l1[1])
remove() Removes the item with the specified value Murali
print(n_list[1][3]) Ex:
o/p: 5 >>> list1[-5:-3]
[1, 4]
example11: Negative indexing
# Negative indexing in lists Ex:
my_list = ['p','r','o','b','e'] >>> list1[3:]
print(my_list[-1]) [16, 25]
o/p: e
Ex:
# fifth last item >>> list1[:3]
print(my_list[-5]) [1, 4, 8]
Output: p
Ex:
Example12: Add/Change List Elements >>> list1[:]
# Correcting mistake values in a list [1, 4, 8, 16, 25]
odd = [2, 4, 6, 8]
Ex:
# change the 1st item >>> list1[:45]
odd[0] = 1 [1, 4, 8, 16, 25]
print(odd)
o/p: [1, 4, 6, 8] * List type also supports concatenation:
>>>list1=[1,4,8,16,25]
# change 2nd to 4th items >>>list2=[36,49,64,81,100]
odd[1:4] = [3, 5, 7] >>>list3=list1+list2
print(odd) >>>list3
o/p: [1, 3, 5, 7] o/p: [1,4,8,16,25, 36,49,64,81,100]
more functions on list are: Make a copy of a list with the list() method:
list.append() : to add content at end thislist = ["apple", "banana", "cherry"]
list.insert(i,x) : to insert content at specific ith index mylist = list(thislist)
list.remove(x) : to remove x by searching. print(mylist)
List.clear() : to clear all the items of list.
List.count() : to count the no. of items exist.
Murali Krishna Senapaty
Date: 18-04-2022
Append list2 into list1: Example
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
Tuples allow duplicate values:
for x in list2: thistuple = ("apple", "banana", "cherry", "apple", "cherry")
list1.append(x) print(thistuple)
print(list1)
list1.extend(list2)
print(list1)
Example
so a list can be used like a stack with append() and pop() methods for push/pop Print the number of items in the tuple:
operations. thistuple = ("apple", "banana", "cherry")
print(len(thistuple))
++++++++++++++++++++++++++++++++++++++++++++++
Create Tuple With One Item
Tuple Datatype: To create a tuple with only one item, you have to add a comma after the
Tuple is similar to list, it is immutable or cannot be changed or read only.
item, otherwise Python will not recognize it as a tuple.
A tuple is a collection which is ordered and unchangeable.
Tuples are written with round brackets. Example
example:
Tuple1=(123,”hello”,12.34) One item tuple, remember the comma:
Tuple1 thistuple = ("apple",)
print(type(thistuple))
As tuple cannot not changed so , we can apply list() method for conversion and then we
can change it. #NOT a tuple
thistuple = ("apple")
Example print(type(thistuple))
Create a Tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple)
Tuple Items - Data Types
Tuple items can be of any data type:
Example
Allow Duplicates String, int and boolean data types:
tuple1 = ("apple", "banana", "cherry")
Since tuples are indexed, they can have items with the same value: tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False, False)
Murali Krishna Senapaty
Date: 18-04-2022
thistuple = ("apple", "banana", "cherry")
Example print(thistuple[-1])
A tuple with strings, integers and boolean values:
tuple1 = ("abc", 34, True, 40, "male")
Range of Indexes
Example You can specify a range of indexes by specifying where to start and where
What is the data type of a tuple? to end the range.
mytuple = ("apple", "banana", "cherry")
print(type(mytuple))
When specifying a range, the return value will be a new tuple with the
o/p: <class 'tuple'> specified items.
Example
The tuple() Constructor
It is also possible to use the tuple() constructor to make a tuple. Return the third, fourth, and fifth item:
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
Example print(thistuple[2:5])
Using the tuple() method to make a tuple:
thistuple = tuple(("apple", "banana", "cherry")) # note the double round-
brackets
print(thistuple) By leaving out the start value, the range will start at the first item:
Access Tuple Items Example
You can access tuple items by referring to the index number, inside square
brackets:
This example returns the items from the beginning to, but NOT included,
Example "kiwi":
Print the second item in the tuple: thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
thistuple = ("apple", "banana", "cherry") print(thistuple[:4])
print(thistuple[1])
By leaving out the end value, the range will go on to the end of the list:
Negative Indexing Example
Negative indexing means start from the end.
This example returns the items from "cherry" and to the end:
-1 refers to the last item, -2 refers to the second last item etc. thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[2:])
Example
Print the last item of the tuple: Range of Negative Indexes
Murali Krishna Senapaty
Date: 18-04-2022
Specify negative indexes if you want to start the search from the end of the
tuple:
Add Items
Example
Since tuples are immutable, they do not have a build-in append() method,
This example returns the items from index -4 (included) to index -1 but there are other ways to add items to a tuple.
(excluded)
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango") 1. Convert into a list: Just like the workaround for changing a tuple, you
print(thistuple[-4:-1]) can convert it into a list, add your item(s), and convert it back into a tuple.
print(x)
Murali Krishna Senapaty
Date: 18-04-2022
Tuples are unchangeable, so you cannot remove items from it, but you can If the number of variables is less than the number of values, you can add
use the same workaround as we used for changing and adding tuple items: an * to the variable name and the values will be assigned to the variable as
a list:
Example
Convert the tuple into a list, remove "apple", and convert it back into a tuple:
Example
thistuple = ("apple", "banana", "cherry")
Assign the rest of the values as a list called "red":
y = list(thistuple)
y.remove("apple") fruits = ("apple", "banana", "cherry", "strawberry", "raspberry")
thistuple = tuple(y)
(green, yellow, *red) = fruits
you can delete the tuple completely:
print(green)
Example print(yellow)
print(red)
The del keyword can delete the tuple completely:
thistuple = ("apple", "banana", "cherry") o/p:
del thistuple apple
print(thistuple) #this will raise an error because the tuple no longer exists banana
['cherry', 'strawberry', 'raspberry']
Unpacking a Tuple
Example
When we create a tuple, we normally assign values to it.
Add a list of values the "tropic" variable:
Packing a tuple:
fruits = ("apple", "banana", "cherry") fruits = ("apple", "mango", "papaya", "pineapple", "cherry")
a, b, c = fruits
(green, *tropic, red) = fruits
print(a)
print(b) print(green)
print(c) print(tropic)
o/p:
print(red)
apple
banana
o/p:
cherry
apple
['mango', 'papaya', 'pineapple']
Cherry
Using Asterisk*
Loop Through a Tuple
Murali Krishna Senapaty
Date: 18-04-2022
You can loop through the tuple items by using a for loop. Print all items, using a while loop to go through all the index numbers:
You can also loop through the tuple items by referring to their index number. Example
Use the range() and len() functions to create a suitable iterable. Join two tuples:
Print all items by referring to their index number: tuple3 = tuple1 + tuple2
print(tuple3)
thistuple = ("apple", "banana", "cherry")
for i in range(len(thistuple)):
print(thistuple[i]) Multiply Tuples
If you want to multiply the content of a tuple a given number of times, you
Using a While Loop can use the * operator:
You can loop through the list items by using a while loop.
Example
Multiply the fruits tuple by 2:
Use the len() function to determine the length of the tuple, then start at 0 fruits = ("apple", "banana", "cherry")
and loop your way through the tuple items by refering to their indexes. mytuple = fruits * 2
Remember to increase the index by 1 after each iteration. print(mytuple)
Example
Tuple Methods
Murali Krishna Senapaty
Date: 18-04-2022
Python has two built-in methods that you can use on tuples. Python has a set of built-in methods that you can use on sets.
Method Description Method Description
count() Returns the number of times a specified add() Adds an element to the set
value occurs in a tuple
clear() Removes all the elements from the set
index() Searches the tuple for a specified value
and returns the position of where it was copy() Returns a copy of the set
found
difference() Returns a set containing the difference
between two or more sets
++++++++++++++++++++++++++++++++++++++++++++++
difference_update Removes the items in this set that are also
Set DATATYPE: () included in another, specified set
Sets are used to store multiple items in a single variable. discard() Remove the specified item
A set is a collection which is unordered, unchangeable*, Returns a set, that is the intersection of two
intersection()
and unindexed. other sets
* Note: Set items are unchangeable, but you can remove
items and add new items. intersection_upda Removes the items in this set that are not
te() present in other, specified set(s)
Sets are written with curly brackets.
isdisjoint() Returns whether two sets have a
So, set is a collection of unordered and unindexed items.
intersection or not
syntax/example:
set1={‘a’,’b’,’c’} issubset() Returns whether another set contains this
set or not
Example Example
Duplicate values will be ignored: Using the set() constructor to make a set:
thisset = {"apple", "banana", "cherry", "apple"}
thisset = set(("apple", "banana", "cherry")) # note the double round-brackets
print(thisset) print(thisset)
o/p: o/p:
{'banana', 'cherry', 'apple'} {'apple', 'cherry', 'banana'}
We cannot access items of set using index because set does not have indexing.
but we can access items using in statement in a for loop/if statement.
Set Items - Data Types ex:
Set items can be of any data type: s1={'apple', 'banana', 'cherry'}
print("banana" in s1)
Example o/p: true
String, int and boolean data types: ex:
s1={‘apple’, ‘banana’, ‘cherry’}
set1 = {"apple", "banana", "cherry"} for x in s1:
set2 = {1, 5, 7, 9, 3} print(x)
set3 = {True, False, False} o/p:
apple
o/p: banana
{'cherry', 'apple', 'banana'} cherry
{1, 3, 5, 7, 9}
ex:
{False, True}
s1={'apple','banana','cherry'}
if('banana' in s1):
A set can contain different data types: print("exist")
else:
print("not exist")
Example o/p:
Murali Krishna Senapaty
Date: 18-04-2022
exist [staring position: ending position:incrementation]
So, [: : -1 ] means here by default starting postion is -1 as decrementation is present.
to add items: add() method is used So next position is -1+-1=-2 and so on.
ex: s1.add(“orange”) So reading the elements will be in order of positions -1, -2, -3…
So output will be reverse.
to add multiple items update() method is used
ex: s1.update([“mango”,”grapes”]) If we write [: : 1] then the starting position will be from 0 to last index , so the items will
be displayed serially.
to get the length of a set: len() method
ex: print(len(s1))
++++++++++++++++++++++++++++++++++++++++++++++
to remove an item from a set: remove() or discard()
ex:
s1.remove(“banana”)
or
Dictionary:
s1.discard(“banana”)
* if the item not found then remove() method produces error but discard() will not Dictionaries are used to store data values in key:value pairs.
produce.
A dictionary is a collection which is ordered*, changeable and do not allow
for pop operation: pop() method used duplicates.
ex:
x=s1.pop()
As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier,
to delete the set completely: del() method dictionaries are unordered.
ex:
del(s1) Dictionaries are written with curly brackets, and have keys and values:
to join two sets: union() method or update() method used
Syntax:
ex:
Dictionary name={ key1: item1, key2:item2..}
s1={'a','b','c'}
s2={1,2,3}
s3=s1.union(s2) Example
print(s1)
print(s2) Create and print a dictionary:
print(s3)
thisdict = {
using update() method:
ex:
"brand": "Ford",
s1={'a','b','c'} "model": "Mustang",
s2={1,2,3} "year": 1964
s1.update(s2) }
print(s1) print(thisdict)
print(s2)
Example o/p:
3
Print the "brand" value of the dictionary:
thisdict = {
"brand": "Ford", Dictionary Items - Data Types
"model": "Mustang",
"year": 1964 The values in dictionary items can be of any data type:
}
print(thisdict["brand"]) Example
O/P:
Ford String, int, boolean, and list data types:
thisdict = {
"brand": "Ford",
Duplicates Not Allowed "electric": False,
"year": 1964,
Dictionaries cannot have two items with the same key: "colors": ["red", "white", "blue"]
}
Example o/p:
Duplicate values will overwrite existing values: {'brand': 'Ford', 'electric': False, 'year': 1964, 'colors': ['red', 'white', 'blue']}
thisdict = {
"brand": "Ford",
"model": "Mustang", Accessing Items
"year": 1964,
"year": 2020 You can access the items of a dictionary by referring to its key name, inside
} square brackets:
print(thisdict)
Example
o/p:
{'brand': 'Ford', 'model': 'Mustang', 'year': 2020} Get the value of the "model" key:
thisdict = {
"brand": "Ford",
Dictionary Length "model": "Mustang",
"year": 1964
To determine how many items a dictionary has, use the len() function: }
x = thisdict["model"]
Example o/p:
Murali Krishna Senapaty
Date: 18-04-2022
Mustang
Get Values
Get Keys The values() method will return a list of all the values in the dictionary.
Example
The keys() method will return a list of all the keys in the dictionary.
Get a list of the values:
Example x = thisdict.values()
o/p: Example
dict_keys(['brand', 'model', 'year'])
Make a change in the original dictionary, and see that the values list gets
updated as well:
Example car = {
"brand": "Ford",
Add a new item to the original dictionary, and see that the keys list gets "model": "Mustang",
updated as well: "year": 1964
car = { }
"brand": "Ford",
"model": "Mustang", x = car.values()
"year": 1964
} print(x) #before the change
o/p:
dict_keys(['brand', 'model', 'year']) Example
dict_keys(['brand', 'model', 'year', 'color'])
Add a new item to the original dictionary, and see that the values list gets
updated as well:
Murali Krishna Senapaty
Date: 18-04-2022
car = { "model": "Mustang",
"brand": "Ford", "year": 1964
"model": "Mustang", }
"year": 1964
} x = car.items()
The items() method will return each item in a dictionary, as tuples in a list. Example
Check if "model" is present in the dictionary:
Example thisdict = {
"brand": "Ford",
Get a list of the key:value pairs
"model": "Mustang",
"year": 1964
x = thisdict.items()
}
o/p: if "model" in thisdict:
dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)]) print("Yes, 'model' is one of the keys in the thisdict dictionary")
o/p:
Yes, 'model' is one of the keys in the thisdict dictionary
Example
Make a change in the original dictionary, and see that the items list gets
updated as well: Change Values
car = { You can change the value of a specific item by referring to its key name:
"brand": "Ford",
Murali Krishna Senapaty
Date: 18-04-2022
The pop() method removes the item with the specified key name:
Example thisdict = {
"brand": "Ford",
Change the "year" to 2018:
"model": "Mustang",
thisdict = {
"year": 1964
"brand": "Ford",
}
"model": "Mustang",
thisdict.pop("model")
"year": 1964
print(thisdict)
}
thisdict["year"] = 2018 o/p:
o/p: {'brand': 'Ford', 'year': 1964}
{'brand': 'Ford', 'model': 'Mustang', 'year': 2018}
Example
Update Dictionary
The popitem() method removes the last inserted item (in versions before
The update() method will update the dictionary with the items from the given 3.7, a random item is removed instead):
argument. thisdict = {
"brand": "Ford",
The argument must be a dictionary, or an iterable object with key:value "model": "Mustang",
pairs. "year": 1964
}
Example thisdict.popitem()
print(thisdict)
Update the "year" of the car by using the update() method:
o/p:
thisdict = { {'brand': 'Ford', 'model': 'Mustang'}
"brand": "Ford",
"model": "Mustang",
"year": 1964 Example
}
thisdict.update({"year": 2020}) The del keyword removes the item with the specified key name:
o/p: thisdict = {
{'brand': 'Ford', 'model': 'Mustang', 'year': 2020} "brand": "Ford",
"model": "Mustang",
"year": 1964
Removing Items }
del thisdict["model"]
print(thisdict)
There are several methods to remove items from a dictionary:
o/p:
Example
Murali Krishna Senapaty
Date: 18-04-2022
{'brand': 'Ford', 'year': 1964}
Example
Print all values in the dictionary, one by one:
Example for x in thisdict:
print(thisdict[x])
The del keyword can also delete the dictionary completely:
thisdict = {
"brand": "Ford", Example
"model": "Mustang",
"year": 1964
You can also use the values() method to return values of a dictionary:
}
for x in thisdict.values():
del thisdict
print(x)
print(thisdict) #this will cause an error because "thisdict" no longer exists.
Example xample
The clear() method empties the dictionary: You can use the keys() method to return the keys of a dictionary:
thisdict = { for x in thisdict.keys():
"brand": "Ford", print(x)
"model": "Mustang",
"year": 1964
} Example
thisdict.clear()
print(thisdict) Loop through both keys and values, by using the items() method:
for x, y in thisdict.items():
print(x, y)
Loop Through a Dictionary
You can loop through a dictionary by using a for loop.
Copy a Dictionary
You cannot copy a dictionary simply by typing dict2 = dict1,
When looping through a dictionary, the return value are the keys of the
dictionary, but there are methods to return the values as well. because: dict2 will only be a reference to dict1, and changes made
in dict1 will automatically also be made in dict2.
Example
There are ways to make a copy, one way is to use the built-in Dictionary
Print all key names in the dictionary, one by one: method copy().
for x in thisdict:
print(x) Example
Murali Krishna Senapaty
Date: 18-04-2022
Make a copy of a dictionary with the copy() method: "year" : 2011
thisdict = { }
"brand": "Ford", }
"model": "Mustang",
"year": 1964 Example
}
mydict = thisdict.copy() Create three dictionaries, then create one dictionary that will contain the
print(mydict) other three dictionaries:
child1 = {
Another way to make a copy is to use the built-in function dict(). "name" : "Emil",
"year" : 2004
Example }
child2 = {
Make a copy of a dictionary with the dict() function: "name" : "Tobias",
thisdict = { "year" : 2007
"brand": "Ford", }
"model": "Mustang", child3 = {
"year": 1964 "name" : "Linus",
} "year" : 2011
mydict = dict(thisdict) }
print(mydict)
myfamily = {
Nested Dictionaries "child1" : child1,
"child2" : child2,
"child3" : child3
A dictionary can contain dictionaries, this is called nested dictionaries.
}
Example
Create a dictionary that contain three dictionaries: Dictionary Methods
myfamily = {
"child1" : { Python has a set of built-in methods that you can use on dictionaries.
"name" : "Emil", Method Description
"year" : 2004
}, clear() Removes all the elements from the dictionary
"child2" : {
"name" : "Tobias", copy() Returns a copy of the dictionary
"year" : 2007
}, fromkeys() Returns a dictionary with the specified keys and
"child3" : { value
"name" : "Linus",
Murali Krishna Senapaty
Date: 18-04-2022
get() Returns the value of the specified key Type conversion in python:
items() Returns a list containing a tuple for each key value =============================
pair python defines type conversion functions to convert from one datatype to another type.
int(): to convert into int datatype.
ex1:
keys() Returns a list containing the dictionary's keys
x=int(10)
y=int(2.5)
pop() Removes the element with the specified key z=int(“12”)
print(x)
popitem() Removes the last inserted key-value pair print(y)
print(z)
setdefault() Returns the value of the specified key. If the key int along with base: int(a,base)
does not exist: insert the key, with the specified here the base represents the base for the digits in given string.
value Ex:
s1=’10010’
Updates the dictionary with the specified key-value c=int(s1,2)
update()
print(c)
pairs d=int(s1,10)
print(d)
values() Returns a list of all the values in the dictionary o/p:
18
10010
Examples using different datatypes: float(): it converts into float type.
------------------------------------------------ Ex:
Python can be used as a calculator: x=float(12)
+, - *, / , ( , ) etc directly on prompt similar to the simple calculator y=float(2.5)
Here the operator / gives by default float result when we apply even on integers. z=float(“3”)
Ex: r=float(“3.6”)
>>> 12/5 print(x)
2.4 print(y)
To get a floor division we can use // operator print(z)
Ex: print(r)
>>> 12//5
2 o/p:
12.0
*when we use python prompt as a calculator then the recent calculation result is 2.5
maintained in a variable _ (underscore) 3.0
3.6
>>>x=20
>>>y=30 Str(): used to convert into string type
>>>x+y Ex:
50 x=str(‘s1’)
>>>_+70 y=str(25)
120 z=str(3.5)
Murali Krishna Senapaty
Date: 18-04-2022
print(x) c=list(str1)
print(y) print(c)
print(z) o/p:
o/p: ['h', 'e', 'l', 'l', 'o', ' ', 'h', 'o', 'w', ' ', 'a', 'r', 'e', ' ', 'y', 'o', 'u']
s1
25 dict() : to convert a tuple into a dictionary where provide (value,key)
3.5 ex:
t1=((‘a’,1), (‘b’,2), (‘c’,3))
Ord(): used to convert a character to integer to get Unicode d1=dict(t1)
Ex: print(d1)
s=’a’; o/p:
c=ord(s) {'a': 1, 'b': 2, 'c': 3}
print(c)
o/p:
97
Hex() : to convert integer to hexa decimal.
Oct(): to convert integer to octal number. Python operators:
Tuple(): to convert into tuple type
Ex: Python divides the operators in the following groups:
s="hello world"
x=tuple(s)
print(x) Arithmetic operators
o/p: Assignment operators
('h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd') Comparison operators
Logical operators
str(): it is used to convert an integer into string
ex: Identity operators
a=123 Membership operators
b=str(a) Bitwise operators
print(b)
o/p: ‘123’
complex() : it is to convert integer to complex number.
Ex:
Python Arithmetic Operators
x=complex(12,5)
print(x) Arithmetic operators are used with numeric values to perform
type(x) common mathematical operations:
set() : it is used to convert into set type Operator Name Example
ex:
s=”hello”;
c=set(s) + Addition x+y
print(c)
o/p: { ‘h’, ‘e’, ‘l’, ‘o’} - Subtraction x-y
list() : it is to convert into list type.
Ex: * Multiplication x*y
str1=”hello how are you”;
Murali Krishna Senapaty
Date: 18-04-2022
/ Division x/y &= x &= 3 x=x&3
** Exponentiation x ** y ^= x ^= 3 x=x^3
== Equal x == y
Operator Example Same As
!= Not equal x != y
= x=5 x=5
> Greater than x>y
+= x += 3 x=x+3
< Less than x<y
-= x -= 3 x=x-3
>= Greater than or equal to x >= y
*= x *= 3 x=x*3
<= Less than or equal to x <= y
/= x /= 3 x=x/3
or Returns True if one of the x < 5 or x < 4 not in Returns True if a sequence with the x not in
statements is true specified value is not present in the object y
not Reverse the result, returns False not(x < 5 and x < 10) Example:
if the result is true Ex:
a=10
list1=[1,2,3,4,5]
Python Identity Operators if(a in list1):
print("present")
Identity operators are used to compare the objects, not if they are else:
equal, but if they are actually the same object, with the same print("not present")
memory location:
Operator Description Example Python Bitwise Operators
is Returns True if both variables are x is y
the same object Bitwise operators are used to compare (binary) numbers:
Operator Name Description
is not Returns True if both variables are x is not y
not the same object & AND Sets each bit to 1 if both bits are 1
Example:
ex: | OR Sets each bit to 1 if one of two bits is 1
a=20
b=25 ^ XOR Sets each bit to 1 if only one of two bits is 1
if(a is b):
print("true") ~ NOT Inverts all the bits
else:
print("false")
<< Zero fill Shift left by pushing zeros in from the right
Python Membership Operators left shift and let the leftmost bits fall off
Example1:
Ask for the user's name and print it:
.format() method: print('Enter your name:')
this method takes the pass arguments, formats and then places them in the string x = input()
where place holders {} are present. print('Hello, ' + x)
Syntax:
{}.format(value) Example2:
Here (value) can be integer/string/float etc Num=input(“enter a number”)
Ex1: Example3:
print(“{} , how are you”.format(“alok”)) Print(“enter a number”)
Num=input()
#print("{} , how are you".format("alok"))
#o/p: alok , how are you By default the input statement accepts the data in string form, so we need type
conversion as per the user’s requirement.
#.format can be used with string
s="how are you" Multiple Input :
print("alok {} , i am fine".format(s)) We can input multiple data in one line using two methods:
1. split()
a=15; b=25 2. List comprehension
print("the 1st value is {0} and 2nd value is {1}".format(a,b))
print("the 1st value is {1} and 2nd value is {0}".format(a,b)) split(): This method helps to input multiple data.
Syntax:
x="apple"; y="orange";xcost=120;ycost=60 input().split(separator)
print("i like {} and i need {}".format(x,y))
print("i like {} and its cost is {}".format(x,xcost)) example1:
# taking two inputs at a time
#we can even use keyword arguments to format the string
x, y = input("Enter a two value: ").split()
print("hello {name}, {greetings}".format(greetings="good morning",name="sam"))
print("Number of boys: ", x)
print("Number of girls: ", y)
we can also use the format specifiers of c language here:
ex: print()
x=12.3456
print(“the value is %f”%x) # taking three inputs at a time
x, y, z = input("Enter a three value: ").split()
x=12.3456 print("Total number of students: ", x)
print("the value is %f"%x) print("Number of boys is : ", y)
y="hello" print("Number of girls is : ", z)
print("string is %s"%y) print()