Python Control Flow
Topic: Control Flow & Decision Making
Teaching Python how to "Think" and choose paths.
Understanding Control Flow
In a simple script, Python reads code line-by-line from top to bottom. However, real programs need to make choices. Control Flow is the order in which individual statements are executed. We use Conditional Statements to tell Python: "Only run this code IF something is true."
The Tools of Logic: Comparison Operators
To make a decision, Python compares two values. The result is always True or False.
Equal to
Not equal to
Greater than
Less than
Greater or Equal
Less or Equal
The If... Elif... Else Structure
Python uses three main keywords to handle decisions:
- if: The first condition to check.
- elif: (short for "else if") Used to check more conditions if the first one was false.
- else: The "fallback" plan if none of the above conditions were met.
score = int(input("Enter student score: "))
if score >= 70:
print("Result: Distinction")
elif score >= 50:
print("Result: Pass")
else:
print("Result: Fail")
In Python, the 4-space gap (or Tab) after an
if statement is not optional. It defines the "scope." If you don't indent, Python won't know which code belongs to the decision!
Practical Problems
Let's look at how this works in real-world software development:
A. Security Login
Verifying if a user is authorized to enter.
if pin == "0550":
print("Welcome, User!")
else:
print("Invalid Pin. Locked.")
B. Smart Discount
Applying a discount based on total purchase.
if bill > 10000:
final = bill * 0.90
print("Discounted Price:", final)
else:
print("Amount Due:", bill)
๐ป Practical Coding Lab
The Challenge: Write an "Odd or Even" checker. Hint: Use the modulo operator (%) which gives the remainder of a division.
2. If the number divided by 2 has a remainder of 0, print "Even".
3. Otherwise, print "Odd".
Click to reveal Solution Code
if num % 2 == 0:
print("This is an Even number.")
else:
print("This is an Odd number.")
Comments
Post a Comment