Tuesday, October 28, 2025

Control Flow, Functions & Statements – II

 Control Flow, Functions & Statements – II


1. What Is Control Flow?

  • Every Python program runs line by line — but real problems need decisions, repetition, and organization.
  • Control flow gives your code the power to deciderepeat, and reuse logic.

Example (Human Analogy):

“If it’s raining, take an umbrella.

Otherwise, wear sunglasses.”

That’s how computers make choices too!


2. Conditional Statements (if, elif, else)

Conditional statements help your code make decisions based on True or False conditions.

Syntax:

if condition:
    # code runs when condition is True
elif another_condition:
    # runs if first is False and this is True
else:
    # runs when none are True
 

Example:

age = 18
if age >= 18:
    print("You can vote!")
else:
    print("Sorry, not eligible.")
 

 Output:

You can vote!
 

Key Points:

  • Conditions use comparison operators like:
    • == equal to
    • != not equal
    • <><=>=

Real-life analogy:

“If temperature > 30, turn on AC; else, open window.”


3. Combining Multiple Conditions

Sometimes you need to check more than one condition together.

  • and → all conditions must be true
  • or → at least one must be true
  • not → reverses the condition

Example:

temperature = 28
humidity = 70
 
if temperature > 25 and humidity > 60:
    print("It's hot and humid today!")
 

 Output:

It's hot and humid today!
 

4. Loops: Automating Repetition

Loops let you repeat actions without writing the same line again and again.


a) for Loop

Used when you know how many times to repeat.

Example:

for i in range(5):
    print("Iteration:", i)
 

 Output:

Iteration: 0
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
 

b) while Loop

Used when you repeat until a condition changes.

Example:

count = 0
while count < 3:
    print("Count:", count)
    count += 1
 

 Output:

Count: 0
Count: 1
Count: 2
 

⚠️ Be careful:

If your condition never becomes False, the loop will run forever (infinite loop).


5. Controlling Loops: break and continue

  • break → stops the loop immediately
  • continue → skips the current step and continues to next

Example:

for num in range(1, 6):
    if num == 3:
        continue   # skip 3
    if num == 5:
        break      # stop at 5
    print(num)
 

 Output:

1
2
4
 

6. Functions: Reusable Code Blocks

Functions help organize logic into small, reusable pieces.

Syntax:

def function_name(parameters):
    # code
    return value
 

Example:

def greet(name):
    return f"Hello, {name}!"
 
print(greet("Amit"))
 

 Output:

Hello, Amit!
 

Why use functions?

  • Saves time (write once, use many times)
  • Keeps code clean and modular
  • Makes debugging easier

💡 Tip:

Functions can even call other functions!


7. Returning Values and Passing Data

Functions can return results to use elsewhere.

Example:

def add(a, b):
    return a + b
 
result = add(5, 3)
print("Sum:", result)
 

 Output:

Sum: 8
 

8. Organizing Code with Modules

When your code becomes large, split it into multiple files called modules.

Step 1: Create a file helpers.py

def add(a, b):
    return a + b
 

Step 2: Use it in another file

import helpers
print(helpers.add(10, 5))
 

 Output:

15
 

Why use modules?

  • Keeps code organized
  • Allows reuse across projects
  • Python already provides many built-in modules like mathosdatetime

9. Real-Life Analogy: The Restaurant Example 🍽

Concept

Real-life analogy

if/else

Deciding the menu (veg or non-veg)

Loops

Cooking 10 plates of pasta

Functions

Each kitchen station (salad, grill)

Modules

Different kitchens working together

Control flow makes your program work like a well-run restaurant — efficient, logical, and reusable.


10. Common Mistakes to Avoid

Forgetting colons (:) after ifelif, or for lines

Wrong indentation — Python is strict about spacing

Writing infinite loops accidentally

Using = instead of == for comparison

Always test and read your conditions carefully!


11. Putting It All Together

Example Program:

def check_grade(score):
    if score >= 90:
        return "Excellent"
    elif score >= 75:
        return "Good"
    elif score >= 50:
        return "Average"
    else:
        return "Needs Improvement"
 
scores = [95, 82, 47, 60]
 
for s in scores:
    print(f"Score: {s}, Grade: {check_grade(s)}")
 

 Output:

Score: 95, Grade: Excellent
Score: 82, Grade: Good
Score: 47, Grade: Needs Improvement
Score: 60, Grade: Average
 

12. Mini Challenge – FizzBuzz

Task:

Write a program that takes a number and:

  • Prints “Fizz” if divisible by 3
  • Prints “Buzz” if divisible by 5
  • Prints “FizzBuzz” if divisible by both
  • Otherwise prints the number

Hint:

Use % (modulus) operator and if-elif-else.


13. Key Takeaways

Concept

Meaning

Control Flow

The logic that guides program execution

If/Else

Helps programs make decisions

Loops

Automates repetition

Functions

Makes code reusable and clean

Modules

Keeps big programs organized


14. Next Steps

🎯 Practice simple scripts like:

  • Checking even or odd numbers
  • Printing multiplication tables
  • Creating your own module with a few helper functions

💡 Modify examples to include:

  • break and continue
  • Nested conditions
  • Return values in functions

 

Lecture Notes: Optimising Numerical Code

Lecture Notes: Optimising Numerical Code Prerequisites: Basic Python programming Understanding of NumPy arrays and vector ...