You are on page 1of 54

Mepco Schlenk Engg.

college Object Oriented Programming

PYTHON
PROGRAMMING

PYTHON PROGRAMMING

▰ Invented in the Netherlands, early 90s by Guido van Rossum


▰ Named after Monty Python
▻ When he began implementing Python, Guido van Rossum was also reading the published scripts
from “Monty Python's Flying Circus”, a BBC comedy series from the 1970s. Van Rossum thought
he needed a name that was short, unique, and slightly mysterious, so he decided to call the
language Python.
▰ Open sourced from the beginning
▰ Considered a scripting language, but is much more
▰ Scalable, object oriented and functional from the beginning
▰ Used by Google from the beginning
▰ Increasingly popular

S.Muralidharan 1
Mepco Schlenk Engg. college Object Oriented Programming

▰ Python is easy to learn and use and provide many useful features for programmers. This
characteristic makes it as a widely used programming language.

S.Muralidharan 2
Mepco Schlenk Engg. college Object Oriented Programming

S.Muralidharan 3
Mepco Schlenk Engg. college Object Oriented Programming

Comparison between Programming Language & Scripting Language

PROGRAMMING LANGUAGE SCRIPTING LANGUAGE


Formal languages, which comprises a set of Languages which help in writing programs for
instructions to produce various kinds of outputs a special run-time environment that automate
the execution of tasks
Has organized way of communicating with computer Need not be an in an organized way

Compiler based Languages are executed much Execution speed is slow


faster while interpreter based languages are
executed slower
Pre-declared variables Varying degree of automatic variable
management
Can be divided into high-level / Low-level languages Can be divided into client-server scripting
or Compier-based or Interpreter-based languages. languages and server-side scripting
languages.
Difficult to learn and implement as more Easier to learn and implement as it shifts the
programmer effort is needed burden to the machine
C, C++ JavaScript, Python, Perl, PHP and Ruby

Used to develop various applications such as Mostly used for web development
desktop, web, mobile, etc., 7

Run
with some input

Write/Edit

NO OK
?
YES
YES
More
Inputs?
NO
8

S.Muralidharan 4
Mepco Schlenk Engg. college Object Oriented Programming

Running Python

Character Set & Tokens in Python

▰ Character set is a bunch of identifying elements in the programming language.


▻ Letters:-- A-Z, a-
Letters: a- z
▻ Digits:-- 0 to 9
Digits:
▻ Special Symbols:-
Symbols:- space + - / ( ) [ ] = ! = < > , ‘ “ $ # ; : ? &
▻ White Spaces:-
Spaces:- Blank Space , Horizontal Tab, Vertical tab, Carriage Return.
▻ Other Characters:-
Characters:- Python can process all 256 ASCII and Unicode Characters.
▰ Individual elements that are identified by programming language are called tokens or lexical
unit.

10

S.Muralidharan 5
Mepco Schlenk Engg. college Object Oriented Programming

Keywords
▰ Keywords are also called as
reserved words these are having Key
Words
special meaning in python language.
language.
The words are defined in the python
interpreter hence these cant be used
as programming identifiers
identifiers.. Punctuators Identifiers
▰ Few Keywords in Python
TOKENS
and assert global if
break class import in
continue def is lambda
del elif not or Operators Literals
else except pass print
exec finally raise return
11
for from try while

Identifier
▰ A Python Identifier is a name given
to a function, class, variable, module, Key
Words
or other objects that you’ll be using
in your Python program.
program.
▰ In short, its a name appeared in the
program..
program Punctuators Identifiers

▻ For example
example:: a, b, c TOKENS
▻ a b and c are the identifiers and
▻ a b & c and , are the tokens

Operators Literals

12

S.Muralidharan 6
Mepco Schlenk Engg. college Object Oriented Programming

Identifier – Naming convention in Python


▰ An identifier can be a combination of uppercase letters,
lowercase letters, underscores, and digits (0-9). Hence, the
Key
following are valid identifiers:
identifiers: myClass
myClass,, my_variable,
my_variable, var_1
var_1, and Words
print_hello_world..
print_hello_world
▰ The first character must be letter.
letter.
▰ Special characters such as %, @, and $ are not allowed within
identifiers..
identifiers Punctuators Identifiers
▰ An identifier should not begin with a number
number.. Hence, 2variable is
not valid, but variable
variable22 is acceptable.
acceptable. TOKENS
▰ Python is a case-
case-sensitive language and this behaviour extends
to identifiers
identifiers..Thus
Thus,, Labour and labour are two distinct identifiers
in Python
Python..
▰ You cannot use Python keywords as identifiers
identifiers..
▰ You can use underscores to separate multiple words in your Operators Literals
identifier..
identifier
SOME VALID IDENTIFIERS
IDENTIFIERS:: Myfile
Myfile11 ,DATE
,DATE99_7_8,y3
,y3m9d3,
13
SOME INVALID IDENTIFIERS:
IDENTIFIERS: MY
MY--REC,28
REC,28dre,break,elif,del
dre,break,elif,del

Literals
▰ Literals are also called as constants or constant
values these are the values which never change Key
Words
during the execution of program
program..
▰ Sequence of letters enclosed in quotes is called
string or string literal or constant
constant..
Punctuators Identifiers
▰ Python supports both form of quotes i.e.
▰ ‘Hello’ & “Hello” TOKENS

▰ What are the types of literals?


▻ String Literals or Constants.
Constants.
▻ Numeric Literals or Constants.
Constants.
Operators Literals
▻ Boolean Literals or Constants.
Constants.
▻ Special Literal None.
None.
▻ Literal Collections.
Collections. 14

S.Muralidharan 7
Mepco Schlenk Engg. college Object Oriented Programming

Types of Literals

15

String Literals
▰ String Literals : Sequence of letters enclosed in quotes is called string or string literal or constant.
▰ Representation of a string literal
▻ >>> s = “Hello Python”

▰ To access the first character on the string you just created, type and enter the variable name s
and the index 0 within square brackets like this:
>>>s[0]
▻ You’ll get this output: ‘H’
▰ To access the last character, you can use this expression:
>>>s[len(s)-1]
Len() function is used to find the length of the string.
▰ There is actually an easier way to access the last item on the string:
17
>>>s[-1]

S.Muralidharan 8
Mepco Schlenk Engg. college Object Oriented Programming

Types of Strings
▰ Python supports two ways of representation of strings:
1) Single Line Strings. 2)Multi Line Strings.
▰ Strings created using single quote or double quote must end in one line are called single line
strings
▰ For Example:
▻ Item=“Computer” Or Item= ‘Computer’
▰ Strings created using single quote or double quote and spread across multiple lines are called
Multi Line Strings. By adding backslash \ one can continue to type on next line.
▰ For instance: Item = ‘Key\
board’
▰ Size of string
▻ ‘\\’ -size is 1 (\ is an escape sequence)
▻ ‘abc’ -size is 3
▻ “\ab” -size is 2 18
▻ “Raama\’s Laptop” -size is 13

Escape Sequences

\r Carriage return

\t Tab

\n New Line

\f  ASCII Formfeed

\b  ASCII Backspace

\’ & \”  Single Quote & Double Quote


\\  Back Slash

S.Muralidharan 9
Mepco Schlenk Engg. college Object Oriented Programming

 backspace

 Tab
 Back Slash
 Carriage return

 Single Quote

 Double Quote

 New Line

20

 integer
▰ Numerical Literals have the following types:
▻ int or integers - Whole numbers
▻ float - real values
▻ Complex - Complex numbers
 To convert integer to binary
Binary digit followed by 0b

 To convert integer to octal

 float  Octal digit zero followed by letter o

 To convert integer to Hexadecimal


Hexadecimal digit zero followed by x

 binary

S.Muralidharan 10
Mepco Schlenk Engg. college Object Oriented Programming

Literals
▰ Operators are tokens that trigger some computation
when applied to a variable
variable.. Key
Words

Punctuators Identifiers

TOKENS
Op Meaning Example Remarks

+ Addition 9+2 is 11
9.1+2.0 is 11.1
- Subtraction 9-2 is 7
9.1-2.0 is 7.1
* Multiplication 9*2 is 18
Operators Literals
9.1*2.0 is 18.2
/ Division 9/2 is 4.25 In Python3
9.1/2.0 is 4.55 Real div.
// Integer 9//2 is 4
Division 22
% Remainder 9%2 is 1

▰ Operator precedence & Associativity in Python

24

S.Muralidharan 11
Mepco Schlenk Engg. college Object Oriented Programming

25

▰ Punctuators are also called as separators Key


Words

Punctuators Identifiers

TOKENS

Operators Literals

26

S.Muralidharan 12
Mepco Schlenk Engg. college Object Oriented Programming

While typing the Python program…


▰ Python does not use any symbol to terminate the statement.
▰ Use consistent indentation. no explicit brackets, e.g. { }, to group statements
▻ The first line with less indentation is outside of the block.
▻ The first line with more indentation starts a nested block.
▻ Often a colon appears at the start of a new block. (E.g. for function and class definitions.).
▰ Single line comment always starts with #. Multiline comment will be in triple quotes. For
example “’ write a program to find the simple interest “’.
▻ Note: Triple apostrophe is called docstrings.
▰ You should always have whitespace around operators but not with parenthesis.
▰ Python is case sensitive.
▰ A group of statements which are part of another statement or function is called Block or
Code Block. 27

▰ A variable pointing to a value of certain type can be made to point to a value/object of different
type this is called Dynamic Typing.
10
x

10
x

Hello World

28

S.Muralidharan 13
Mepco Schlenk Engg. college Object Oriented Programming

INPUT ( ) FUNCTION

▰ Input( ) Function is a built in function of python used to read values from the user
▰ The general format or syntax of the input() is:
Variable_to_hold_the_value=input(message)
Where,
variable_to_Hold_the_Value is a variable which is the label for a memory location where the value is stored.

Int converted into float

Int converted into Hex

Int converted into Octal

29

Print() function

▰ print( ) Function is a built in function of python used to display the values on the screen

30

S.Muralidharan 14
Mepco Schlenk Engg. college Object Oriented Programming

VARIABLES AND ASSIGNMENTS

Error! String can not be divided.

Type returned as string

Type returned as float

Type returned as integer


31

By default Input in
python will be a string.

32

S.Muralidharan 15
Mepco Schlenk Engg. college Object Oriented Programming

▰ Python provides us with two inbuilt functions to read the input from the keyboard.
▻ input ( prompt ) val = input("Enter your value: ")
print(val)
In newer version of python
name = input('What is your name?\n')
What is your name?
print(name)
Ram
Ram

g = raw_input("Enter your name : ")


▻ raw_input ( prompt ) print g
In older version of python(like Python 2.x)

33

Note that float to int conversion


is truncation, not rounding off

34

S.Muralidharan 16
Mepco Schlenk Engg. college Object Oriented Programming

VARIABLES AND ASSIGNMENTS

▰ A simple assignment statement


Variable = Expression;
▰ Computes the value (object) of the expression on the right hand side expression (RHS)
▰ Associates the name (variable) on the left hand side (LHS) with the RHS value
▰ = is known as the assignment operator.
▰ Python allows multiple assignments
Binds x to 10 and y to
x, y = 10, 20 20
▰ Evaluation of multiple assignment statement:
▻ All the expressions on the RHS of the = are first evaluated before any binding happens.
▻ Values of the expressions are bound to the corresponding variable on the LHS.

x, y = 10, 20
x is bound to 21 and y to
11 at the end of the 35
x, y = y+1, x+1 program

36

S.Muralidharan 17
Mepco Schlenk Engg. college Object Oriented Programming

Loop & Conditional


statements

37

For statement

CONDITION : ALL THE FOOT BALLS AVAILABLE WITH X SHOULD SHOOTED INTO THE GOAL POST

HOW MANY BALLS = 3


HOW MANY TIMES THE PLAYER SHOULD GO IN BETWEEN = 3
38

S.Muralidharan 18
Mepco Schlenk Engg. college Object Oriented Programming

39

▰ A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a
string).
fruits = ["apple", "banana", "cherry"] apple
for x in fruits: Output Banana
print(x) cherry
▰ With the break statement we can stop the loop before it has looped through all the items:
fruits = ["apple", "banana", "cherry"]
for x in fruits: apple
print(x) Output
Banana
if x == "banana":
break
▰ With the continue statement we can stop the current iteration of the loop, and continue with the next:
fruits = ["apple", "banana", "cherry"] Apple
for x in fruits: Output
cherry
if x == "banana":
continue
print(x)
40

S.Muralidharan 19
Mepco Schlenk Engg. college Object Oriented Programming

▰ To loop through a set of code a specified number of times, we can use the range() function,
▻ The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by
default), and ends at a specified number. 0
for x in range(6): Output 1
print(x) 2
3
4
▻ Note that range(6) is not the values of 0 to 6, but the values 0 to 5.
5
▻ The range() function defaults to 0 as a starting value, however it is possible to specify the starting value by
adding a parameter: range(2, 6), which means values from 2 to 6 (but not including 6).
▻ The range() function defaults to increment the sequence by 1, however it is possible to specify the increment
value by adding a third parameter: range(2, 30, 3) 2
for x in range(2, 15, 3): Output 5
print(x) 8
11
14
41

▰ The else keyword in a for loop specifies a block of code to be executed when the loop is
finished: 0
1
for x in range(6): Output 2
print(x)
3
else:
4
print("Finally finished!")
5
Finally finished
▻ The else block will NOT be executed if the loop is stopped by a break statement.
0
for x in range(6): 1
if x == 3: break Output 2
print(x)
else:
print("Finally finished!")

42

S.Muralidharan 20
Mepco Schlenk Engg. college Object Oriented Programming

▰ Nested Loops
▻ A nested loop is a loop inside a loop.
▻ The "inner loop" will be executed one time for each iteration of the "outer loop":
adj = ["red", "big", "tasty"] red apple
fruits = ["apple", "banana", "cherry"] Output red banana
red cherry
for x in adj: big apple
for y in fruits: big banana
print(x, y) big cherry
tasty apple
tasty banana
tasty cherry

43

While/Do While statements

CONDITION : ALL THE FOOT BALLS AVAILABLE WITH X SHOULD SHOOTED INTO THE GOAL POST

HOW MANY BALLS = “Don’t know”


HOW MANY TIMES THE PLAYER SHOULD GO IN BETWEEN = “Till X has the last ball”
44

S.Muralidharan 21
Mepco Schlenk Engg. college Object Oriented Programming

Python does not have built-in functionality


to explicitly create a do while loop like other
WHILE languages. DO..WHILE

45

While …
▰ Example for while 1
i = 1 2
while i < 6:
Output : 3
print(i) 4
i += 1 5
▰ With the break statement we can stop the loop even if the while condition is true:
i = 1 Output : 1
while i < 6: 2
print(i) 3
if i == 3:
break
i += 1
▰ With the continue statement we can stop the current iteration, and continue with the next:
i = 0 1
while i < 6: Output :
2
i += 1 4
if i == 3: 5
continue 6 46
print(i)

S.Muralidharan 22
Mepco Schlenk Engg. college Object Oriented Programming

▰ With the else statement we can run a block of code once when the condition no longer is
true:
i = 1 1
while i < 6: Output : 2
print(i) 3
i += 1 4
else: 5
print("i is no longer less than 6") i is no longer less than 6

▰ The pass statement is a null statement. But the difference between pass and comment is
that comment is ignored by the interpreter whereas pass is not ignored.
value=raw_input('Enter your option ') Output : Enter your option mepco
print ' Your option is ' , value Your option is mepco
i=0 value is : 5
The pass statement is a null statement. But the difference
while i< len(value):
between pass and comment is that comment is ignored by
i+=1 the interpreter whereas pass is not ignored.
pass
print 'value is :' , i 47

Switch case…

48

S.Muralidharan 23
Mepco Schlenk Engg. college Object Oriented Programming

▰ Switch case is available after Python 3.10 only.


▰ From version 3.10 upwards, Python has implemented a switch case feature called “structural
pattern matching”. You can implement this feature with the match and case keywords.
Syntax Example
match term: lang = input("What's the programming language you want to learn? ")
case pattern-1: match lang:
action-1 case "JavaScript":
case pattern-2: print("You can become a web developer.")
action-2 case "Python":
case pattern-3: print("You can become a Data Scientist")
action-3 case "PHP":
case _: print("You can become a backend developer")
action-default case "Solidity":
print("You can become a Blockchain developer")
case "Java":
print("You can become a mobile app developer")
case _:
print("The language doesn't matter,what matters is solving problems.")

49

If-else statement
IF I have to buy coffee, I
will go right to canteen.
Else I will go straight to
Hostel.

50

S.Muralidharan 24
Mepco Schlenk Engg. college Object Oriented Programming

▰ Examples :
a = 33
b = 33
if b > a:
print("b is greater than a")
Output a and b are equal
elif a == b:
print("a and b are equal")

a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b: Output a is greater than b
print("a and b are equal")
else:
print("a is greater than b") 51

52

S.Muralidharan 25
Mepco Schlenk Engg. college Object Oriented Programming

▰ Break & Continue

The break statement is used to terminate


the loop or statement in which it is Continue is also a loop control
present. statement just like the break
If the break statement is present in the statement. continue statement is
nested loop, then it terminates only opposite to that of break statement,
those loops which instead of terminating the loop, it forces
contains break statement. to execute the next iteration of the loop.
53

Additional Information about Python

▰ Python follows Short-circuit Evaluation


▻ Do not evaluate the second operand of binary short-circuit logical operator if the result can be
deduced from the first operand.
▻ Also applies to nested logical operators
▰ A function called range() help to iterate over a sequence of numbers.
>>> range(10)
Example 1: Example 2: Example 3:

54

S.Muralidharan 26
Mepco Schlenk Engg. college Object Oriented Programming

STRINGS IN PYTHON

55

Python Strings

▰ Strings in Python have type str


▰ They represent sequence of characters
▻ Python does not have a type
corresponding to character.
▰ Strings are enclosed in single quotes(')
or double quotes(“)
More readable when we use print statement
▻ Both are equivalent
▰ Backslash (\) is used to escape quotes
and special characters

56

S.Muralidharan 27
Mepco Schlenk Engg. college Object Oriented Programming

▰ len function gives the length of a string

\n is a single character: the special


character representing newline

57

▰ In Python, + and * operations


have special meaning when
operating on strings
• + is used for concatenation
of (two) strings
• * is used to repeat a string,
an int number of time
• Function/Operator
Overloading
▰ A str object is immutable;
that is, its content cannot be
changed once the string is
created.

58

S.Muralidharan 28
Mepco Schlenk Engg. college Object Oriented Programming

▰ Strings can be indexed


▰ When the index is too large, it
▰ First character has index 0
results in error.

▰ Negative indices start counting


from the right
▰ Negatives indices start from -1
▰ -1 means last, -2 second last, ...

59

Slicing
When start and end have
▰ To obtain a substring the same sign, if start
▰ s[start:end] means substring of s >=end, empty slice is
starting at index start and ending at returned
index end-1
▰ s[0:len(s)] is same as s
▰ Both start and end are optional
▻ If start is omitted, it defaults to 0
▻ If end is omitted, it defaults to the
length of string
▰ s[:] is same as s[0:len(s)], that is
same as s
▰ Reverse indexing can also be used 60

S.Muralidharan 29
Mepco Schlenk Engg. college Object Oriented Programming

61

▰ Comparison of strings
Example 1 Example 2

62

S.Muralidharan 30
Mepco Schlenk Engg. college Object Oriented Programming

Various in-built string functions

63

64

S.Muralidharan 31
Mepco Schlenk Engg. college Object Oriented Programming

LISTS

65

Lists

▰ Unlike C++ or Java, Python Programming Language doesn’t have arrays. To hold a sequence
of values, then, it provides the ‘list’ class. A Python list can be seen as a collection of values.
▰ To create python list of items, you need to mention the items, separated by commas, in
square brackets.
>>> colors=['red','green','blue']
▰ A Python list may hold different types of values.
>>> days=['Monday','Tuesday','Wednesday',4,5,6,7.0]
▰ A list may have python list.

66

S.Muralidharan 32
Mepco Schlenk Engg. college Object Oriented Programming

▰ Slicing a list

Slicing of List

67

▰ Reassigning values of a list

Reassigning of a value in
the List

Deleting selective items


in the list

Deleting the list


68

S.Muralidharan 33
Mepco Schlenk Engg. college Object Oriented Programming

▰ Concatenation of lists

Concatenation of Lists

Multiplying a Python list by


an integer makes copies of
its items that a number of
times while preserving the
order

69

▰ Checking membership in a list

Checking membership in
a list

▰ Iterating on a list using loops

Iterating on a list

70

S.Muralidharan 34
Mepco Schlenk Engg. college Object Oriented Programming

▰ Appending a list To add a new member


to a list –
and change the list
object itself – we use
the
list's append() method:

▰ Changing the value at a specific index


To change the value
that exists at a given
list's index, we can
simply reassign it as
we would a variable:

71

Example :
# All elements of list are true
l = [4, 5, 1]
print(all(l))
Output:
The all() function True
▰ all() builtin function is an inbuilt # All elements of list are false False
function in Python l = [0, 0, False]
print(all(l))
False
which returns true True
if all the elements # Some elements of list are
of a given iterable( # true while others are false
List, Dictionary, l = [1, 0, 6, 7, False]
Tuple, set, etc) are print(all(l))
True else it returns # Empty List
False. l = []
print(all(l))
▰ any() builtin function Example :
# All elements of list are True
Python any() l = [4, 5, 1]
function returns True print(any(l))
if any of the Output:
elements of a given # All elements of list are False True
iterable(List,Dictiona l = [0, 0, False] False
print(any(l))
ry, Tuple, set, etc) True
are True else it # Some elements of list are True False
returns False. # while others are False
# l = [1, 0, 6, 7, False]
# print(any(l))

# Empty list
72
l = []
print(any(l))

S.Muralidharan 35
Mepco Schlenk Engg. college Object Oriented Programming

73

TUPLES

75

S.Muralidharan 36
Mepco Schlenk Engg. college Object Oriented Programming

▰ Python Tuple is a collection of objects separated by


commas. In some ways, a tuple is similar to a list in
terms of indexing, nested objects, and repetition but a
tuple is immutable, unlike lists which are mutable.

76

▰ Accessing Values in Tuple in Python

Using Positive Index

Using Negative Index

▰ Concatenating Tuples

77

S.Muralidharan 37
Mepco Schlenk Engg. college Object Oriented Programming

▰ Nesting of Tuples ▰ Deleting of Tuples

▰ Repetition Tuples ▰ Length of Tuples

▰ Slicing Tuples in Python ▰ Converting Tuples into List

78

Tuple Vs List

79

S.Muralidharan 38
Mepco Schlenk Engg. college Object Oriented Programming

Tuple Vs List

List

Tuple

List is Mutable

Tuple is Immutable

80

FUNCTIONS

81

S.Muralidharan 39
Mepco Schlenk Engg. college Object Oriented Programming

FUNCTIONS IN PYTHON
▰ A function is a block of code which only runs when it is called. You can pass data, known as
parameters, into a function. A function can return data as a result.
▰ Creating a Function : def my_function():
print("Hello from a function")

▰ Calling a Function : def my_function():


print("Hello from a function")

my_function()

▰ Calling a Function with arguments : def my_function(fname):


print(" Mr. “ + fname )

my_function(“Murali")
my_function(“Srinivas")
my_function(“Vijay")

NOTE : A parameter is the variable listed inside the parentheses in the function definition.
An argument is the value that is sent to the function when it is called. 82

▰ Default arguments : def my_function(country = "Norway"): Output :


print("I am from " + country)

my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")

▰ Passing a List as an Argument : def my_function(food): Output :


for x in food:
print(x)

fruits = ["apple", "banana", "cherry"]

my_function(fruits)

83

S.Muralidharan 40
Mepco Schlenk Engg. college Object Oriented Programming

▰ Return values from a function : def my_function(x): Output :


return 5 * x

print(my_function(3))
print(my_function(5))
print(my_function(9))

▰ Recursive Function : def tri_recursion(k): Output :


if(k > 0):
result = k + tri_recursion(k - 1)
print(result)
else:
result = 0
return result

print("\n\nRecursion Example Results")


tri_recursion(6) 84

▰ Variable length arguments : def print_info(arg1,*var): Output:


... print("Result")
... print (arg1)
... for var1 in var:
... print (var1)
... return

85

S.Muralidharan 41
Mepco Schlenk Engg. college Object Oriented Programming

Dictionary

86

Dictionary

▰ Dictionary is a data structure in which we store values as a pair of key and value. Each key is

separated from its value by a colon (:), and consecutive items are separated by commas.
▰ The entire items in a dictionary are enclosed in curly brackets({}).

▰ SYNTAX: dictionary_name = {key_1: value_1, key_2: value_2, key_3: value_3}

87

S.Muralidharan 42
Mepco Schlenk Engg. college Object Oriented Programming

88

▻ Creating a Dictionary
• You can create a dictionary by enclosing the items inside a pair of curly braces ({}).
• Each item consists of a key, followed by a colon, followed by a value. The items are
separated by commas. For example, the following statement:
students = {"111-34-3434":"John", "132-56-6290":"Peter"}
creates a dictionary with two items.
• The item is in the form key:value. The key in the first item is 111-34-3434, and its
corresponding value is John.
• The key must be of a hashable type such as numbers and strings. The value can be of any
type.
• You can create an empty dictionary by using the following syntax:
▻ students = {} # Create an empty dictionary 90

S.Muralidharan 43
Mepco Schlenk Engg. college Object Oriented Programming

▻ Adding, Modifying, and Retrieving Values


• To add an item to a dictionary, use the syntax:
dictionaryName[key] = value
• For example:
students["234-56-9010"] = "Susan“
• If the key is already in the dictionary, the preceding statement replaces the value for the
key.
• To retrieve a value, simply write an expression using dictionaryName[key].
• If the key is in the dictionary, the value for the key is returned. Otherwise, a KeyError
exception is raised.
91

92

S.Muralidharan 44
Mepco Schlenk Engg. college Object Oriented Programming

93

94

S.Muralidharan 45
Mepco Schlenk Engg. college Object Oriented Programming

95

▰ Deleting items :

96

S.Muralidharan 46
Mepco Schlenk Engg. college Object Oriented Programming

97

98

S.Muralidharan 47
Mepco Schlenk Engg. college Object Oriented Programming

▰ Looping items:

99

Sorting Items and Looping over Items in a Dictionary

100

S.Muralidharan 48
Mepco Schlenk Engg. college Object Oriented Programming

Nested Dictionaries

101

Difference between a List and a Dictionary

▰ First, a list is an ordered set of items. But, a dictionary is a data structure that is used for matching one item

▰ (key) with another (value).

▰ • Second, in lists, you can use indexing to access a particular item. But, these indexes should be a number. In

▰ dictionaries, you can use any type (immutable) of value as an index. For example, when we write Dict['Name'],
Name acts as an index but it is not a number but a string.

▰ • Third, lists are used to look up a value whereas a dictionary is used to take one value and look up another

▰ value. For this reason, dictionary is also known as a lookup table.

▰ Fourth, the key-value pair may not be displayed in the order in which it was specified while defining the

▰ dictionary. This is because Python uses complex algorithms (called hashing) to provide fast access to the items
stored in the dictionary. This also makes dictionary preferable to use over a list of tuples.
102

S.Muralidharan 49
Mepco Schlenk Engg. college Object Oriented Programming

When to use which Data Structure?

▰ Use lists to store a collection of data that does not need random access.

▰ • Use lists if the data has to be modified frequently.

▰ • Use a set if you want to ensure that every element in the data structure must be unique.

▰ • Use tuples when you want that your data should not be altered.

103

SET

104

S.Muralidharan 50
Mepco Schlenk Engg. college Object Oriented Programming

▰ Sets are used to store multiple items in a single variable.


▰ A set is a collection which is unordered, unchangeable, and unindexed.
▰ 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.
▰ Un changeable
▻ Set items are unchangeable, meaning that we cannot change the items after the set has been
created.
▰ Un indexed
▻ Indexing not possible
105

thisset = {"apple", "banana", "cherry", "apple"}


Output
print(thisset) {'banana', 'cherry', 'apple'}

print(len(thisset)) 3
<class 'set‘>
print(type(myset))

▰ The major advantage of using a set, as opposed to a list, is that it has a highly optimized
method for checking whether a specific element is contained in the set.

106

S.Muralidharan 51
Mepco Schlenk Engg. college Object Oriented Programming

# typecasting list to set


myset = set(["a", "b", "c"]) OUTPUT
print(myset) {'c', 'b', 'a'}

# Adding element to the set


myset.add("d")
print(myset) {'d', 'c', 'b', 'a'}

107

# A Python program to demonstrate adding elements in a set


# Creating a Set
people = {“Murali", “Sriram", “Harini"}

print("People:", end = " ")


print(people)

# This will add Lakshmi in the set


people.add(“Lakshmi")

# Adding elements to the set using iterator


for i in range(1, 6):
people.add(i)

print("\nSet after adding element:", end = " ")


print(people)

OUTPUT
People: {‘Murali', ‘Sriram', ‘Harini'}
Set after adding element: {1, 2, 3, 4, 5, ‘Murali', ‘Sriram', ‘Harini‘ , ‘Lakshmi'}
108

S.Muralidharan 52
Mepco Schlenk Engg. college Object Oriented Programming

Union operation on Python Sets

▰ Two sets can be merged using union() function or | operator. The values are accessed and traversed
with merge operation perform on them to combine the elements, at the same time duplicates are
removed.
# Python Program to demonstrate union of two sets

people = {“Murali", “Sriram", “Srinivas"}


venue = {“Computer Lab", “Seminar Hall"}
substitute = {“Raman", “Raju"}

# Union using union() function


population = people.union(venue) OUTPUT
print("Union using union() function") Union using union() function
print(population) {‘Murali', 'Sriram', 'Computer Lab', 'Seminar Hall', 'Srinivas‘}

population = people.union(venue,substitute) Union using union() function with 3 sets


print("Union using union() function with 3 sets") {'Raju', 'Sriram', 'Srinivas', 'Raman', 'Computer Lab', 'Murali', 'Seminar Hall'}
print(population)

# Union using "|“ operator


population = people|substitute Union using '|' operator
print("\nUnion using '|' operator") {'Murali', 'Sriram', 'Raman', 'Raju', 'Srinivas'} 109
print(population)

Intersection operation on Python Sets

▰ This can be done through intersection() or & operator. Common Elements are selected. They are similar
to iteration over the Hash lists and combining the same values on both the Table.
# Python program to demonstrate intersection of two sets
set1 = set()
set2 = set()

for i in range(5):
set1.add(i)
for i in range(3,9):
set2.add(i)

# Intersection using intersection() function


set3 = set1.intersection(set2)
OUTPUT
print("Intersection using intersection() function") Intersection using intersection() function
print(set3) {3, 4}
# Intersection using "&" operator
set3 = set1 & set2
Intersection using '&' operator
print("\nIntersection using '&' operator") {3, 4}
print(set3) 110

S.Muralidharan 53
Mepco Schlenk Engg. college Object Oriented Programming

Finding Difference of Sets in Python

▰ To find difference in between sets. This is done through difference() or – operator.


# Python program to demonstrate difference of two sets
set1 = set()
set2 = set()

for i in range(5):
set1.add(i)
for i in range(3,9):
set2.add(i)

# Difference of two sets using difference() function


set3 = set1.difference(set2)

print(" Difference of two sets using difference() function") OUTPUT


print(set3) Difference of two sets using difference() function
{0, 1, 2}
# Difference of two sets using '-' operator
set3 = set1 - set2
Difference of two sets using '-' operator
print("\nDifference of two sets using '-' operator") {0, 1, 2}
print(set3)
111

S.Muralidharan 54

You might also like