1.3 Decision Making & Loops
Decision Making & Loops in Python
Programs become useful when they can make decisions and repeat operations automatically. Python provides conditional statements for decision making and loops for repetition.
These concepts are fundamental to Data Science and Automation. They are used to filter records, validate data, process files, repeat calculations, and control program execution.
ifstatementsif-elsestatementsif-elif-elsestatements- Nested conditions
- Comparison and logical operators
forloopswhileloopsrange()- Nested loops
break,continue, andpass- Practical Data Science and Automation examples
1. What Is Decision Making?
Decision making allows a program to execute different instructions depending on whether a condition is True or False.
For example, a program may need to determine whether a student has passed, whether a value is positive, or whether a file exists.
Real-World Logic
If marks are 40 or more:
Student passes
Otherwise:
Student fails
Python expresses this logic using conditional statements.
2. The if Statement
The if statement executes a block of code only when
its condition evaluates to True.
Syntax
if condition:
statement
Example
age = 20
if age >= 18:
print("Eligible")
Since age >= 18 is true, the message is displayed.
The colon : after the condition and the
indentation of the code block are essential.
3. The if-else Statement
Use if-else when there are two possible execution
paths.
Syntax
if condition:
statement_if_true
else:
statement_if_false
Example
marks = 72
if marks >= 40:
print("Pass")
else:
print("Fail")
Exactly one of the two blocks is executed.
4. The if-elif-else Statement
When more than two conditions need to be checked, Python provides
elif, which means else if.
Example: Grade Classification
marks = 86
if marks >= 90:
grade = "A+"
elif marks >= 80:
grade = "A"
elif marks >= 70:
grade = "B"
elif marks >= 60:
grade = "C"
else:
grade = "D"
print(grade)
Python evaluates the conditions from top to bottom. Once a
condition is true, its block executes and the remaining
elif and else blocks are skipped.
5. Multiple Conditions
A conditional structure can contain multiple
elif branches.
temperature = 32
if temperature < 0:
print("Freezing")
elif temperature < 15:
print("Cold")
elif temperature < 30:
print("Moderate")
else:
print("Hot")
Arrange overlapping conditions carefully. Python evaluates
an if-elif-else chain from top to bottom.
6. Comparison Operators
Conditions commonly use comparison operators. A comparison
produces a Boolean result: True or False.
| Operator | Meaning | Example |
|---|---|---|
== |
Equal to | 10 == 10 |
!= |
Not equal to | 10 != 5 |
> |
Greater than | 10 > 5 |
< |
Less than | 5 < 10 |
>= |
Greater than or equal to | 10 >= 10 |
<= |
Less than or equal to | 5 <= 10 |
Example
score = 75
print(score >= 40)
print(score == 100)
7. Logical Operators
Logical operators combine multiple conditions.
| Operator | Meaning |
|---|---|
and |
True when both conditions are true. |
or |
True when at least one condition is true. |
not |
Reverses the Boolean result. |
Using and
age = 25
has_id = True
if age >= 18 and has_id:
print("Access allowed")
Using or
day = "Saturday"
if day == "Saturday" or day == "Sunday":
print("Weekend")
Using not
logged_in = False
if not logged_in:
print("Please log in")
8. Nested if Statements
An if statement inside another if statement is called a nested conditional.
age = 22
has_id = True
if age >= 18:
if has_id:
print("Entry allowed")
else:
print("ID required")
else:
print("Entry not allowed")
Nested conditions are useful when a second decision depends on the result of a previous decision.
Excessive nesting can make code difficult to read. Where possible, simplify complex conditions or move logic into functions.
9. Conditional Expression
Python provides a compact one-line conditional expression for simple choices.
age = 20
status = "Adult" if age >= 18 else "Minor"
print(status)
This is sometimes called a ternary conditional expression.
Conditional expressions are useful for short, simple decisions. Avoid using them for complicated logic.
10. Truthy and Falsy Values
Python evaluates objects in Boolean contexts such as
if conditions.
Some values are considered falsy, including
False, None, numeric zero, and empty
containers or strings.
name = ""
if name:
print("Name entered")
else:
print("Name is empty")
Since the empty string is falsy, the else block runs.
11. What Are Loops?
A loop repeatedly executes a block of code.
Loops are useful when the same operation must be performed for multiple values, records, files, or iterations.
Without a Loop
print(1)
print(2)
print(3)
print(4)
print(5)
With a Loop
for number in range(1, 6):
print(number)
The second approach is shorter, scalable, and easier to maintain.
12. The for Loop
A for loop iterates over the items of an iterable,
such as a string, list, tuple, set, dictionary, or range.
Syntax
for variable in iterable:
statement
Example
for number in [10, 20, 30]:
print(number)
Output:
10
20
30
13. Using range()
The range() function generates a sequence of integers
commonly used with for loops.
range(stop)
for number in range(5):
print(number)
Output:
0
1
2
3
4
The stop value is not included.
range(start, stop)
for number in range(1, 6):
print(number)
Output:
1
2
3
4
5
range(start, stop, step)
for number in range(2, 11, 2):
print(number)
Output:
2
4
6
8
10
14. Counting Backwards with range()
A negative step can be used to generate a decreasing sequence.
for number in range(5, 0, -1):
print(number)
Output:
5
4
3
2
1
15. Iterating Through a String
Strings are iterable, so a for loop can process one
character at a time.
word = "Python"
for character in word:
print(character)
Output:
P
y
t
h
o
n
16. Iterating Through a List
scores = [78, 91, 84, 67]
for score in scores:
print(score)
This pattern is extremely common when processing datasets.
Data Science Example
sales = [1200, 1500, 1750, 900]
total = 0
for amount in sales:
total += amount
print(f"Total sales: {total}")
Output:
Total sales: 5350
17. The while Loop
A while loop repeatedly executes a block as long as
its condition remains true.
Syntax
while condition:
statement
Example
count = 1
while count <= 5:
print(count)
count += 1
Output:
1
2
3
4
5
18. for Loop vs while Loop
| Feature | for Loop | while Loop |
|---|---|---|
| Typical use | Iterating over a known iterable. | Repeating while a condition remains true. |
| Common example | Processing records in a list. | Repeating until a condition changes. |
| Number of iterations | Often determined by the iterable. | Depends on the condition. |
| Risk of infinite loop | Lower in ordinary iteration. | Higher if the condition never becomes false. |
19. Infinite while Loops
A while loop can continue forever if its condition
never becomes false.
For example, this code creates an infinite loop:
count = 1
while count <= 5:
print(count)
The value of count never changes, so the condition
remains true.
Correct Version
count = 1
while count <= 5:
print(count)
count += 1
Always ensure that a while loop has a valid path
toward termination unless an intentional infinite loop is
required.
20. The break Statement
break immediately terminates the nearest enclosing
loop.
for number in range(1, 11):
if number == 6:
break
print(number)
Output:
1
2
3
4
5
Practical Example
values = [10, 25, 30, -1, 45, 50]
for value in values:
if value == -1:
break
print(value)
The loop stops when the sentinel value -1 is found.
21. The continue Statement
continue skips the remaining statements in the
current iteration and proceeds to the next iteration.
for number in range(1, 6):
if number == 3:
continue
print(number)
Output:
1
2
4
5
Data Cleaning Example
values = [10, None, 25, None, 40]
for value in values:
if value is None:
continue
print(value)
Missing values are skipped in this simple example.
22. The pass Statement
pass performs no operation. It acts as a placeholder
where Python syntax requires a statement.
for number in range(5):
if number == 3:
pass
print(number)
Unlike continue, pass does not skip the
rest of the loop iteration.
| Statement | Effect |
|---|---|
break |
Terminates the loop. |
continue |
Skips the current iteration. |
pass |
Does nothing; acts as a placeholder. |
23. Nested Loops
A loop placed inside another loop is called a nested loop.
for row in range(1, 4):
for column in range(1, 4):
print(row, column)
The inner loop runs completely for every iteration of the outer loop.
Multiplication Table Example
for number in range(1, 6):
for multiplier in range(1, 6):
print(number * multiplier, end=" ")
print()
Nested loops are useful for matrix processing, tabular data, combinations, and many algorithmic tasks.
24. else with Loops
Python allows an else block to be associated with a
loop. The loop's else block executes when the loop
finishes normally rather than through break.
Example
for number in range(1, 4):
print(number)
else:
print("Loop completed")
Output:
1
2
3
Loop completed
When break Is Used
for number in range(1, 6):
if number == 3:
break
print(number)
else:
print("Loop completed")
Here, the loop's else block does not execute because
the loop terminated using break.
A loop else is executed when the loop terminates
normally, not when it is terminated by break.
25. Getting Index and Value with enumerate()
The built-in enumerate() function is useful when a
loop needs both the position and the value of each item.
subjects = ["Python", "Statistics", "Data Science"]
for index, subject in enumerate(subjects):
print(index, subject)
Output:
0 Python
1 Statistics
2 Data Science
Start Index from 1
for number, subject in enumerate(subjects, start=1):
print(number, subject)
26. Iterating Over Multiple Sequences with zip()
zip() allows corresponding items from multiple
iterables to be processed together.
names = ["Alex", "Jordan", "Taylor"]
scores = [85, 92, 78]
for name, score in zip(names, scores):
print(f"{name}: {score}")
Output:
Alex: 85
Jordan: 92
Taylor: 78
This pattern is particularly useful when processing related sequences.
27. Loop Control Summary
| Feature | Purpose | Typical Use |
|---|---|---|
break |
Stop the loop. | Stop searching after finding a match. |
continue |
Skip the current iteration. | Ignore invalid or unwanted records. |
pass |
Do nothing. | Temporary placeholder. |
enumerate() |
Provide index and value. | Processing numbered records. |
zip() |
Iterate over multiple iterables together. | Processing related sequences. |
28. Data Science Example — Classifying Scores
Conditions and loops can be combined to classify a collection of scores.
scores = [92, 76, 48, 35, 81, 67]
for score in scores:
if score >= 90:
grade = "A+"
elif score >= 80:
grade = "A"
elif score >= 60:
grade = "B"
elif score >= 40:
grade = "C"
else:
grade = "F"
print(f"{score}: {grade}")
This demonstrates how iteration and conditional logic can work together to process multiple records.
29. Data Filtering with Conditions
A common Data Science operation is selecting values that satisfy a condition.
sales = [1200, 800, 2500, 950, 3100]
for amount in sales:
if amount >= 2000:
print(amount)
Only sales values meeting the threshold are displayed.
The same logical idea is later implemented more efficiently with tools such as pandas and NumPy when working with large datasets.
30. Automation Example — Processing Files
Loops are frequently used in automation to process multiple items.
files = [
"report.csv",
"sales.csv",
"students.csv"
]
for filename in files:
print(f"Processing {filename}")
Later, this pattern can be combined with Python's
pathlib, os, and other libraries to
perform actual file operations.
31. Searching with a Loop
A loop can search through values and stop when the desired item is found.
names = ["Alex", "Jordan", "Taylor", "Morgan"]
target = "Taylor"
for name in names:
if name == target:
print("Found:", name)
break
The break statement prevents unnecessary iterations
after the target is found.
32. Practical Program — Number Analyzer
The following program accepts several numbers and determines whether each number is positive, negative, or zero.
numbers = [12, -5, 0, 27, -9, 18]
for number in numbers:
if number > 0:
print(f"{number}: Positive")
elif number < 0:
print(f"{number}: Negative")
else:
print(f"{number}: Zero")
This combines:
- Lists
- for loops
- if-elif-else
- Comparison operators
- f-string formatting
33. Common Mistakes in Conditions and Loops
| Mistake | Problem | Correct Approach |
|---|---|---|
Using = instead of == |
Assignment is not equality comparison. |
Use == when comparing values.
|
| Missing colon | Conditional or loop block is incomplete. |
Add : after the condition.
|
| Wrong indentation | Code block structure becomes invalid. | Use consistent indentation. |
| Infinite while loop | Loop condition never becomes false. | Update the loop-control variable. |
| Incorrect range boundary | Stop value is unexpectedly included. |
Remember that the stop value of
range() is excluded.
|
| Unnecessary nesting | Code becomes difficult to understand. | Simplify conditions or use functions. |
34. Python Interview Questions
Q1. What is the difference between if and
elif?
View Answer
if starts a conditional chain, while
elif provides additional conditions that are
checked when previous conditions in the chain were false.
Q2. What is the difference between a for loop and a while loop?
View Answer
A for loop is commonly used to iterate over an
iterable, whereas a while loop continues as
long as its condition remains true.
Q3. What does break do?
View Answer
It immediately terminates the nearest enclosing loop.
Q4. What is the difference between
break and continue?
View Answer
break terminates the entire loop, while
continue skips the current iteration and
proceeds to the next iteration.
Q5. What does range(5) generate?
View Answer
It represents the sequence of integers from
0 through 4. The stop value
5 is excluded.
Q6. What is a nested loop?
View Answer
A nested loop is a loop placed inside another loop. The inner loop executes for each iteration of the outer loop.
35. Examination Questions
Multiple Choice Questions
Q1. Which statement is used to test a condition in Python?
checkifwhencondition
Answer: B — if
Q2. What is the output of the following?
for i in range(3):
print(i)
- 1 2 3
- 0 1 2
- 0 1 2 3
- 3 2 1
Answer: B — 0, 1, 2
Q3. Which statement immediately terminates a loop?
stopcontinuebreakexitloop
Answer: C — break
Q4. Which statement skips the current iteration?
breakcontinuepassskip
Answer: B — continue
Short Answer Questions
-
Explain the purpose of the
if-elif-elsestructure. -
Differentiate between
forandwhileloops. -
Explain
break,continue, andpass. -
Explain the three forms of
range()with examples. - What is a nested loop? Give one practical application.
36. Practical Challenge
Build a Student Performance Analyzer
Write a Python program that processes a list of student scores.
- Store at least 10 scores in a list.
-
Use a
forloop to process the scores. - Classify each score as Excellent, Good, Pass, or Fail.
- Count how many students failed.
-
Skip invalid scores using
continue. - Stop processing if a special sentinel value is encountered.
- Display a final summary.
37. Decision Making & Loops Quick Reference
| Concept | Syntax / Example |
|---|---|
| if |
if age >= 18:
|
| if-else |
if condition: ... else: ...
|
| if-elif-else |
if ... elif ... else ...
|
| for loop |
for item in items:
|
| while loop |
while condition:
|
| range() |
range(start, stop, step)
|
| break |
break
|
| continue |
continue
|
| pass |
pass
|
| enumerate |
for i, value in enumerate(items):
|
| zip |
for a, b in zip(list1, list2):
|
38. Key Takeaways
-
ifis used for conditional decision making. -
elifallows additional conditions to be checked. -
elsehandles the remaining case. - Comparison operators produce Boolean results.
-
and,or, andnotcombine or modify logical conditions. -
A
forloop iterates over an iterable. -
A
whileloop runs while a condition remains true. -
range()is frequently used for controlled numeric iteration. -
breakterminates a loop. -
continueskips the current iteration. -
passacts as a placeholder and performs no operation. - Nested loops are useful for multidimensional and repeated processing tasks.
- Conditions and loops form the foundation for later Data Science and Automation workflows.
Use conditions to decide and loops to repeat. Once you master these two ideas, you can build programs that respond intelligently to data and automate repetitive tasks.