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

Programming using Python

prutor.ai Amey Karkare


Dept. of CSE
IIT Kanpur

For any queries reach out to rahulgr@iitk.ac.in or rahulgarg@robustresults.com


or whatsapp 9910043510

1
Welcome Python Programming
Conditionals: if-else continued

prutor.ai

2
Oct-16 Programming
Finding min of 3 numbers
Given
a,b,c

prutor.ai
TRUE FALSE
a<=b

TRUE FALSE TRUE FALSE


a<=c b<=c

Print Print c Print b Print


a c
3
Oct-16 Programming
Givena,
b,c if a <= b:
TRUE
a<=b
FALSE if a <= c:
TRUE
a<=c
FALSE TRUE
b<=c
FALSE print ('min=',a)
else:
print ('min=',c)
Print Print c Print b Print

prutor.ai
a c

• Each branch else:


translates to an if-
else statement if (b <= c) :
• Hierarchical print ('min=',b)
branches result in
nested if-s
else:
print ('min=',c)
4
Oct-16 Programming
Nested if, if-else
• Earlier examples showed us nested if-else
if a <= b:

prutor.ai
if a <= c:

else:

else:
if b <= c) :

else:
… 5
Oct-16 Programming
Elif
• A special kind of nesting is the chain of if-else-if-
else-… statements
• Can be written elegantly using if-elif-..-else
if cond1:

prutor.ai
if cond1:
s1 s1
else: elif cond2:
if cond2: s2
s2 elif cond3:
else: s3
if cond3: elif …
s3 else
else: last-block-of-stmt

6
Oct-16 Programming
Summary of if, if-else

• if-else, nested if's, elif.


• Multiple ways to solve a problem
prutor.ai
–issues of readability,
maintainability
–and efficiency

7
Oct-16 Programming

You might also like