Programming 10
Programming 10
Conditional Statements
In daily routine
If it is very hot, I will skip exercise.
If there is a quiz tomorrow, I will first study and then sleep.
Otherwise I will sleep now.
If I have to buy coffee, I will go left. Else I will go
straight.
if-else statement
• Compare two integers and print the min.
6 10
if x < y:
print (x)
else:
print (y) Output
print (‘is the min’) 6
if statement (no else!)
General form of the if statement
if boolean-expr : S1
S1
S2
S2
Execution of if statement
◦ First the expression is evaluated.
◦ If it evaluates to a true value, then S1 is executed and then control moves to the S2.
◦ If expression evaluates to false, then control moves to the S2 directly.
if-else statement
General form of the if-else statement
if boolean-expr :
S1 S1 S2
else:
S2 S3
Execution of if-else statement
S3
◦ First the expression is evaluated.
◦ If it evaluates to a true value, then S1 is executed and then control moves to
S3.
◦ If expression evaluates to false, then S2 is executed and then control moves to
S3.
◦ S1/S2 can be blocks of statements!
Nested if, if-else
if a <= b:
if a <= c:
…
else:
…
else:
if b <= c) :
…
else:
…
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: 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
…