Just like any other programming language, Python programming language includes some keywords that are used to control the flow of our program. You might be familiar with the following keywords. Lets see them one by one and how it is done in Python.
1. Conditional Statements
There are three keywords to control conditional flow: if, elif and else.
Note: Since this is the first code of this course, please not that beginning and ending of any block of statement(s) is identified by tabs or spaces. In the below example the statement print("x equals y") is started with a fixed tab space which indicates that this block is a block of code of "if" statement.
x = 20
y = 23
# compare two numbers
if x == y:
print("x equals y")
elif x < y:
print("x is less than y")
else:
print("x is greater than y")
2. "while" statement
Here is how we can repeat a block of statement(s) using while keyword
i = 1
x = 2
# print the mathematical power of x raise to i
while i <= 10:
print(x, "^", i, " = ", x**i)
i += 1
Note : Python does not support incrementing like i++ or ++i. ** symbol is used to mathematically raise power to some numeric constant or variable.
3. "for" statement
Here is how we can repeat a block of statement(s) using for keyword
arr = [3, 7, 8, 8, 9, 1]
for i in arr:
print(i)
# for with range function
for i in range(1, 10):
print(i)
Range function creates an array starting from the number defined in 1st argument to the 2nd argument and incrementing each step by 1. It takes an optional 3rd parameter "step" which defines how much to increment.
# for with range function with step
for i in range(1, 10, 2):
print(i)
4. "break" and "continue" statement
break: It is used to exit from complete loop.
# find first negative number
arr = [3, 6, 10, 334, -5, 33, 48, -11, 20]
for i in arr:
if i < 0:
print("First n-ve number : ", i)
break
continue: It will not execute the remaining part of the loop (from the point where we have written the continue statement). However, it continues the loop from next iteration.
# print all positive numbers
for i in arr:
if i < 0:
continue
print(i)
Python jupyter notebook for control flow statements
Access Jupyter notebook for this chapter here:
Python Notebook - Control Flow Statements