Python Control Flow
Python Control Flow
else Statement
execute a block of code only when a specific condition is met. For example,
Python if Statement
An if statement executes a block of code only when the specified condition is met.
Syntax
if condition:
# body of if statement
execution.
Working of if Statement
if number > 0:
print('Positive number')
else:
print('Not a positive number')
if condition1:
# code block 1
elif condition2:
# code block 2
else:
# code block 3
if number > 0:
print('Positive number')
else:
print('Zero')
# outer if statement
if number >= 0:
# inner if statement
if number == 0:
print('Number is 0')
print(result)
Run Code
can be written as
grade = 40
print(result)
If needed, we can use logical operators such as and and or to create complex
conditions to work with an if statement.
age = 35
salary = 6000
The for loop iterates over the elements of sequence in order. In each iteration, the
body of the loop is executed.
The loop ends after the last item in the sequence is reached.
Indentation in Loop
In Python, we use indentation to define a block of code, such as the body of a loop. For
example,
languages = ['Swift', 'Python', 'Go']
# Start of loop
for lang in languages:
print(lang)
print('-----')
# End of for loop
print('Last statement')
Run Code
values = range(4)
1st 0 Prints 0 No
2nd 1 Prints 1 No
3rd 2 Prints 2 No
Yes
4th 3 Prints 3
The loop terminates.
Tip: We can end a for loop before iterating through all the items by using a break
statement.
A for loop can have an optional else clause. This else clause executes after the
iteration completes.
digits = [0, 1, 5]
for i in digits:
print(i)
else:
print("No items left.")
We can also use for loop to repeat an action a certain number of times. For example,
languages = ['Swift', 'Python', 'Go']
Hi
Hi
Hi
Here, we used the list languages to run the loop three times. However, we didn't use
any of the elements of the list.
In such cases, it is clearer to use the _ (underscore) as the loop variable.
The _ indicates that a loop variable is a placeholder and its value is intentionally being
ignored.
For example,
languages = ['Swift', 'Python', 'Go']
# using _ for placeholder variable
for _ in languages:
print('Hi')
Run Code
Here, the loop still runs three times because there are three elements in
the languages list. Using _ indicates that the loop is there for repetition and not for
accessing the elements.
A for loop can also have another for loop inside it. For each cycle of the outer loop,
the inner loop completes its entire sequence of iterations. For example,
# outer loop
for i in range(2):
# inner loop
for j in range(2):
print(f"i = {i}, j = {j}")
while condition:
# body of while loop
Here,
1. The while loop evaluates condition, which is a boolean expression.
2. If the condition is True, body of while loop is executed. The condition is evaluated again.
3. This process continues until the condition is False.
4. Once the condition evaluates to False, the loop terminates.
Tip: We should update the variables used in condition inside the loop so that it eventually
evaluates to False. Otherwise, the loop keeps running, creating an infinite loop.
Flowchart of Python while Loop
print('The end.')
print(f'Hi {user_input}')
in Python, a while loop can have an optional else clause - that is executed once the
loop condition is False. For example,
counter = 0
break
Note: The break statement is usually used inside decision-making statements such as if...else.
Example: break Statement with for Loop
We can use the break statement with the for loop to terminate the loop when a certain
condition is met. For example,
for i in range(5):
if i == 3:
break
print(i)
continue
range() Syntax
Example 1: range(stop)
# create a sequence from 0 to 3 (4 is not included)
numbers = range(4)
pass
print('Hello')
Run Code
Here, notice that we have used the pass statement inside the if statement .
However, nothing happens when the pass is executed. It results in no operation (NOP).
Suppose we didn't use pass or just put a comment as:
n = 10
if n > 10:
# write code later
print('Hello')
Here, we will get an error message: IndentationError: expected an indented
block
Note: The difference between a comment and a pass statement in Python is that while
the interpreter ignores a comment entirely, pass is not ignored.
def function(args):
pass
class Example:
pass