There are generally two types of statements. One is Simple statements and the other is Compound statements. A compound statement is said to be a collection of statements which are there to affect or maybe control the running and execution of other statements in one way or the other. In Python, we get multiple methods to build or write compound statements.

We will be discussing the various ways that we can build or construct compound statements in the python programming language.

The ‘ if ‘ statement to begin with

The ‘ if ‘ statement is usually preferable for performing those executions which are based on some condition, i.e. to perform conditional executions.

Working Example :

a = 45
b = 24
if a > b:
  print("a is greater than b")

This ‘ if ‘ statement renders the value of the expression to be true and hence prints the statement, “a is greater than b”. It checks the conditions one at a time until a true value encounters. When a true value encounters, it executes the respective statements.

A full program example of the ‘if statement and subsequent elif and else statements”.

a = 24
b = 45
if a > b:
  print("a is greater than b")
elif a == b:
  print("a and b are equal in value")
else :
  print("b is greater")
This is image title
Output of the if compound statements in python

Nested if statement

Python lets us use if statements inside one another, i.e. the nested if statement.

Working example :

a, b = 9, 16  

if b != a:   
    if b > a:   
        print("b is greater than a")   
    else:   
        print("a is greater than b")   
else:   
    print("a, b are all equal")  
This is image title
Output of the Nested If Compound Statements in Python

The ‘ range() ‘ function

This function is used to print anything whether its a number or a string elements in a sequential manner. Its indexing starts from 0 by default, and increases by 1 (if not specified by the user) and ends at the last index of the range that has been specified.

As in,

Lets look at the for loop example once again utilizing this method.

print("List Iteration")   
ls = ["python", "for", "programmers"]   
for a in range(len(ls)):   
    print(ls[a]) 
This is image title

Note : A for-loop can also be used inside a for-loop. Also, for that matter any control statement i.e. any conditional statement can be used inside any other statement or even a loop.

To understand this, we go through an example here :

print("Example of different control statements inside loop")   
carMaker = ["Bugatti", "Tata", "Vitara"]   
carModels = {'Bugatti':'Veyron', 'Tata':'Nano', 'Vitara':'Brezza'}  
for name in range(len(carMaker)):   
    for a in carModels:  
        if(a == carMaker[name]):  
            print("%s  %s" %(a, carModels[a])) 
Compound Statements Example —> Control Statements inside loops

The ‘while’ Statement –> Loops

The usage of “while statement is to run a group of statements in a loop or repeated manner till certain conditions satisfy.

Syntax :

while expression:  
    statement(s)  

We realize that Python generally uses tabs or indentation as its preferred method of combining statements. Thus, statements that are there after the while conditions/expressions – must be conveniently space to be perceived as the part of a unit code block.

The ” while ” expression gets executed in a loop manner until a provided set condition is satisfied. It stops performing the statement execution immediately when the loop condition gets a false value.

For example :

a = 1 
print ("The values of a are : ") 
while a <= 5: 
    print (a)
    a += 1 
Output of the While Compound Statement in Python

The ‘ for ‘ statement —> Another loop statement

The ‘ for ‘ statement is usually used to traverse or move through a string or list or for that matter even arrays in a specific sequential manner, i.e. one by one

Example : 

print("List Iteration")   
ls = ["python", "for", "programmers"]   
for a in ls:   
   print(a)  
This is image title
For loop — Compound Statments in Python

Various in-built functions in Python are there which are available and can take-in input of list elements or arrays or strings etc. and also traverse through that elements of lists or arrays or strings and give meaningful and useful outputs.

The ‘ with ‘ statement

Its usage is done when in need to wrap the running of a code block containing various methods accented by context manager.

An object that pronounces the runtime context to be set is known as a context manager.

Example :

In the aobe with open("C:\WelcomingFile.txt") as f: 
    data = f.read()  
    print(data)  
This is image title

In the program above, we have used the with statement to open a file to perform further operations.

zip — Another combining in-built function

Zip is a function in Python which helps in combining various similar types of  iterators like dictionary- dictionary or list-list, elements at the “ith” position.

The shortest length is utilize while the items of larger length of iterators do not execute but skip.

carMaker = ["Bugatti", "Vitara", "Tata"]   
carModels = ['Veyron', 'Brezza', 'Nano']  
for a, b in zip(carMaker, carModels):   
   print("Car model %s is a product of %s car maker company" %(b, a))  
Zip Program Example Output

The ‘ try ‘ statement

This expression sets exception handlers for a collection of statements in the code block.

  • The ‘ except ‘ command takes in code to handle the exception or error raised in try block.
  • One can also include try-except statements inside other code blocks or similar try-except code blocks.
  • the ‘ finally ‘ method: This statement is there to clean various resources

The program below, raises a ‘TypeError’ because %d excepts integer values. You should refer to the program below to understand better :

carMaker = ["Bugatti", "Vitara", "Tata"]   
carModels = {'Bugatti':'Veyron', 'Tata':'Nano', 'Vitara':'Brezza'}  
try:  
    for name in range(len(carMaker)):       
        for x in carModels:  
            if(x == carMaker[name]):  
                print("%s  %d" %(x, carModels[x]))   
except TypeError as t:   
    print('oops! Type error -- ', t)  
except ValueError:  
    print('oops! invalid  value')  
finally:  
 print('Execution of the finally code block'); 
Output of the Try statement

The ‘ Enumerate ‘ method — Another example of Compound Statements in Python

The ‘ enumerate ‘ function is a built-in Python method which takes-in input of various iterators, lists, strings, etc. and in turn, outputs tuples containing data with its index as it is in the iterating sequence.

Working Program Example :

print("List Iteration")   
carMaker = ["Maruti", "Fiat", "Honda"]   
for a, x in enumerate(carMaker):  print("%s  %s" %(a, x))  
This is image title

The various other Control Loop Statements

The various Loop control statements like break, continue and pass are there and are generally used when one wants to alter the flow of execution from its normal logical sequence. This means it is there to either exit the execution or is there to pass control to execution or skip the remaining block of code.

The “Class” definition

The class definition is there to pronounce a class instance or object.

clasdef:       "class" c_name [inheritance] ":" suitor
inheritance_ls:    "(" [list_of_expressions] ")" 
c_name:      identifier 

A class definition is a statement that is executable in nature. It is there to first evaluate the inheritance_ls list present. All items in the inheritance list must return a class object. The suitor class then executes in a new running frame.

A class instance or object then gets create using the inheritance_ls list for the super classes.

Conclusion — Compound Statements in Python

In this article we have learned about the various compound statements in python programming language. We also went through various programming examples demonstrating these compound statements.

Hope to have cleared your concept about Compound Statements in Python. Thereby, bidding you Good Bye !!

Categorized in: