Lecture 5 Control Structures in Python
Lecture 5 Control Structures in Python
INTRODUCTION TO COMPUTER
PROGRAMMING
Lecture 5: Control Structures in Python
Outline
• Boolean Data Type
• Relational / Comparison Operators
• Logical Operators
• Conditional Statements
Boolean Data Types
• In Python, to represent Boolean values, True and False,
we use the bool data type.
• Boolean values are used to evaluate the value of the
expression. For example, when we compare two values,
the expression is evaluated, and Python returns the
Boolean True or False.
• Like any other value, Boolean values are used in
expressions and can be stored in variables. If you don’t
use the proper case or you try to use True and False for
variable names, Python will give you an error message.
Boolean Data Types Cont.
• For Example:
Relational Operators
• Relational operators are also called comparison
operators.
• It performs a comparison between two values. It returns
a Boolean True or False depending upon the result of
the comparison.
Logical Operators
• Logical operators are useful when checking if a condition is
true or false.
• Python has three logical operators. All logical operator
returns a Boolean value True or False depending on the
condition in which it is used.
Operator Description Example
and (Logical True if both the
a and b
and) operands are True
True if either of the
or (Logical or) a or b
operands is True
not (Logical True if the operand is
not a
not) False
Logical Operators Cont.
• For Example:
Conditional Statements
• In Python, condition statements act depending on
whether a given condition is true or false.
• You can execute different blocks of codes depending on
the outcome of a condition. Condition statements
always evaluate to either True or False.
• These are conditional statements:
if statement
if-else
if-elif-else
nested if-else
The if Statement
• An if statement tells Python to only execute a portion of
code if a condition is met.
• It takes a condition and evaluates to either True or.
False
• If the condition is True, then the True block of code will
be executed, and if the condition is False, then the block
of code is skipped, and The controller moves to the next
line.
The if Statement Cont.
• In Python, an if statement consists of the following:
i. The if keyword
ii. A condition (that is, an expression that evaluates to
True or False)
iii. A colon
iv. Starting on the next line, an indented block of code
The if Statement Cont.
• The Syntax of if statement:
• Example:
The if - else statement
• The if-else statement checks the condition and executes
the if block of code when the condition is True, and if
the condition is False, it will execute the else block of
code.
• Syntax of the if-else statement: