MOBI BOOT CAMP CORP. logoLearning Buddy
  • SIGN IN
  • Introduction
  • Setup
  • 1A: Fundamental Building Blocks
  • 1B: Compound Statements
    • If - Conditional block
    • Quiz
    • Colab Exercise
  • 2: Ordered Collection
  • 3: Unordered Collection
  • 4: More Data types
  • 5: Iteration Constructs
  • 6: Other constructs
  • 7. Regex
  • 8. Date and Time
  • Revision
  • Practice Exercise
  • Titanic Workshop

Control Statements

Control Statements provide mechanisms to control the execution of a program based on certain conditions and thereby deviate from the sequential order. Python provides a conditional if statement and loop structures - while and for - as part of Control Statements.

Control Statements become part of a compound statement and should all be executed together based on the control statement's conditional result.

Compound Statement

As we already learned, a compound statement contains groups of statements that work together as a block. They typically span multiple lines and use indentation to mark the group. While you can occasionally write a simple compound statement on a single line, indentation is mandatory for defining multi-line blocks in Python. Python is strict about the consistency of your spaces relative to the preceding statement; failing to do so will result in an IndentationError.

Although there are many varieties of Compound Statements, in this chapter, you will learn about one such statement: the 'if', 'elif', and 'else'.

Conditional if statement

A very common conditional that is used in almost all programming languages is an if statement.

Before you proceed further on if, let us understand the relational and logical operators available, which are used in if and while statements.

The following are the relational operators in Python, which all evaluate to True or False based on the expression. The two operands, 9 and 8, shown below, can be replaced by any expression consisting of one or more variables.

Operator name Notation Examples Result
Greater than > 9 > 8
'b' > 'a'
True
Less than < 9 < 8
'ba' < 'ab'
False
Greater than or equal to >= 9 >= 8
'ab' >= 'aa'
True
Less than or equal to <= 9 <= 8
'ab' <= 'ba'
False
Equal to == 9 == 8
'aa' == 'ba'
False
Not equal to != 9 != 8
'ba' != 'ab'
True

For strings, it uses lexicographical ordering in evaluating the expressions as long as both operands are strings; otherwise, you get an error when you compare a string with a numerical value. Refer to: http://docs.python.org/reference/expressions.html

The following are the logical operators in Python:

Operator name Notation Example Result Comment
logical AND and
9 > 8 and 5 > 4
True Returns True only if both expressions are True. This operator evaluates the second expression only if the first expression evaluates to True.
logical OR or
8 > 9 or 5 > 4
True Returns True if at least one expression is True. This operator evaluates the second expression only if the first expression evaluates to False.
logical NOT not
not 9 > 8
False Reverses the Boolean value (inverts the result).

Operator Precedence

Here is the table showing the precedence order of all the operators in Python, including the Arithmetic operators. The highest precedence is on the top, and the lowest is at the bottom.

Operator Order of Evaluation Description
not R -> L Unary operators
*, /, % L -> R Multiplication, division, modulo
+, — L -> R Addition, subtraction
<, <=, >, >= L -> R Relational operators
==, != L -> R Relational equality/identity operators
and, or L -> R Logical operators
=, +=, -= R -> L Assignment operators

To change the above order of precedence, you can place parentheses '()' around the expressions that should be evaluated first. In this case, the innermost set of parentheses is evaluated first. This mostly works as intended, except when the parentheses are used with the logical operators 'and' and 'or'. For example, the below expression does not evaluate the parentheses first, as the expression to the left of the logical operator is evaluated first.

9>10 and (a>b)

Short-Circuit Concept

Logical operators and and or use short-circuit evaluation. This means Python stops evaluating an expression as soon as the final result is known:

  • The and rule: Python stops at the first False. If the expression on the left is False, the entire condition must be False, so the right side is never evaluated.
  • The or rule: Python stops at the first True. If the expression on the left is True, the entire condition must be True, so the right side is never evaluated.

If Conditional Flowchart

The following flowchart depicts the control flow of the program based on the result of the boolean expression:

x % 2 == 0

If 'x' is an even number, then x % 2 == 0 returns True, in which case the program enters the block of code that prints out 'You input an even number' and then 'Good bye'. If the conditional evaluates to False, then the program skips the block of code that prints 'You input an even number' and outputs only 'Good bye'. So the program, instead of going in a sequential order, takes a deviation based on a conditional expression.

if block flow chart

The if Statement:

if (conditional expression which evaluates to True, False or any other literal value):

A conditional expression is made up of one or more logical and relational expressions, including combinations of both types, which, on the whole, evaluates to True or False.

Note on Truthiness: A conditional expression doesn't have to be a strict Boolean (True or False). Python evaluates 0, None, empty strings "", and empty lists [] as False. Almost all other values (like 1 or "hello") are evaluated as True.

A colon ':' should follow immediately after the conditional expression. If the conditional expression evaluates to True, then the execution flow starts from the indented statements after the :. If the conditional evaluates to False, then the execution flow skips the indented block after : and executes the statements after the if block.

The code for the above flowchart

x = int(input())
if x % 2 == 0:
    print("You input an even number")
print("statement after the if block")

The if...else Statement:

An if statement can be followed by an optional else statement, which executes when the boolean expression is false.

The syntax of an if...else is:

if (boolean_expression) :
  //Executes when the Boolean expression is true
else :
  //Executes when the Boolean expression is false

Run the above code and input an even and odd number and study how the if or else block gets executed based on the boolean expression evaluation. The same execution can be visualized with the flowchart below.

if else flow chart

else is optional in an if statement.

The if...elif...else Statement:

An if-else statement can be followed by optional elif...else statements. When using if, elif, and else statements, there are a few points to keep in mind.

  • An if can have zero or one else, and it must come after any ifs.
  • An if can have zero to many elifs, and they must come before the final else.
  • Once an elif succeeds, none of the remaining elifs or the final else's will be tested.

Now, let us take a grading calculation as an example below to use the if-elif-else operators:

score = float(input("Please enter your score: "))
if score > 90:
    print("Congratulations! You scored an 'A' grade")
elif score > 80:
    print("Congratulations! You scored a 'B' grade")
elif score > 70:
    print("Congratulations, you scored a 'C' grade")
else:
    print("Sorry, you failed.")

In the above program, you first get the input from the user, and then evaluate the first conditional, if (score > 90), which is of the form:

if (conditional expression which evaluates to True or False):

If the conditional expression evaluates to True, then the execution flow starts from the indented statements after the :. If the conditional evaluates to False, then the execution flow skips the indented block after : and proceeds to the elif statement and checks for the conditional again. The same logic is applied to all other conditionals all the way to the else statement. The last else statement is executed if all conditional expressions above evaluated to False.

Order of Evaluation

In the if-elif-else block above, why is it critical that score > 90 is checked first? What would happen if you checked score > 70 first?

(Hint: Think about how the program skips remaining conditions once it finds a True match).

Shorthand If Notation

If you have only one statement to execute, you can put it on one line.

a = 3
b = 2
if b > a:
    print("b is greater than a")

Shorthand If-Else

Similarly, if you have only one statement to execute, one for if, and one for else, you can put it all on one line.

a = 3
b = 2
print(a) if b > a else print(b)

Note that there are no colons used in these notations, and this only works when the conditional has to execute just one line of code based on the conditional.

Shorthand Multiple if-else

a = 3
b = 3
print(a) if a > b else print("equals") if a == b else print(b)

Math Module

As you saw in the first chapter, we can use the math module for advanced mathematical calculations. To use it, we must first import it. Here is an example of how to find the square root of a number using the math module:

# import the math module
import math

math.sqrt(4)

Note: A module is nothing but a software program that is packaged and distributed so that others can use it. You will learn more on modules in Chapter 6.

While the math module provides methods to work on floating-point numbers, you can use the cmath module to work with imaginary (complex) numbers. So, if you try to find the square root of -1 using the math module, it raises an error, but if you use cmath instead, then you will get 1j as the result.

pass statement

Sometimes you do not have the complete implementation for a compound statement, in which case you can use a pass statement, which is just a placeholder so that your code compiles but does nothing in that compound statement.

For example:

if True:
    pass

Remember, however, the execution flow continues after the pass statement is executed if there are more statements after it. This is not like a return statement. pass just results in no operation (NOP). Here the below statement does print 'hi'

if True:
    pass
    print("hi")

We typically use pass when the implementation of a block of code whether in a function, conditionals, loops etc., (topics covered in later chapters) is deferred to a later date.


Hands-on Exercises

Exercise 1: Cinema Ticket Pricing

Write a program that determines the price of a cinema ticket based on a customer's age.

  1. Define a variable age = 15.
  2. Apply the following conditional rules:
    • If age is under 5, the ticket is free (0 dollars).
    • If age is between 5 and 17 (inclusive), the ticket costs 10 dollars.
    • If age is 18 or older, the ticket costs 15 dollars.
  3. Print the final ticket price.
# Write your code below and click Run Code
Click to view Answer
age = 15

if age < 5:
    price = 0
elif age <= 17:
    price = 10
else:
    price = 15

print("Ticket price is:", price, "dollars")
# Output: Ticket price is: 10 dollars

Exercise 2: Leap Year Checker

Write a program to determine if a given year is a leap year. A year is a leap year if:

  • It is divisible by 4.
  • But if it is divisible by 100, it is not a leap year, unless it is also divisible by 400.
  1. Store a year in a variable, e.g., year = 2024.
  2. Write nested or compound if-else blocks to check these conditions. (Hint: Use the modulo operator % to check divisibility, e.g., year % 4 == 0).
  3. Print whether the year is a Leap Year or a Common Year.
# Write your code below and click Run Code
Click to view Answer
year = 2024

if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
    print(year, "is a Leap Year")
else:
    print(year, "is a Common Year")
# Output: 2024 is a Leap Year
Privacy Policy | Terms & Conditions