You are on page 1of 9

Lesson 3: CONDITIONAL STATEMENTS

1. Boolean Objects, Values, and Expression 2


• Comparison Operators 2
• Identity Operators 3
• Boolean Operators 4
• Mixing Boolean and Comparison Operators 5
2. Conditional Statements 5
• else statements 5
• elif statements 6
3. Conditional Expressions 6
4. Practice Questions 7
5. Sample Programs 8
• Learn Addition 8
• Scissor, Paper, Rock 9

1
Lesson 3: CONDITIONAL STATEMENTS
The term “object” will be used frequently throughout this text. A Python object is essentially anything we
can assign to a variable – numbers, strings of characters, lists, functions, etc. There are different types of
objects: for example, an integer is a different type of object than a string.

3.1. Introduction
The main purpose of any programming is to implement some kind of logic. In this section, conditional
statements such as if, else, and elif will be introduced. If/else blocks are a core syntax element in
Python. They let us conditionally control the flow of the program.

Like all high-level programming languages, Python provides selection statements that let you choose
actions with two or more alternative courses.

For example, the following code prints “Too fast” if the speed exceeds 100km/h, and will print “Below
speed limit. Well done” if speed is 100km/h or below.

Selection statements use conditions, which are Boolean expressions.

3.2. Boolean Types, Values, and Expressions

A Boolean expression is an expression that evaluates to a Boolean value True or False.

Comparison Operators

Also called relational operators, these operators compare two values and evaluate down to a single
Boolean value.

Assume variable a holds 5 and variable b holds 10.


OPERATOR DESCRIPTION EXAMPLE RESULT
== Equal to a == b False
!= Not equal to a != b True
> Greater than a > b False
< Less than a < b True
>= Greater than or equal to a >= b False
<= Less than or equal to a <= b True

2
A variable that holds a Boolean value is known as a Boolean variable. A Boolean variable can hold one of
the two values: True or False. Internally, Python uses 1 to represent True and 0 for False. We can use
the int function to convert a Boolean value to an integer. For example,

We can also use the bool function to convert a numeric value to a Boolean value. The function returns
False if the values is 0; otherwise it always returns True. For example,

The following Python objects evaluate to False via bool:


• False
• None
• Zero of any numeric type
• Any empty sequence
• Empty dictionaries and sets

Non-zero numbers and non-empty sequences evaluate to True via bool.

Identity Operators

Identity operators are used to compare two objects if they are actually the same object, points to the
same memory location.

OPERATOR DESCRIPTION
is Object identity
is not Negated object identity

The is operator checks to see if two objects are actually the same and is commonly used to check if a
variable references the None object, or either of the Boolean objects.

Using IDLE (interactive interpreter), the code below checks if variable x refers to the None object, and
displays the unique id of both x and None:

To demonstrate that x actually refers or points to None, the example above runs the id() function on both
objects, which result to the same integer values, therefore the statement x is None returns True.

3
Use is not to check if two objects are different:

Important rules to keep in mind when checking for None:


• Do use the identity operators is and is not.
• Do not use the equality operators == and !=.

Logical/Boolean Operators
Boolean operators are used to compare Boolean values. The and and or operators always take two
Boolean values (or expression).

OPERATOR DESCRIPTION EXAMPLE RESULT


and Returns True if both statements are (5 > 2) and (5 < 10) True
True
or Returns True if one of the (5 > 10) or (20 > 5) True
statements is True
not Reverses the result not False True

The and operator evaluates an expression to True if both Boolean values are True; otherwise, it evaluates
to False.

Truth Table for the and Operator


EXPRESSION RESULT
True and True True
True and False False
False and True False
False and False False

The or operator evaluate to True if either of the two Boolean values is True. If both are False, it evaluates
to False.

Truth Table for the or Operator


EXPRESSION RESULT
True or True True
True or False True
False or True True
False or False False

The not operator operates on only one Boolean value (or expression). It evaluates to the opposite
Boolean value.

Truth Table for the not Operator


EXPRESSION RESULT
not False True
not True False

4
Mixing Boolean and Comparison Operators

The left expression will be interpreted first, and then it will evaluate the right expression. Once, the value
for each expression is known, it will then evaluate the whole expression down to one Boolean value.

Boolean operators have an order of operations just like the math operators do. After any math and
comparison operators evaluate, Python evaluates the not operator first, then the and operators, and then
the or operators.

3.3. if Statements
An if statements’ clause (that is, the block following the if statement) will execute if and only if the
condition is True. The clause is skipped if the condition is False.

Syntax:

if boolean-expresssion:
statement(s)

In Python, an if statement consists of the following:


• The if keyword
• A condition (an expression that evaluates to True or False)
• A colon
• Starting on the next line, an indented block of code (called the if clause)

The following is an example of a program that prompts the user to enter an exam score. If the score is
greater than 90, allowance will be increased by 3%. Assume allowance already has a value.

else Statements
An if clause can optionally be followed by an else statement. The else clause is executed only when the
if statement’s condition is False. An else statement doesn’t have a condition, and in code, an else
statement always consists of the following:
• The else keyword
• A colon
• Starting on the next line, an indented block of code (called the else clause)

Returning to the exam score example, if exam score is 90 below, then allowance will be increased by 1%.

5
elif Statements
We can create a series of conditionals using if for the first one, elif for the rest, and (optional) else for
anything not caught by other conditionals.

While only one of the if or else clauses will execute, we may have a case where we want one of many
possible clauses to execute. It provides another condition that is checked only if any of the previous
conditions were False . In code, an elif statement always consists of the following:
• The elif keyword
• A condition (an expression that evaluates to True or False)
• A colon
• Starting on the next line, an indented block of code (called the elif clause)

Using the exam score/allowance example, we’ll add some more conditions. If score is greater than 95, the
increase will be 4%, if it is between 91 to 95 (inclusive), increase by 3%, and if it is between 86 to 90
(inclusive) the increase will be 2%, and 81 to 85 will increase by 1%:

3.4. Conditional Expressions (Ternary Operator)


Python supports a syntax for writing a compact if-else statement in a single line replacing the multi-line
if-else. Only if and else statement allowed, no elif.

Syntax:
[expression1] if [conditional_expression ] else [expression2]

The [conditional_expression] is evaluated first. If it returns True, the expression evaluates to


[expression1] , if it returns False, the expression evaluates to [expression2].

Example:

6
PRACTICE QUESTIONS

1. What do the following expressions evaluate to?


a) (5 > 4) and (3 == 5)
b) not (5 > 4)
c) (5 > 4) or (3 == 5)
d) (True and True) and (True and False)
e) (not False) or (not True)
2. Write code that prints Hello if 1 is stored in greeting variable, prints Hi if 2 is stored in greeting
variable, and prints Greetings! If anything else is stored in greeting.
3. Write a Boolean expression that evaluates True if weight is greater than 50 or height is greater
than 160.
4. Rewrite the following statement using a Boolean expression:

EXTRA CREDIT
Look up the random() function on the Internet, and find out what they do. Experiment with them in the
interactive shell.

7
SAMPLE PROGRAMS

P301. Learn Addition


Write a program that generates two random integers under 100 and prompts the user to enter the sum of
these two integers. The program then reports True if the answer is correct, otherwise False.

8
P302. Scissor, Rock, Paper
Write a program that plays the popular scissor-rock-paper game. (A scissor can cut a paper, a rock can
knock a scissor, and a paper can wrap a rock.) The program randomly generates a number 0 , 1 , or 2
representing scissor, paper, and rock. The program prompts the user to enter a number 0 , 1 , or
2 and displays a message indicating whether the user or the computer wins, loses, or draws.

Here’s a sample run:


scissor (0), paper (1), rock (2): 1 [Enter]
The computer is rock, You are paper. You won!

You might also like