Chapter 3: Control Structures Summary
Chapter 3: Control Structures
Objectives
- Understand and apply conditional statements: if, if-else, if-elif-else.
- Develop programs to handle multiple conditions.
- Implement iteration statements: for loops and while loops.
Conditional Statements
- Need for Conditional Statements: Manage program execution based on conditions.
- Check a condition.
- Execute code block if True; skip if False.
IF Statements
- Syntax:
if expression:
statement1 - Executes statements if the condition is true; skips if false.
- Indentation crucial: same indent indicates a block of statements.
IF ELSE Statements
- Syntax:
if expression:
statement1
else:
statement2 - Executes statement1 if true; otherwise, executes statement2.
IF ELIF ELSE Statements
- Syntax:
if expression1:
statement1
elif expression2:
statement2
...
else:
statement n - Allows testing multiple conditions sequentially.
Nested IF ELSE
- If a condition inside another condition must be checked, use nested if.
Iteration Statements
- Need for Iteration: Perform repetitive tasks until a condition changes.
WHILE Statements
- Syntax:
while expression:
statement1 - Executes statements while the condition is True.
FOR Loop Statements
- Syntax:
for variable_name in list_name:
body of loop - Iterates through elements in a given list.
The RANGE() Function
- Generates a sequence of numbers:
range(start, end, step). range(n) produces numbers from 0 to n-1.
BREAK and CONTINUE Statements
- Break: Exits the loop immediately.
- Continue: Skips to the next iteration of the loop.
PASS Statement
- Does nothing; serves as a placeholder.
NESTED Loop
- A loop inside another loop, used for multidimensional arrays like matrices.