Presented By: Prof. Madhuri N.
Shinde
Email id: mnshinde@[Link]
Outcomes
By the end of the lecture student will be able to:
use decision control statements
Problem Solving, Programming and Python
Programming by Madhuri Shinde
Content
Decision control statements
Problem Solving, Programming and Python
Programming by Madhuri Shinde
Decision making
Decision making in programming is same as daily life
decisions
checking of conditions occurring while execution
of the program
specifying actions taken according to the conditions
Decision structures produce TRUE or FALSE outcome
after evaluating expressions
You need to determine which action to take and which
statements to execute if outcome is TRUE and which
statements to execute if outcome is FALSE
Problem Solving, Programming and Python
Programming by Madhuri Shinde
Decision control statements
Selection / conditional Basic loop structures /
Branching Statements Iterative Statements
if while loop
break
if - else for loop
continue
Nested if Nested loop
pass
if - elif - else else with loop
Problem Solving, Programming and Python
Programming by Madhuri Shinde
Any Queries ???
Thank you !
Mail id: mnshinde@[Link]
Problem Solving, Programming and Python
Programming by Madhuri Shinde
Lecture 2
Problem Solving, Programming and Python
Programming by Madhuri Shinde
Outcomes
By the end of the lecture student will be able to:
make use of selection/conditional branching
Statements:
Problem Solving, Programming and Python
Programming by Madhuri Shinde 8
Content
Selection/conditional branching Statements:
if,
if-else,
nested if,
if-elif-else statements.
Problem Solving, Programming and Python
Programming by Madhuri Shinde 9
if statement
if statement is used to test particular condition.
If the condition is True, then it executes the block of
statements which is called as if block
Syntax:
if <condition>:
<statements>
Problem Solving, Programming and Python
Programming by Madhuri Shinde 10
if statement
Problem Solving, Programming and Python
Programming by Madhuri Shinde 11
if – else statement
The if – else statement provides an else block
combined with the if statement which is executed in
the false case of the condition
Syntax:
if <condition>:
<statements 1>
else:
<statements 2>
Problem Solving, Programming and Python
Programming by Madhuri Shinde 12
if – else statement
Problem Solving, Programming and Python
Programming by Madhuri Shinde 13
if – else statement
Example: Check given number is odd or even
Problem Solving, Programming and Python
Programming by Madhuri Shinde 14
Nested if statement
Nested if statements means the if statement is inside another
if statement
The nested statement is executed only when the outer “if
statement” True
Syntax:
if <condition>:
if <condition>:
<statements 1>
else:
<statements 2>
else:
<statements 3>
Problem Solving, Programming and Python
Programming by Madhuri Shinde 15
Nested if statement
Problem Solving, Programming and Python
Programming by Madhuri Shinde 16
if – elif – else statement
The if – else statement provides an else block
combined with the if statement which is executed in
the false case of the condition
Syntax:
if <condition>:
<statements 1>
else:
<statements 2>
Problem Solving, Programming and Python
Programming by Madhuri Shinde 17
if – elif – else statement
Problem Solving, Programming and Python
Programming by Madhuri Shinde 18
Any Queries ???
Thank you !
Mail id: mnshinde@[Link]
Problem Solving, Programming and Python
Programming by Madhuri Shinde 19
Lecture 3
Problem Solving, Programming and Python
Programming by Madhuri Shinde
Outcomes
By the end of the lecture student will be able to:
understand basic loop Structures/Iterative statements
Problem Solving, Programming and Python
Programming by Madhuri Shinde 21
Content
Basic loop Structures/Iterative statements:
while loop,
for loop,
Nested loops,
Problem Solving, Programming and Python
Programming by Madhuri Shinde 22
Basic loop Structures /
Iterative statements:
In programming, loops are a sequence of instructions
that does a specific set of instructions or tasks based
on some conditions and continue the tasks until it
reaches certain conditions.
The control structures of programming languages
allow us to execute a statement or block of statement
repeatedly.
Types of Loops in Python:
while loops
for loops
Problem Solving, Programming and Python
Programming by Madhuri Shinde 23
while Loop
while loop is used to execute a block of statements
repeatedly until a given a condition is satisfied & when the
condition becomes false, the line immediately after the loop
in program is executed
Syntax:
while condition:
statement(s)
# body of loop that has set of statements which require
s repeated execution
Problem Solving, Programming and Python
Programming by Madhuri Shinde 24
while Loop
Example to display “python programming” 3 times
count=0
while count < 3:
print("python programming")
count=count+1
print("Outside the loop")
Problem Solving, Programming and Python
Programming by Madhuri Shinde 25
while Loop
i =1 Output:
sum1=0 i: 1 Sum is: 0
while i <6: i: 2 Sum is: 1
print("i:",i,"\tSum is:",sum1) i: 3 Sum is: 3
i: 4 Sum is: 6
sum1 =sum1 + i
i: 5 Sum is: 10
i=i+1
Final sum is: 15
print("Final sum is:",sum1)
Problem Solving, Programming and Python
Programming by Madhuri Shinde 26
for Loop
With the ‘for’ loop we can execute a set of statements, once
for each item in a list, tuple, set etc. A for loop is used for
iterating over a sequence.
Syntax:
For Iterative_variable in sequence:
Statement (s)
# body of loop that has set of statements which requir
es repeated execution
Problem Solving, Programming and Python
Programming by Madhuri Shinde 27
for Loop
Example:
#Print each fruit in a fruit list:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
Output:
apple
banana
cherry
Problem Solving, Programming and Python
Programming by Madhuri Shinde 28
.
Range
The range() function returns a sequence of numbers,
starting from 0 by default, and increments by 1 (by default),
and stops before a specified number
Syntax
range(start, end, step)
Example:
x = range(8) -> 0, 1, 2, 3, 4, 5, 6, 7
x = range(3, 8) - > 3, 4, 5, 6, 7
x = range(3, 8, 2) - > 3, 5, 7
x = range(8, 1, -2) - > 8, 6, 4, 2
Problem Solving, Programming and Python
Programming by Madhuri Shinde 29
Quiz for with range
for i in range(1, 4):
print("Lockdown ",float( i))
print("Stay safe at Home")
else:
print("Lockdown ",float( i + 1))
print("Stay safe at home")
print("Take care, wear mask when you want
to go out for emergency work ")
Problem Solving, Programming and Python
Programming by Madhuri Shinde 30
For with range
31
Problem Solving, Programming and Python
Programming by Madhuri Shinde
For with range
Problem Solving, Programming and Python
Programming by Madhuri Shinde 32
for Loop
sum1=0 Output:
for i in range (1,6):
print("i:",i,"\t Sum is:",sum1) i: 1 Sum is: 0
sum1 =sum1 + i i: 2 Sum is: 1
i: 3 Sum is: 3
print("Final sum is:",sum1)
i: 4 Sum is: 6
i: 5 Sum is: 10
Final sum is: 15
Problem Solving, Programming and Python
Programming by Madhuri Shinde 33
Looping Through a String
Since a string is simply a sequence of characters,
the for loop iterates over each character automatically
Problem Solving, Programming and Python
Programming by Madhuri Shinde 34
Nested Loops
A nested loop is a loop within a loop
The "inner loop" will be executed first for each
iteration of the "outer loop":
Problem Solving, Programming and Python
Programming by Madhuri Shinde 35
Exercise: nested for loop
Print Pattern using loop
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
Suppose I want in reverse of it what changes I have to do in above code?
36
Problem Solving, Programming and Python
Programming by Madhuri Shinde
Nested loops with list
Problem Solving, Programming and Python
Programming by Madhuri Shinde 37
Any Queries ???
Thank you !
Mail id: mnshinde@[Link]
Problem Solving, Programming and Python
Programming by Madhuri Shinde 38
Lecture 4
Problem Solving, Programming and Python
Programming by Madhuri Shinde
Outcomes
By the end of the lecture student will be able to:
make use of break, continue, pass statements in
python program
Break Continue Pass statements by Madhuri
Shinde 40
Content
break
continue
pass
else statement used with loops
Break Continue Pass statements by Madhuri
Shinde 41
break Statement
With the break statement we can stop the loop even if
the looping condition is true.
Syntax:
break
Break Continue Pass statements by Madhuri
Shinde 42
break Statement
Example with ‘while’ loop:
#Exit the loop when i is 3:
i=1 Output:
while i<5:
print(i) 1
if i == 3: 2
break 3
i += 1
Break Continue Pass statements by Madhuri
Shinde 43
break Statement
Example with ‘for’ loop:
#Exit the loop when x is "banana":
fruits = ["apple","banana","cherry"] Output:
for x in fruits:
print(x) apple
if x =="banana": banana
break
Break Continue Pass statements by Madhuri
Shinde 44
continue Statement
With the continue statement we can stop the current
iteration, and continue with the next iteration
Syntax:
continue
Break Continue Pass statements by Madhuri
Shinde 45
continue Statement
Example with ‘while’ loop:
#Continue to the next iteration if i is 3:
Output:
i=1
while i<5:
1
print(i)
2
i += 1
3
if i == 3:
4
continue
Break Continue Pass statements by Madhuri
Shinde 46
continue Statement
Example with ‘for’ loop:
# do not print banana:
fruits = ["apple", "banana", "cherry"] Output:
for x in fruits:
if x == "banana": apple
continue
cherry
print(x)
Break Continue Pass statements by Madhuri
Shinde 47
pass statement
It is used when a statement is required syntactically
but you do not want any command or code to execute.
The pass statement is a null operation; nothing
happens when it executes.
Syntax:
pass
Break Continue Pass statements by Madhuri
Shinde 48
pass statement
Break Continue Pass statements by Madhuri
Shinde 49
pass statement
Example with ‘while’ loop:
Output:
i=1
while i<5: 1
print(i) 2
if i == 3: 3
pass 4
i += 1
Break Continue Pass statements by Madhuri
Shinde 50
Pass v/s Continue
Break Continue Pass statements by Madhuri
Shinde 51
else statement used with loops
The else block is placed just after the for or while loop.
It is executed only when the loop is not terminated by a
break statement
else statement with for loop:
Syntax:
for variable in sequence:
# Body of for loop
else:
Statement
Break Continue Pass statements by Madhuri
Shinde 52
else statement with for loop
Break Continue Pass statements by Madhuri
Shinde 53
else statement with while loop
Syntax:
while condition:
# Body of while loop
else:
Statement
Break Continue Pass statements by Madhuri
Shinde 54
else statement with while loop
Break Continue Pass statements by Madhuri
Shinde 55
Any Queries ???
Thank you !
Email id: mnshinde@[Link]
Break Continue Pass statements by Madhuri
Shinde 56
Lecture 5
Problem Solving, Programming and Python
Programming by Madhuri Shinde
Outcomes
By the end of the lecture student will be able to:
use tuples
Problem Solving, Programming and Python
Programming by Madhuri Shinde 58
Tuples
A tuple represents a collection of elements.
These elements are put in parenthesis () separated by
comma
Sequence of immutable objects
Tuples are expressed in following format:
tuple1 = (element1, element2, element3, .....)
Problem Solving, Programming and Python
Programming by Madhuri Shinde 59
Tuples
1. Creation of tuples
2. Accessing values in tuples
3. Updating tuples / trying to add new element
4. Deleting elements of the tuple
5. Displaying tuple
6. Loop through a tuple
Problem Solving, Programming and Python
Programming by Madhuri Shinde 60
1. Creation of tuples
Problem Solving, Programming and Python
Programming by Madhuri Shinde 61
2. Accessing values in tuples
Problem Solving, Programming and Python
Programming by Madhuri Shinde 62
3. Updating tuples / trying to add
new element
Problem Solving, Programming and Python
Programming by Madhuri Shinde 63
4. Deleting elements of the tuple
Problem Solving, Programming and Python
Programming by Madhuri Shinde 64
5. Displaying Tuple
Problem Solving, Programming and Python
Programming by Madhuri Shinde 65
6. Loop through a tuple
Problem Solving, Programming and Python
Programming by Madhuri Shinde 66
7. Range()
Problem Solving, Programming and Python
Programming by Madhuri Shinde 67
8. enumerate()
Problem Solving, Programming and Python
Programming by Madhuri Shinde 68
9. Copying tuple
Problem Solving, Programming and Python
Programming by Madhuri Shinde 69
Tuple operations
1. len()
2. Concatenation “+”
3. Repetition “*”
4. "in" check if element exist
5. "not in" check if element exist
6. max()
7. min()
8. sum()
9. all(): returns True, when all elements are true
10. any(): returns True, when any elements are true
11. tuple():converts an iterable(tuple,string,set,dict) to tuple
12. sorted():new sorted tuple
Problem Solving, Programming and Python
Programming by Madhuri Shinde 70
Tuple operation
Problem Solving, Programming and Python
Programming by Madhuri Shinde 71
Tuple operations
Problem Solving, Programming and Python
Programming by Madhuri Shinde 72
Tuple operations
Problem Solving, Programming and Python
Programming by Madhuri Shinde 73
Tuple operations
Problem Solving, Programming and Python
Programming by Madhuri Shinde 74
Tuple operations
Problem Solving, Programming and Python
Programming by Madhuri Shinde 75
Tuple methods
Problem Solving, Programming and Python
Programming by Madhuri Shinde 76
Any Queries ???
Thank you !
Mail id: mnshinde@[Link]
Problem Solving, Programming and Python
Programming by Madhuri Shinde 77
Lecture 7
Problem Solving, Programming and Python
Programming by Madhuri Shinde
Outcomes
By the end of the lecture student will be able to:
make use of dictionary
Problem Solving, Programming and Python
Programming by Madhuri Shinde
Content
Dictionary
Creating
Assessing
Adding
Updating values
Dictionary method
Problem Solving, Programming and Python
Programming by Madhuri Shinde
Dictionary
A dictionary is a collection which is unordered,
changeable and indexed.
In Python dictionaries are written with curly
brackets, and they have keys and values.
Syntax:
DictionaryName = {key: value}
Problem Solving, Programming and Python
Programming by Madhuri Shinde
Creating a dictionary
Values : any datatype, duplicated
Keys : not repeated, immutable.
language = {1: 'python', 2: 'C', 3: 'C++'}
print(language)
{1: 'python', 2: 'C', 3: 'C++'}
#empty Dictionary
Dict = {}
print(Dict)
{} Problem Solving, Programming and Python
Programming by Madhuri Shinde
Creating a dictionary dict() function
# Creating a Dictionary with dict() method
Dict=dict()
print(Dict)
{}
Dict = dict({1: 'Python', 2: 'C++', 3:'C'})
print(Dict)
{1: 'Python', 2: 'C++', 3: 'C'}
# Creating a Dictionary with each item as a Pair
Dict = dict([(1, 'Python'), (2, 'C++')])
print(Dict)
{1: 'Python', 2: Problem
'C++'} Solving, Programming and Python
Programming by Madhuri Shinde
Creating a Nested Dictionary
Dict = {1: 'Python', 2: 'C++',
3:{'developed by' : 'Dennis M. Ritchie',
'year' : '1972'}}
print(Dict)
{1: 'Python', 2: 'C++', 3: {'year': '1972', 'developed by': 'Dennis
M. Ritchie'}}
Problem Solving, Programming and Python
Programming by Madhuri Shinde
Adding elements in a dictionary
# Adding elements one at a time
Dict[0] = 'Python'
Dict[2] = 'C++'
Dict[3] = 20
print(Dict)
{0: 'Python', 2: 'C++', 3: 20}
Problem Solving, Programming and Python
Programming by Madhuri Shinde
Adding elements in a dictionary
# Adding set of values to a single Key
Dict['multi'] = 2, 3, 4
print(Dict)
{0: 'Python', 2: 'C++', 3: 20, 'multi': (2, 3, 4)}
# Adding Nested Key value to Dictionary
Dict[5] = {'Nested' :{'1' : 'Life', '2' : 'Love'}}
print(Dict)
{0: 'Python', 2: 'C++', 3: 20, 5: {'Nested': {'2': 'Love', '1': 'Life'}}, 'mul
ti': (2, 3, 4)}
Problem Solving, Programming and Python
Programming by Madhuri Shinde
Assessing elements
In order to access the elements of a dictionary refer to its key
name. Key can be used inside square brackets.
get() method
Dict={0: 'Python', 2: 'C++', 3: 20, 5: {'Nested': {'2': 'Love', '1':
'Life'}}, 'multi': (2, 3, 4)}
print(Dict[0])
Python
print([Link](3))
20
Problem Solving, Programming and Python
Programming by Madhuri Shinde
Assessing elements
Dict={0: 'Python', 2: 'C++', 3: 20, 5: {'Nested': {'2': 'Love', '1':
'Life'}}, 'multi': (2, 3, 4)}
print(Dict[5])
{'Nested': {'1': 'Life', '2': 'Love'}}
print(Dict['multi'])
(2, 3, 4)
print(Dict['multi'][2])
4
Problem Solving, Programming and Python
Programming by Madhuri Shinde
Updating values
Dict={0: 'Python', 2: 'C++', 3: 20, 5: {'Nested': {'2': 'Love', '1':
'Life'}}, 'multi': (2, 3, 4)}
Dict[3] = 'HTML‘
print(Dict)
{0: 'Python', 'multi': (2, 3, 4), 2: 'C++', 3: 'HTML', 5: {'Nested
': {'1': 'Life', '2': 'Love'}}}
Problem Solving, Programming and Python
Programming by Madhuri Shinde
Dictionary method
Method Description
clear() Removes all the elements from the dictionary
copy() Returns a copy of the dictionary
fromkeys() Returns a dictionary with the specified keys and value
get() Returns the value of the specified key
items() Returns a list containing a tuple for each key value pair
keys() Returns a list containing the dictionary's keys
pop() Removes the element with the specified key
popitem() Removes the last inserted key-value pair
setdefault() Returns the value of the specified key. If the key does not exist:
insert the key, with the specified value
update() Updates the dictionary with the specified key-value pairs
values() Returns a list of all the values in the dictionary
Problem Solving, Programming and Python
Programming by Madhuri Shinde
1 clear() method:
Dict={0: 'Python', 2: 'C++'}
Removes all the elements from the dictionary
Syntax:
[Link]()
[Link]()
print(Dict)
{}
Problem Solving, Programming and Python
Programming by Madhuri Shinde
2 copy() method:
Returns a copy of the dictionary
Syntax:
[Link]()
Dict={0: 'Python', 2: 'C++'}
new_dict=[Link]()
print("original dictionary: ", Dict)
print("new dictionary: ", new_dict)
original dictionary: {0: 'Python', 2: 'C++'}
new dictionary: {0: 'Python', 2: 'C++'}
Problem Solving, Programming and Python
Programming by Madhuri Shinde
3 fromkeys() method:
Returns a dictionary with the specified keys and value
Syntax:
fromkeys(seq, val)
where seq : The sequence to be transformed into a dictionary.
val : Initial values that need to be assigned to the generated keys.
Defaults to None.
seq = { 'RollNo', 'Name', 'ContactNo'}
res_dict = [Link](seq)
print ("The dict : ", res_dict)
The dict : {'ContactNo': None, 'Name': None, 'RollNo': None}
Problem Solving, Programming and Python
Programming by Madhuri Shinde
4 get() method:
returns the value of the Syntax:
specified key [Link](key, default=none)
Dict={0: 'Python', 2: 'C++'}
print(Dict[0]) print([Link](0))
print(Dict[3]) print([Link](2))
print([Link](3))
Python Python
KeyError: 3 C++
None
Problem Solving, Programming and Python
Programming by Madhuri Shinde
5 items() method:
Returns a list containing a tuple for each key value pair
Syntax:
[Link]()
Dict={0: 'Python', 2: 'C++'}
print([Link]())
dict_items([(0, 'Python'), (2, 'C++')])
Problem Solving, Programming and Python
Programming by Madhuri Shinde
6 keys() method:
Returns a list containing the dictionary's keys
Syntax:
[Link]()
Dict={0: 'Python', 2: 'C++'}
print([Link]())
dict_keys([0, 2])
Problem Solving, Programming and Python
Programming by Madhuri Shinde
7 pop() method:
Removes the element with the specified key
Syntax:
[Link](key, def )
where key : The key whose key-value pair has to be returned and removed.
def : The default value to return if specified key is not present.
Dict={0: 'Python', 2: 'C++'}
[Link](2)
print(Dict)
print("return default value",[Link]('C',4))
print(Dict)
{0: 'Python'}
return default value 4
{0: 'Python'}
Problem Solving, Programming and Python
Programming by Madhuri Shinde
8 popitem() method:
Removes the last inserted key-value pair
Syntax:
[Link]()
Dict={0: 'Python', 1:"C", 2: 'C++'}
removed=[Link]()
print("Removed element: ",removed)
print("After removing element from dictionary:", Dict)
Removed element: (2, 'C++')
After removing element from dictionary:
{0: 'Python', 1: 'C'}
Problem Solving, Programming and Python
Programming by Madhuri Shinde
9 setdefault() method:
Returns the value of the specified Syntax:
key. If the key does not exist: insert [Link](key[, default_value])
the key, with the specified value
Dict={0: 'Python', 1:"C", 2: 'C++'} Dict={0: 'Python', 1:"C", 2:
sv = [Link](1, "HTML") 'C++'}
print(sv) sv = [Link](4, "HTML")
print(Dict) print(sv)
print(Dict)
C
{0: 'Python', 1: 'C', 2: 'C++'} HTML
{0: 'Python', 1: 'C', 2: 'C++', 4: 'H
TML'}
Problem Solving, Programming and Python
Programming by Madhuri Shinde
10 update() method:
Updates the dictionary with the specified key-value pairs
Syntax:
[Link]([other])
Dict={0: 'Python', 1:"C", 2: 'C++'}
[Link]({1: "HTML"})
print(Dict)
[Link]({"4": "HTML"})
print(Dict)
{0: 'Python', 1: 'HTML', 2: 'C++'}
{0: 'Python', 1: 'C', 2: 'C++', '4': 'HTML'}
Problem Solving, Programming and Python
Programming by Madhuri Shinde
11 values() method:
Returns a list of all the values in the dictionary
Syntax:
[Link]()
Dict={0: 'Python', 1:"C", 2: 'C++'}
print([Link]())
dict_values(['Python', 'C', 'C++'])
Problem Solving, Programming and Python
Programming by Madhuri Shinde
What will be the output of above Python code?
d1={"abc":5,"def":6,"ghi":7}
print(d1[0])
A. Abc
B. 5
C. {"abc":5}
D. Error
Answer: D Error
Problem Solving, Programming and Python
Programming by Madhuri Shinde
Which method to be used to get following result of Python
code?
dict={"Joey":1,"Rachel":2}
dict.______ ({"Phoebe":2})
print(dict)
dict={"Joey":1,"Rachel":2,"Phoebe":2}
[Link] ({"Phoebe":2})
Problem Solving, Programming and Python
Programming by Madhuri Shinde
Select correct ways to create an empty dictionary
A. sampleDict = {}
B. sampleDict = dict()
C. sampleDict = dict{}
Answer: A and B
Problem Solving, Programming and Python
Programming by Madhuri Shinde
Select all correct ways to copy a dictionary in Python
A. dict2 = [Link]()
B. dict2 = dict([Link]())
C. dict2 = dict(dict1)
D. dict2 = dict1
Answer: A, B and C
Problem Solving, Programming and Python
Programming by Madhuri Shinde
Select the correct ways to get the value of marks key.
student = { "name": “Rohan", "class": 4, "marks": 75 }
A. m = [Link](2)
B. m = [Link](‘marks’)
C. m = student[2])
D. m = student[‘marks’])
Answer: B and D
Problem Solving, Programming and Python
Programming by Madhuri Shinde
Select the correct way to print Rohan’s age.
student = {1: {'name': ‘Rohan', 'age': '27’}, 2: {'name': ‘Riya',
'age': '22’}}
A. student[0][1]
B. student[1][“age”]
C. student[0][“age”]
Answer: B
Problem Solving, Programming and Python
Programming by Madhuri Shinde
Any Queries ???
Thank you !
Mail id: mnshinde@[Link]
Problem Solving, Programming and Python
Programming by Madhuri Shinde