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:
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")
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")
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')
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')
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 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)
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.
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])
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]))
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))
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))
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)
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');
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)
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:
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;
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 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)
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