Chapter 3: Compound statements


Compound statements contain one or groups of other statements; they affect or control the execution of those other statements in some way.

In general, they span multiple lines, but can be also be listed in a single line.

The if, while and for statements implement traditional control flow constructs, whereas try specifies exception handlers and/or cleanup code for a group of statements, while the with statement allows the execution of initialization and finalization code around a block of code. Function and class definitions are also syntactically compound statements.

They consists of one or more ‘clauses’. A clause consists of a 'header' and a ‘suite’.

The 'clause' headers of a particular compound statement are all at the same indentation level. They should begins with an uniquely identifying keyword and should ends with a colon.

'suite' is a group of statements controlled by a clause. It can be of one or more semicolon-separated simple statements on the same line as the header, following the header’s colon (one liner), or it can be one or more indented statements on subsequent lines. Only the latter form of a suite can contain nested compound statements; the following is illegal, mostly because it wouldn’t be clear to which if clause a following else clause would belong:

Traditional Control Flow Constructs


if Statement

The if statement is used for conditional execution similar to that in most common languages. If statement can be constructed in three format depending on our need.

  • if: when we have "if something do something" condition
  • if .. else: when we have condition like "if something: do something else do something else"
  • if .. elif ..else: When we have too many conditions or nested conditions

if

This format is used when specific operation needs to be performed if a specific condition is met. Syntax:

if <condition>:
        <code block>

Where:

  • <condition>: sentence that can be evaluated as true or false.
  • <code block>: sequence of command lines.
  • The clauses elif and else are optional and  several elifs for the if may be used but only  one else at the end.
  • Parentheses are only required to avoid ambiguity. Example:

In [2]:
password = input("Please enter the password:")
if password == "Simsim":
    print("\t> Welcome to the cave")


Please enter the password:Simsim
	> Welcome to the cave

In [3]:
x = "Mayank"
y = "TEST"
if y == "TEST":
    print(x)


Mayank

In [4]:
if y:
    print("Hello World")


Hello World

In [5]:
z = None
if z:
    print("TEST")

In [6]:
x = 11
if x > 10:
    print("Hello")
    if x > 10.999999999999:
        print("Hello again")
        if x % 2 == 0:
            print("Bye bye bye ...")


Hello
Hello again

In [7]:
x = 10
y = None
z = "111"
print(id(y))
if x:
    print("Hello in x")

if y:
    print("Hello in Y")

if z:
    print("Hello in Z")


1827972304
Hello in x
Hello in Z

if ... else statement

if <condition>:
    <code block>
else:
    <code block>

Where:

  • <condition>: sentence that can be evaluated as true if statement if statemente or false.
  • <code block>: sequence of command lines.
  • The clauses elif and else are optional and several elifs for the if may be used but only one else at the end.
  • Parentheses are only required to avoid ambiguity.

In [9]:
x = "Anuja"

if x == "mayank":
    print("Name is mayank")
else:
    print("Name is not mayank and its", x)


Name is not mayank and its Anuja

if ...elif ... else statement

if <condition>:
    <code block>
elif <condition>:
    <code block>
elif <condition>:
    <code block>
else:
    <code block>

Where:

  • <condition>: sentence that can be evaluated as true or false.
  • <code block>: sequence of command lines.
  • The clauses elif and else are optional and several elifs for the if may be used but only one else at the end.
  • Parentheses are only required to avoid ambiguity.

In [11]:
# temperature value used to test
temp = 31

if temp < 0:
    print ('Freezing...')
elif 0 <= temp <= 20:
    print ('Cold')
elif 21 <= temp <= 25:
    print ('Room Temprature')
elif 26 <= temp <= 35:
    print ('Hot')
else:
    print ('Its very HOT!, lets stay at home... \nand drink lemonade.')


Hot

In [13]:
# temperature value used to test
temp = 60

if temp < 0:
    print ('Freezing...')
elif 0 <= temp <= 20:
    print ('Cold')
elif 21 <= temp <= 25:
    print ('Room Temprature')
elif 26 <= temp <= 35:
    print ('Hot')
else:
    print ('Its very HOT!, lets stay at home... \nand drink lemonade.')


Its very HOT!, lets stay at home... 
and drink lemonade.

Imagine that in the above program, 23 is the temperature which was read by  some sensor or manually entered by the user and Normal is the response of the program.


In [1]:
a = "apple"
b = "banana"
c = "Mango"
if a == "apple":
    print("apple")
elif b == "Mango":
    print("mango")
elif c == "Mango":
    print("My Mango farm")


apple

In [11]:
x = list(range(10))

a = 0
x.reverse()
print(x)
while x:
    a = x.pop()
    print(a)
print(a)


[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
0
1
2
3
4
5
6
7
8
9
9

In [12]:
x = list(range(10))
print(x)
a = 0
x.reverse()
while x:
    a = x.pop(0)
    print(a)
print(a)


[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
9
8
7
6
5
4
3
2
1
0
0

In [7]:
items = "This is a test"
for count, item in enumerate(items[1:], start=11):  
    print(item, count, end=" ")
    if 'i' in item: break  
else:
    print("\nFinished")

print(count)


h 11 i 12 12

One line if

There are instances where we might need to have If the code block is composed of only one line, it can be written after the colon:

if temp < 0: print 'Freezing...'

Since version 2.5, Python supports the expression:

<variable> = <value 1> if <condition> else <value 2>

Where <variable> receives <value 1> if <condition> is true and <value 2> otherwise.


In [1]:
x = 20

if x > 10: print ("Hello ")

print("-"*30)

val = 1 if x < 10 else 24
print(val)


Hello 
------------------------------
24