Before I start with control flow tools, here are a few definitions:

• Value: Basic units of data. Eg- 10,'string'.
• Variable: A name that refers to a value. Eg- var=10, var is the variable.
• Statement: A section of code that represents a command or action.
• Operator: A symbol that performs operations on operands. Eg- * is for multiplication
• Expression A combination of variables, operators, and values to perform a task.

To learn about operators in Python refer here.

Some of the control flow tools are:

• if statement
• while statement
• for statement
• break, continue and pass

if statements are used for conditional decision making. Executution starts from if then elif and finally else statements. The first condition that matches (evaluates to True) is executed and the remaining conditions are skipped. Example:

num=42
if num>0:
print('postive number')
elif num==0:
print('Zero')
else:
print('negative number')
#output
postive number


The while statement is used for iteration. It consists of a condition, which evaluates to either True or False. The code inside the while loop is executed as long as the condition evaluates to True. Example:

print('while example')
counter=10
while counter>0:
print(counter)
counter-=1
print('Blast off')
#output
while example
10
9
8
7
6
5
4
3
2
1
Blast off


A for loop is used to iterate over the items of any sequence such as lists, strings. Examples:

print('for example 1')
values=[11,12,34,46]
for i in values:
print(i)

print('for example 2')
for i in range(6):
print(i)
#output
for example 1
11
12
34
46
for example 2
0
1
2
3
4
5


A continue statement is used to skip the current iteration of either a while or for loop. Example:

print('continue example')
for i in range(10):
if(i%2==0):
continue
print(i)
#output
continue example
1
3
5
7
9


In the above example, even numbers are not printed.

A break statement is used to stop the execution of the loop that it is encountered in. Example:

print('break example')
for i in range(10):
if(i==6):
break
print(i)
#output
break example
0
1
2
3
4
5


When 6 is encountered, execution of the for loop is stopped. Note that in the case of nested for loops, only the execution of the loop that break is encountered in is stopped, but not the loops at a higher level.

The pass statement does not do anything. It is generally used in situations where code is expected to be present, but there is nothing meaningful that can be placed. The following example demonstrates the usage of pass, though it is not a good example of where to use pass.

print('pass example')
for i in range(10):
pass
print(i)
pass
#output
pass example
0
1
2
3
4
5
6
7
8
9


References:

Code for today’s plog is here.