Python Programming – Compound statement

In this Page, We are Providing Python Programming – Compound statement. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Python Programming – Compound statement

Compound statement

Compound statements contain groups of other statements, they affect or control the execution of those other statements in some way. In general, compound statements span multiple lines, although a whole compound statement can be contained in one line.

The if, while, and for statements are the traditional control flow compound statements, try to specify exception handlers and/or cleanup code for a group of statements. Function and class definitions are also syntactically compound statements.

Compound statements consist 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. Each clause header begins with a uniquely identifying keyword and ends with a colon. A suite is a group of statements controlled by a clause. A suite can be one or more semicolon-separated simple statements on the same line as the header, following the header’s colon, or it can be one or more indented statements on subsequent lines. Only the latter form of the suite can contain nested compound statements.

The colon is required primarily to enhance readability.

if a == b
print aversus

if a == b:
print a

Notice how the second one is slightly easier to read. Another minor reason is that the colon makes it easier for editors with syntax highlighting; they can look for colons to decide when indentation needs to be increased.

A code block (or simply “block”) is a piece of Python program text that is executed as a unit. Few examples of blocks are a module, a function body, a class definition, etc. Each command typed interactively is a block.

If statement

The if statement is used for conditional execution:

if_stmt : : = " if " expression " : " suite
( " elif " expression " : " suite ) *
["else" " : " suite]

It selects exactly one of the suites by evaluating the expressions one by one until one is found to be true, then that suite is executed (and no other part of the if statement is executed or evaluated). If all expressions are false, the suite of the else clause (if present) is executed.

>>> var=100 
>>> if var==100 :
. . .             print ' var has value 100 '
. . .
var has a value of 100 
>>>
>>> var=100 
>>> if var<> 100 :
. . .           print ' var does not have value 100 '
. . . else:
. . .           print 'var has value 100'
. . .
var has a value of 100 
>>>
>>> var=100 
>>> if var<100 : 
. . .            print ' var has value less than 100 '
. . . elif var>100 : 
. . .            print ' var has value greater than 100'
. . . else:
. . .           print ’ var has value 100 '
. . .
var has a value of 100

The following example shows that if the evaluation of expression gives a result either None, an empty string (‘ ‘), zero (0), or Boolean False, then the condition is considered as false.

>>> if None or ' ' or 0 or False:
. . .          print ' Atleast one condition is true ' 
. . . else:
. . .           print 'None of the condition is true'
. . . 
None of the condition is true

There may be a situation when there is a need to check for another condition after a condition resolves to true. In such a situation, the nested if statement can be used.

>>> var=100
>>> if isinstance ( var , str) :
. . .                 print ' var is a string '
. . . elif (type(var) is int) :
. . .          if var<> 100 :
. . .             print ' var does not have value 100 '
. . . else:
. . .        print 'var has value 100'
. . .
var has a value of 100

While statement

The while statement is used for repeated execution of a group of statements as long as an expression is true:

while_stmt " while " expression " : "  suite
[ " else " suite ]

This compound statement repeatedly tests the expression, and if it is true, it executes the first suite; if the expression is false (which may be the first time it is tested) the suite of the else clause (if present) is executed and the loop terminates.

>>> var=1
>>> while var<=5: 
. . .  print ' Count ',var
. . .  var=var+l
. . .
Count 1
Count 2 
Count 3
Count 4 
Count 5
>>> print ' The loop ends '
The loop ends

The above code can also be witten as follows:

>>> var=l
>>> while var<=5 :
. . .         print ' Count ' , var
. . .   var=var+1
. . . else:
. . .     print 'The loop ends'
. . .
Count 1 
Count 2 
Count 3 
Count 4 
Count 5 
The loop ends

A break statement executed in the first suite terminates the loop without executing the else clause’s suite.

>>> var=l
>>> while var<=5:
. . .   print  ' Count ', var
. . .     var=var+1
. . .      if var==4:
. . .        break
. . . else:
. . .        print ' The loop ends '
. . .
Count 1 
Count 2 
Count 3

A continuous statement executed in the first suite skips the rest of the suite and goes back to testing the expression.

>>> var=0
>>> while var<=5:
. . .         var=var+1
. . .         if var>=3 and var<=4:
. . .              continue
. . .     print 'Count ',var
. . .
Count 1 
Count 2 
Count 5
Count 6

Consider a scenario where the condition never becomes false. This results in a loop that never ends; such a loop is called an infinite loop. One needs to use the keyboard Ctrl+C to come out of the program.

For statement

The for statement is used to iterate over the elements of a sequence (such as a string, tuple, or list) or another iterable object:

for_stmt :  : = " for " target_list " in " expression_list " : " suite 
                            [ " else " suite ]

The expression list expression_list is evaluated once; it should yield an iterable object. An iterator is created for the result of the expression_list. The suite is then executed once for each item provided by the iterator, in the order of ascending indices. Each item, in turn, is assigned to the target list target_list using the standard rules for assignments, and then the suite is executed. When the items are exhausted (which is immediately when the sequence is empty), the suite in the else clause (if present) is executed, and the loop terminates.

>>> for i in [ 1 , 2 , 3 , 4 , 5 ] :
. . . print ' Count ' , i
. . .
Count 1 
Count 2 
Count 3 
Count 4 
Count 5
>>> print ' The loop ends '
The loop ends

The above code can also be written as follows:

>>> for i in range ( 1 , 6 ) :
. . .         print ' Count ' , i
. . . else : 
. . .           print 'The loop ends'
. . .
Count 1 
Count 2 
Count 3
Count 4 
Count 5
The loop ends

A break statement executed in the first suite terminates the loop without executing the else clause’s suite.

>>> for i in [ 1 , 2 , 3 , 4 , 5 ] :
. . . if i==4 :
. . .  break
. . .    print ' Count ' , i
. . . else :
. . .      print  ' The loop ends '
. . .
Count 1 
Count 2 
Count 3

A continue statement executed in the first suite skips the rest of the suite and continues with the next item, or with the else clause if there was no next item.

>>> for i in [ 1 , 2 , 3 , 4 , 5 ] :
. . . if i==4 :
. . . continue
. . .         print  ' Count  ' , i
. . .  else :
. . .       print  ' The loop ends '
. . . 
Count 1 
Count 2 
Count 3 
Count 5 
The loop ends

There might be a scenario where one needs to print the item along with its index. The following example demonstrates this scenario using enumerate () built-in function (discussed later in this chapter).

>>> shuttles= [ ' Columbia ' , ' endeavour ' , ' challenger ' ]
>>> for index , value in enumerate ( shuttles ) :
. . . print index, value
. . .
0 Columbia
1 endeavor
2 challenger 
>>>
>>> value
'challenger'
>>> index 
2

It can also be observed that the target list is not deleted when the loop is finished.

Leave a Comment