GK SOLUTIONS
AI • IoT • Arduino • Projects & Tutorials
DEFEAT THE FEAR
← Back to All Lessons

📦 Lesson 6: Python Functions

⏱️ Estimated time: 30 minutes | Difficulty: Intermediate

Modularity

Functions allow you to define a block of code once and call it multiple times. They make your code cleaner, shorter, and easier to debug.

What is a Loop?

A loop repeats code multiple times. Instead of writing the same line over and over, you use a loop!

Real-World Analogy:

🔄 Imagine washing dishes:
Without a loop: Wash dish. Rinse dish. Wash dish. Rinse dish. Wash dish. Rinse dish.
With a loop: Repeat 10 times: (Wash dish, Rinse dish)

For Loops

Use a for loop to repeat code a specific number of times:

for i in range(5):
    print("Hello!")

Output:

Hello!
Hello!
Hello!
Hello!
Hello!

For Loop with Counter

The counter (i) changes each time through the loop:

for i in range(1, 6):
    print("Number:", i)

Output:

Number: 1
Number: 2
Number: 3
Number: 4
Number: 5

While Loops

Use a while loop to repeat code WHILE a condition is true:

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

Output:

Count: 1
Count: 2
Count: 3

Looping Through Lists

fruits = ["apple", "banana", "orange"]

for fruit in fruits:
    print("I like", fruit)

Output:

I like apple
I like banana
I like orange

Loop Control

break - Exit Loop

for i in range(10):
    if i == 3:
        break
    print(i)
# Output: 0, 1, 2

continue - Skip This

for i in range(5):
    if i == 2:
        continue
    print(i)
# Output: 0, 1, 3, 4

✅ Quick Quiz

❓ How many times will this print "Hi"?
for i in range(3):
print("Hi")

❓ What does "break" do in a loop?

❓ Which loop is best for going through a list?

🎯 Challenge

Write a program that:

  1. Uses a loop to print numbers 1 through 10
  2. But skip number 5 (using continue)
  3. Stop at number 8 (using break)

Expected output: 1, 2, 3, 4, 6, 7

← Previous: If/Else Next: Functions →