Course Content
Control Flow

In this lesson we'll look at constructs for control flow in Python, including conditional expressions, if statement, while loop and for loop.

Conditional Expressions

Conditionals expressions are expressions with boolean operators check certain condition and they evaluates to True of False.

The usual comparision operators >, >=, <, <=, == and != can be used to compare numbers.

price = 70

print(price > 50)
print(price < 50)

We can use the in and not in operators to check a substring is present in a string.

message = 'hello'
print('el' in message)
print('hell' in message)
print('hell' not in message)

The in and not in operators can also be used to check an element is present in a collection like a list or a dictionary.

value = 'a' in ['a', 'e', 'i', 'o', 'u']

value = 3 in [1, 2, 3, 4]

value = 'x' in {'x': 1, 'y': 2}

We can also use the methods startswith and endswith on strings.

filename = ''

filename = 'hello.c'

Combining Conditional Expressions

The not operator can be used to negate a boolean expression.

filename = ''
print(not filename.endswith('.py'))

Multiple conditional expressions can be combined using the and and or operators.

filename = 'hello.txt'
value = '..' not in filename and filename.endswith('.txt')

Note that and and or are short-circuit operators.

In a and b, b is evaluted only if a is True. In a or b, b is evaluted only if a is False.

filename = 'hello.txt'

# the second expressions doom() is not executed
# because the first expression of and is False
value = filename.endswith('.py') and doom()

# the second expression doom() is not executed
# because the first expression of or is True
value = filename.endswith('.txt') or doom()

In the above example, the function doom, which is not defined at all is not called becuase the reasons mentioned in the comments.

The if Statement

The if statement is used to make decisions in code.

n = 33

if n % 2 == 0:

The above example prints whether the number n is even or odd.

Please note that the block of code that is part of if clause or else clause is indented.

We can use elif clause when we need to check multiple condition.

n = 56

if n < 10:
    print(n, 'is a single-digit number')
elif n < 100:
    print(n, 'is a two-digit number')
    print(n, 'is a big number')

The while statement

The while statement is used to execute a loop.

n = 1
while n <= 10:
    print(n, n*n)
    n = n + 1

Just like if, the body of while is indented.

The for statement

The for statement is used to iterate over a list of values.

numbers = ['one', 'two', 'three', 'four', 'five']
for n in numbers:

We'll learn more about for loops in the upcoming lessons.

Have a doubt?
Post it here, our mentors will help you out.