Before I start with control flow tools, here are a few definitions:
- Value: Basic units of data. Eg-
- Variable: A name that refers to a value. Eg-
varis 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 statements are used for conditional decision making. Executution starts from
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
while statement is used for iteration. It consists of a condition, which evaluates to either
False. The code inside the
while loop is executed as long as the condition evaluates to
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
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
continue statement is used to skip the current iteration of either a
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.
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
6 is encountered, execution of the
for loop is stopped. Note that in the case of nested
loops, only the execution of the loop that
break is encountered in is stopped, but not the loops at a
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
pass, though it is not a good example of where to use
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
Code for today’s plog is here.