Conditional Statements
Lecture Contents
• Control Structures
• Sequence Structures
• Decision Structures
• if Statement
• if else Statement
• elif Statement ( Chained Conditionals)
• Nested Conditionals
• Repetition Structures
• Loops
• for loop
• while loop
Conditional Statements and Loops in Python 2
Decision Structures /
Conditional Statements
Conditional Statements and Loops in Python 3
Control Structure
• A control structure controls the order in which a set of statements execute
• Sequence Structure
• All statements are executed in a sequential order
• Sequence structure cannot handle all types of real word scenarios
• Decision Structure / Conditional Statements
• Allow to execute different statements based on a condition
• If condition is True execute statement 1 otherwise execute statement 2
• Examples / Types
• if Statement
• if-else Statement
• elif Statement
• Repetition Structures / Loops
• Execute a block of code specified number of times
• for loop and while loop
Conditional Statements and Loops in Python 4
Decision Structure : Conditional
Statements
• Conditional Statement
• A line of code that includes a Boolean expression
• Evaluates to True or False
• Includes Relational Operators
Conditional Statements and Loops in Python 5
if Statement ( Lab Task 1.1)
• if statement is used to execute a block of code based on a Boolean expression
• Syntax:
• Things to Remember :
• if is in lower case
• There is a colon after the Boolean expression
• Body of if should be indented
• Can contain a single or multiple statements in the body
Conditional Statements and Loops in Python 6
if Statement Example / Flow Chart
Conditional Statements and Loops in Python 7
Problem Solving
Lecture 3: Conditional Statements and Loops in Python 8
if else Statement (Lab Task 1.2)
• Sometimes we need to execute a specified block of code when condition is
true and another block of code when condition is false
Conditional Statements and Loops in Python 9
Problem Solving
Lecture 3: Conditional Statements and Loops in Python 10