Writing compound statements in Python

Writing compound statements in Python

In this post, we'll learn about different compound statements including if condition, loop (while, for) statement, and loop control ( continue, break, pass) statement in Python

A compound statement is defined as a group of statements that affect or control the execution of other statements in some way. Python programming language provides different ways to construct or write compound statements. These are mainly defined as:

if Statement

This statement is used for conditional execution. The syntax of the statement is as follows,

if expression: suite  
elif expression: suite  
else: suite  

if statement evaluates the expressions (condition) one by one until one is found to be true then executes the following suite (a group of statements) for example

a, b = 10, 20  
if a > b:    
    print("a is greater than b")   
elif a < b:     
    print("b is greater than a")   
else:     
    print("Both a and b are equal") 

This is image title

Python programming language allows us to use one if statement inside other if statement, for example:

a, b = 10, 20  

if a != b:   
    if a > b:   
        print("a is greater than b")   
    else:   
        print("b is greater than a")   
else:   
    print("Both a and b are equal")  

This is image title

while Statement

while statement is used to execute a block of statements repeatedly until a given condition is fulfilled. Syntax of the statement is as follows

while expression:  
    statement(s)  

As we know that Python uses indentation as its method of grouping statements, statements after while expression: must be indented by the same number of character spaces otherwise they will not be considered as part of a single block of code. While statement executes repeatedly until a given condition is fulfilled and executes the statement immediately after the loop when the condition becomes false for example,

i = 1  
while i < 6:  
  print('inside while loop - printing value of i -', i)  
  i += 1  
  print('after while loop finished')

This is image title

Else statement can also be used to execute a statement when the while condition becomes false 

i = 1  
while i < 6:  
  print('inside while loop - printing value of i -', i);  
i += 1  
else :  
  print('after while loop finished') 

This is image title

Please note that it is not recommended to use a while loop for iterators as mentioned in the above example instead of using for-in (or for each) loop method in Python. 

for statement

for statement is used to traverse a list or string or array in a sequential manner for example 

print("List Iteration")   
l = ["python", "for", "programmers"]   
for i in l:   
   print(i)  

This is image title

There are few in-built Python functions available that take input as list or string or array etc. and iterate through elements of list or string or array and return index, data or both.

Range() method

Which returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number. Please refer to the example for more detail

print("List Iteration")   
l = ["python", "for", "programmers"]   
for i in range(len(l)):   
    print(l[i]) 

This is image title

We can use for-in loop inside another for-in loop. we can even use any type of control statement condition inside of any other type of loop. Please refer to the example for more detail

print("List Iteration")   
carMake = ["Maruti", "Fiat", "Honda"]   
carModel = {'Maruti':'Alto', 'Fiat':'Punto', 'Honda':'Jazz'}  
for i in range(len(carMake)):   
    for x in carModel:  
        if(x==carMake[i]):  
            print("%s  %s" %(x, carModel[x]))  

This is image title

Enumerate

Another built-in Python function that takes input as iterator, list etc. and returns a tuple containing index and data at that index in the iterator sequence. For example, enumerate (carMake), returns a iterator that will return (0, carMake[0]), (1, carMake[1]), (2, carMake[2]), and so on.

print("List Iteration")   
carMake = ["Maruti", "Fiat", "Honda"]   
for i, x in enumerate(carMake):  print("%s  %s" %(i, x))  

This is image title

zip

Another in-built python function which is helpful to combine similar types of  iterators (list-list or dictionary- dictionary etc.) data items at ith position. It uses the shortest length of these input iterators. Other items of larger length iterators are skipped.

carMake = ["Maruti", "Fiat", "Honda"]   
carModel = ['Alto', 'Punto', 'Jazz']  
for m,mo in zip(carMake, carModel):   
   print("car %s is a product of %s" %(mo, m))  

This is image title

try statement

The try statement specifies exception handlers and/or cleanup code for a group of statements.

_except _clause or statement is a place that contains code to handle the exception or error raised in try block and multiple except clauses while a single try statement clause can be added into the code. In the below example, print command will raise a ‘TypeError’ because %d is expecting integer value

print("List Iteration")   
carMake = ["Maruti", "Fiat", "Honda"]   
carModel = {'Maruti':'Alto', 'Fiat':'Punto', 'Honda':'Jazz'}  
try:  
    for i in range(len(carMake)):       
        for x in carModel:  
            if(x==carMake[i]):  
                print("%s  %d" %(x, carModel[x]))   
except TypeError:   
    print('oops! Type error -- ', t)  

This is image title

  • You can include try-except statements within other try-except statements
  • finally: clause can be added to clean up the resources or objects
  • finally: block is a place to put any code that must execute, whether the try-block raised an exception or not

Please refer to the example for better understanding or implementation

print("List Iteration")   
carMake = ["Maruti", "Fiat", "Honda"]   
carModel = {'Maruti':'Alto', 'Fiat':'Punto', 'Honda':'Jazz'}  
try:  
    for i in range(len(carMake)):       
        for x in carModel:  
            if(x==carMake[i]):  
                print("%s  %d" %(x, carModel[x]))   
except TypeError as t:   
    print('oops! Type error -- ', t)  
except ValueError:  
    print('oops! incorrect value')  
finally:  
 print('Finally Code Execution - done');  

This is image title

with statement

The with statement is used to wrap the execution of a block with methods defined by a context manager where a context manager is an object that defines the runtime context to be established. In the below example, accessing a file by using the open() function returns a file object that is being used for further execution.

with open("c:\welcome.txt") as file: # Use file to refer to the file object  
    data = file.read()  
    print(data)  

This is image title 

Loop Control Statements

The Loop control statement is meant to be used when you want to change the execution flow from its normal sequence, which means it either terminates the execution in between or transfers control to execute or skip the remaining code block. Python programming language supports the following loop control statements:

break

This statement terminates the loop statement and transfers execution to the statement immediately following the loop. In the below example it terminates the execution as soon as the first even number present in the list is found and printed 

List = [15, 3, 4, 7, 5]  
print('find and print first even number present in the list %s' %List)  
for number in List:  
    if(number % 2 == 0):  
        print('%d is first even number present in the list' %number)  
 break;  

Continue

This statement causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating. In the below example it skips the execution the moment an odd number is found and continues iterating next items to find and print all the even numbers present in the list 

List = [15, 3, 16, 9, 24, 4, 7, 5]  
evenNumbers = []  
print('find and print all even number present in the list %s' %List)  
for number in List:  
    if(number % 2 != 0):          
        continue;  
    else:  
        evenNumbers.append(number)  

print('even numbers %s present in the list ' %evenNumbers)  

This is image title

pass

This statement causes the loop to pass the control to execute any additional code on a specific condition, then proceeds to execute the remainder of its body. In the below example pass is the execution control to double the number when an odd number is found then continue printing the numbers.

List = [15, 3, 16, 9, 24, 4, 7, 5]  
EvenNumbers = []  
print('double the number when odd number is found in the list %s' %List)  
for number in List:  
    x = number  
    if(x % 2 != 0):          
        pass  
        print('odd number %s found- double the number' %x)  
        x=x+x   
    else:  
        print('even number %s found- do nothing' %x)           
    print(x)  

This is image title

Conclusion

We want learned about different compound statements including if condition, loop (while, for) statement, and loop control ( continue, break, pass) statement.

Thank for reading!

python language programming

What's new in Bootstrap 5 and when Bootstrap 5 release date?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Random Password Generator Online

HTML Color Picker online | HEX Color Picker | RGB Color Picker

Guide to Python Programming Language

Guide to Python Programming Language

Best Way to Learn Python Programming Language | Python Tutorial

Worried that you have no experience in handling Python? Don’t! Python programming language teaching from Simpliv puts you right there to be able to write Python programs with ease. Place object-oriented programing in a Python context and use Python to perform complicated text processing.

Python Hello World Program - Create & Run Your First Python Program in PyCharm

Python Hello World Program - Your first step towards Python world. Learn how to create the Hello World Python program in PyCharm.

Python Programming Tutorials For Beginners

Python Programming Tutorials For Beginners

Make Python More like An Object-Oriented Programming Language

Asa programmer who has been using Unity to develop games for a long time, the programming language I use is C#. As you know, C# is a strongly typed language and is usually programmed using an object-oriented paradigm (of course, it has other paradigms). Recently, I started to use Python for programming. It has been 5–6 years since I last used Python, and at that time I used Python 2.7. Therefore, I had the impression that Python is a process-oriented dynamic programming language without types. Programming Practices That Make Python More like An Object-Oriented Programming Language