Control Flow and Decision Making in Python
Mastering Python's Control Structures for Effective Programming
Repo (5)
Control Flow and Decision Making
in Python
1. Introduction to Control Flow
Control flow in Python determines the order in which statements are executed. Decision-
making is achieved using if, elif, and else statements, along with comparison and logical
operators.
2. Comparison Operators
Comparison operators are used to compare values and return True or False:
==: Equal to
!=: Not equal to
>: Greater than
<: Less than
>=: Greater than or equal to
<=: Less than or equal to
x = 10
y = 20
print("x == y =", x == y) # False
print("x != y =", x != y) # True
print("x > y =", x > y) # False
print("x < y =", x < y) # True
print("x >= y =", x >= y) # False
print("x <= y =", x <= y) # True
3. Logical Operators
Logical operators combine multiple conditions:
and: True if both conditions are True
or: True if at least one condition is True
not: Reverses the result of a condition
age = 25
is_student = True
if age > 18 and is_student:
print("You are eligible for a student discount.")
4. The if Statement
The if statement executes a block of code if a condition is True.
num = 10
if num > 0:
print("The number is positive.")
5. The else Statement
The else statement executes a block of code if the if condition is False.
num = -5
if num > 0:
print("The number is positive.")
else:
print("The number is not positive.")
6. The elif Statement
The elif statement checks multiple conditions.
num = 0
if num > 0:
print("The number is positive.")
elif num < 0:
print("The number is negative.")
else:
print("The number is zero.")
7. Nested if Statements
if statements can be nested inside each other to check multiple conditions.
num = 10
if num > 0:
if num % 2 == 0:
print("The number is positive and even.")
else:
print("The number is positive and odd.")
else:
print("The number is negative.")
8. Practical Examples
Simple Calculator
operation = input("Enter the operation (+, -, *, /): ")
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
if operation == '+':
result = num1 + num2
elif operation == '-':
result = num1 - num2
elif operation == '*':
result = num1 * num2
elif operation == '/':
if num2 != 0:
result = num1 / num2
else:
result = "Error: Division by zero."
else:
result = "Invalid operation."
print("Result:", result)
Grading System
def grading_system(marks):
if marks >= 90:
grade = "A+"
elif marks >= 80:
grade = "A"
elif marks >= 70:
grade = "B"
elif marks >= 60:
grade = "C"
elif marks >= 50:
grade = "D"
else:
grade = "F"
return grade
marks = float(input("Enter the marks: "))
grade = grading_system(marks)
print(f"The grade for {marks} marks is: {grade}")
Loops and Iteration in Python
1. Introduction to Loops
Loops are used to repeat a block of code multiple times. Python supports two types of loops:
for loops: Iterate over a sequence (list, string, range).
while loops: Repeat a block of code while a condition is True.
2. The for Loop
The for loop iterates over a sequence and executes a block of code for each item.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
3. for Loop with else in Python
The else block runs only if the loop completes without a break statement.
numbers = [1, 2, 3, 4, 5]
for num in numbers:
print(num)
else:
print("Loop completed successfully!")
4. The while Loop
The while loop repeats a block of code as long as the condition is True.
count = 1
while count <= 5:
print(count)
count += 1
5. Controlling Loops with break and continue
break: Exits the loop immediately.
continue: Skips the rest of the code in the current iteration and moves to the next
iteration.
for i in range(10):
if i == 5:
break
print(i)
for i in range(5):
if i == 3:
continue
print(i)
6. Nested Loops
A nested loop places one loop inside another, with the inner loop iterating through its cycle
for each iteration of the outer loop.
# Multiplication table
for i in range(1, 6):
for j in range(1, 6):
print(f"{i} * {j} = {i * j}")
This guide covers fundamental concepts in control flow, decision-making, loops, and iteration
in Python, along with hands-on examples to enhance understanding.
Multiple Choice Questions (MCQs)
MCQs:
1. Which of the following is a correct comparison operator in Python?
a) ==
b) !=
c) >
d) All of the above
2. Which logical operator is used to combine two conditions where both must be true?
a) or
b) not
c) and
d) xor
3. What does the elif statement do in Python?
a) It is used to execute code when a condition is False.
b) It is used to check multiple conditions.
c) It is used to create an infinite loop.
d) It is used to break a loop.
4. Which of the following operators is used for exponentiation in Python?
a) *
b) /
c) %
d) **
5. What will be the output of the following code?
6. num = 10
if num > 5:
print("Greater than 5")
else:
print("Not greater than 5")
a) Greater than 5
b) Not greater than 5
c) Error
d) No output
7. Which of the following is NOT a valid loop in Python?
a) for loop
b) while loop
c) until loop
d) None of the above
8. What does the break statement do in a loop?
a) Skips the current iteration of the loop.
b) Stops the loop completely.
c) Continues the loop without stopping.
d) Restarts the loop.
9. What will be the output of the following code?
10. fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
a) apple banana cherry
b) apple
c) banana
d) None of the above
11. Which loop will execute as long as a condition is true?
a) for loop
b) while loop
c) do-while loop
d) None of the above
12. Which of the following is an example of a nested loop in Python?
a) A loop inside an if statement.
b) A loop inside another loop.
c) An if statement inside a loop.
d) None of the above.
Answers with Detailed Explanations:
1. Answer: d) All of the above
Explanation: All of the options (==, !=, >) are valid comparison operators in Python. The ==
operator checks if two values are equal, != checks if they are not equal, and > checks if
the first value is greater than the second.
2. Answer: c) and
Explanation: The and logical operator is used to combine two conditions where both
conditions must be true for the entire expression to be true. For example, if age > 18 and
is_student: means both conditions must be true for the block of code to execute.
3. Answer: b) It is used to check multiple conditions.
Explanation: The elif (else if) statement is used to check additional conditions if the
previous conditions in the if block were false. It helps to test multiple conditions without
nesting multiple if statements.
4. Answer: d) **
Explanation: The ** operator is used for exponentiation in Python. For example, 2 ** 3 will
return 8, which is 2 raised to the power of 3.
5. Answer: a) Greater than 5
Explanation: Since num = 10 and the condition num > 5 is true, the program will execute
the if block and print "Greater than 5".
6. Answer: c) until loop
Explanation: Python does not have an until loop. The two valid loops in Python are the
for loop and the while loop. The while loop repeats as long as a condition is true, and the
for loop iterates over a sequence.
7. Answer: b) Stops the loop completely.
Explanation: The break statement is used to terminate the loop immediately, even if the
loop’s condition is still true. For example, if i == 5 in a loop, break will exit the loop.
8. Answer: a) apple banana cherry
Explanation: The code iterates over the list fruits and prints each item. Since the list
contains "apple", "banana", and "cherry", the output will be those three printed on
separate lines.
9. Answer: b) while loop
Explanation: The while loop continues to execute as long as the condition specified is
true. It will stop once the condition evaluates to false. A for loop iterates over a
sequence, and a do-while loop doesn’t exist in Python.
10. Answer: b) A loop inside another loop.
Explanation: Nested loops occur when one loop is placed inside another. For example, an
outer loop could iterate over rows, and an inner loop could iterate over columns. This is
often used in problems like printing a multiplication table.
These MCQs and explanations should help clarify the key concepts of control flow, decision
making, and loops in Python! If you'd like to explore more examples or concepts, feel free to
ask.
created by : Hamza Rafqiue