Python Tutorial for Beginners #5: Repeating Tasks made easy with Loops in Python

Raj PatelRaj Patel
12 min read

Imagine you’ve been asked to print(“Hey, IronWill!“) 5 times, then you may do it something like this:

print("Hey, IronWill")
print("Hey, IronWill")
print("Hey, IronWill")
print("Hey, IronWill")
print("Hey, IronWill")

But what if I tell you got to do it 1000 times. Will you go on writing this printing line 1000 times? What if I suddenly wish to print 100000 times. Then? Of course you can do that printing line 10000 times but won’t it be tedious task. What if you had to perform some heavy computations that many number of times then?

For these problems loops come to rescue. Loops are one of the most powerful features in programming. They allow you to repeat a block of code multiple times without having to write the same code over and over again. Here's how we solve the "Hey, IronWill!" problem with a simple loop:

for i in range(5):
    print("Hey, IronWill!")
#This will print "Hey, IronWill!" 5 times

Want it 1000 times? Just change 5 to 1000, that’s it.

for i in range(1000):
    print("Hey, IronWill!")
#This will print "Hey, IronWill!" 1000 times

Want it 100000 times? Just change 1000 to 100000.

for i in range(100000):
    print("Hey, IronWill!")
#This will print "Hey, IronWill!" 100000 times

Just one line of code with infinite possibilities, amazing isn’t it?

After completing this tutorial, you'll have complete command over loops in Python! You'll be able to:

  • Automate repetitive tasks with just a few lines of code

  • Process large amounts of data efficiently

  • Create interactive programs that respond to user input

  • Build complex patterns and calculations with ease

By the end of this tutorial, you'll never have to write the same line of code hundreds of times again. Instead, you'll think like a programmer: "How can I make the computer do this repetitive work for me?"

Let's dive in and unlock the power of loops! 🚀


Python has two main types of loops:

  1. for loops - when you know how many times you want to repeat

  2. while loops - when you want to repeat until a condition becomes false

for loop

A for loop is used when you know exactly how many times you want to repeat a block of code, or when you want to iterate through each item in a collection (like a list, string, or range of numbers).

Think of it like giving instructions to someone: "For each item in this box, do the following steps.”

  • for - The keyword that starts the loop

  • variable - A temporary name that holds each item from the sequence (you can name this anything)

  • in - Connects the variable to the sequence

  • sequence - What you're looping through. It can be numbers, list items, characters in a string, etc.

  • : - Marks the end of the for loop declaration

  • Loop body - The indented code that runs for each iteration. It is important to give the indentation because the intended code will be considered as loop body and it will be executed repeatedly.

How It Works (Step by Step)

  1. Python takes the first item from the sequence

  2. Assigns it to the variable

  3. Runs all the indented code below

  4. Goes back to step 1 with the next item

  5. Repeats until there are no more items in the sequence

Let us look at an example which would provide us more clarity:

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

for fruit in fruits:
    print("I'm eating a ",fruit)

What Python does internally is:

Step 1: fruit = "apple" → prints "I'm eating a apple"

Step 2: fruit = "banana" → prints "I'm eating a banana"

Step 3: fruit = "orange" → prints "I'm eating a orange"

Step 4: No more items → loop ends

Understanding the range( ) function:

The range( ) function is your best friend when you are dealing with for loops and it is the most commonly used sequence in for loops. It generates a sequence of numbers, but it does not actually create a list in memory. It can generate numbers on demand which means it generates the number only when the loop asks for it, making it super efficient even for huge ranges. Let us look at that will the help of an example:

for i in range(1000000):
    # Do something with each number
#This would occupy almost no space in the memory as it would not generate 1000000 numbers in memory

for i in list(range(1000000)):
 # Do something with each number
#This would occupy very large space in the memory as it would  generate list of 1000000 numbers in memory

You can convert the range to list by type casting it. But it is not advisable if you just want to iterate it as you will simply occupy a large amount of memory.

There are typically three ways to use range( ) function:

  1. range(stop) - Starts from 0

     for i in range(5):
         print(i)
    

    Output: 0,1,2,3,4

    It means that give me numbers starting 0 , up to 5 , but do not include 5. This is the most important thing to note that in range function, the stop value is never included. So while specifying stop, you got to be mindful of what you want and what to specify in value.

  2. range(start,stop) - Custom starting point

     for i in range(2, 7):
         print(i)
    

    Output: 2,3,4,5,6

    It means that give me numbers starting from 2, up to 7 but do not include 7. The start value is always included but the stop value is not included. If we don’t specify start explicitly, then by default it’s value is considered as 0.

  3. range(start,stop,step) - Custom step size

     for i in range(0,10,2):
         print(i)
    

    **Output:**0,2,4,6,8

    It means that give me number starting from 0, up to 10 but not include 10. The step value increases the count with whatever have been specified as its value(here it is 2). If we don’t specify step explicitly, then by default it’s value is considered as 1. If we specify negative value in step, then it goes backwards. Let us look that with the help of an example:

     for i in range(10,0,-1):
         print(i)
    

    Output: 10,9,8,7,6,5,4,3,2,1

    Negative values of step help especially when we have to read a string or a list in reverse order.

    Lets look at a practical example of for loop by building a program that takes the input number from user and gives the multiplication table of that number.

     number = int(input("Please enter the number of which you want multiplication table: "))
    
     for i in range(1,11):
     #Here range is 11 because we want to have values from 1 to 10 and 11 is not included
         print(num," X ", i, " = " , num*i)
    

    Example of for loop:

     numbers = [45, 22, 88, 56, 92, 33]
     largest = numbers[0]  # Start with the first number
    
     for number in numbers:
         if number > largest:
             largest = number
    
     print("The largest number is: ",largest)  # Output: 92
    

    while loop

    A while loop is used when you want to repeat a block of code as long as a certain condition remains true. Unlike for loops where you know exactly how many times to repeat, while loops continue until something changes.

    Think of it like: "While this condition is true, keep on repeating these steps..."

    • while - The keyword that starts the loop

    • condition - A boolean expression that evaluates to True or False

    • : - Marks the end of the while loop declaration

    • Loop body - The indented code that runs repeatedly

    • Condition modifier - Code that eventually makes the condition False which is very important or else the loop would keep on executing and will eventually fall into infinite loop. Most of the times the condition modifier would be increment(+) or decrement(-).

How It Works (Step by Step)

  1. Python checks if the condition is True

  2. If True: runs the loop body code

  3. Goes back to step 1 and checks the condition again

  4. If False: exits the loop and continues with the rest of the program

  5. Important: If the condition never becomes False, you will get an infinite loop

Let us look at an example which would provide us more clarity:

number = 10

while number>=0:
    print(number)
    number = number -1

Output: 10,9,8,7,6,5,4,3,2,1,0

Let us look at another example where you have to enter the password, and untill you enter the correct password, it won’t give you access to move further and instead ask you to enter the password again.

password = ""

while password != "secret":
    password = input("Enter the password: ")
    if password != "secret":
        print("Wrong password! Try again.")

print("Access granted")

When to Use While Loops and When to Use For Loops?


Loop Control Statements

Sometimes you need more control over how your loops behave. Python provides special keywords that let you modify the normal flow of loops. These are called loop control statements. There are basically three types of control statements, they are:

  1. break - exit the loop immediately

  2. continue - skip the rest of the current iteration and go to the next one

  3. pass - do nothing

Loop control statements are commonly used within conditional statements like if to control loop execution based on specific conditions. break and continue are widely used whereas pass is not used very frequently. They are typically executed when certain condition is met, allowing you to modify the normal flow of loop iterations.

Exit the Loop Immediately - break

The break statement immediately exits the loop, regardless of the loop condition. It's like an emergency exit door for your loop. You can think of it as “Stop everything and get out of this loop right now!” The control of the program is transferred to the end of the loop.

Let us look at an example, for better clarity:

for i in range(10):
    if i == 5:
        break  # Exit the loop when i equals 5
    print(i)

print("Loop ended!")

Output:

0
1
2
3
4
Loop ended!

The loop was supposed to run 10 times (0 to 9), but when i reached 5, the break statement stopped it immediately.

Let us look at another example where we search a name in a list with the help of a loop and exit the loop as soon as we find that name.

names = ["Rohit","Rahul","Virat","Bumrah","Hardik","Surya"]
target ="Bumrah"

for name in names:
    print("Checking: ",name)
    if name=="Bumrah":
        print("Found: ",name)
        break 
        #No need to move further, we have found our target name

print("Search completed")
Checking: Rohit
Checking: Rahul
Checking: Virat
Checking: Bumrah
Found: Bumrah
Search completed

Skip the rest of the current iteration and go to the next one - continue

The continue statement skips the rest of the current iteration and jumps to the next iteration of the loop. It's like saying skip this iteration and move to the next.

Let us look at it with the help of an example for better clarity:

for i in range(10):
    if i % 2 == 0:  # If i is even
        continue    # Skip the rest and go to next iteration
    print(i)        # This only prints for odd numbers

print("Done")

Output:

1
3
5
7
9
Done

When i was even (0, 2, 4, 6, 8), the continue statement skipped the print(i) line and went directly to the next iteration. In this loop the control of the program is transferred to the beginning of the loop for next iteration. In case of while loop, it is advised to modify the conditions before executing continue statement (if not already done) as it may enter in an infinite loop.

It is important to note that break and continue only affect the innermost loop they are in, incase of nested loops.

Do nothing - pass

The pass statement does absolutely nothing. It is a placeholder that says I am not ready to write code here yet, but I need something so Python doesn't complain. It is used when you are planning code structure but have not written the logic yet or when you want a loop to do nothing under certain conditions. Let us look at it with the help of an example:

for i in range(10):
    if i < 5:
        pass  # Do nothing for number < 5
    else:
        print("Number: ",i)

Output:

5
6
7
8
9

For i = 0,1,2,3,4 the loop does nothing here as it encounters pass statement. For i = 5,6,7,8,9 it prints the value of i.


Nesting of loops

You can put loops inside loops , just exactly like nesting of conditional statements. Matrix operations like matrix addition , matrix subtraction and matrix multiplication often uses nested loops. For printing certain patterns also we need nested loops. Let us print a pattern using nested loops,

n = int(input("Enter the number of lines: "))

for i in range(n):
    for j in range(i+1):
        print("*",end="") # Here end="" prevents automatic newline of print() function
    print() # New line after each row
Enter the number of lines: 5
*
**
***
****
*****

We can print multiple patterns with the help of nesting of loops. From simple triangles to complex designs, mastering nested loops builds the logical thinking skills needed for advanced programming. We will explore pattern printing techniques in detail in our upcoming dedicated tutorial.


Congratulations! You've Mastered Python Loops!

You've just unlocked one of programming's most powerful secrets of making computers do repetitive work for you. Remember writing print(“Hey, IronWill!”) five times manually? Now you can do it 100,000 times with just two lines of code. You've mastered for loops, while loops, range(), loop control with break/continue, and built a project like generating multiplication table for a number. You are no longer thinking like someone who does tasks manually. You are thinking like a programmer who asks "How can I make the computer do this for me?"

Before our next tutorial, challenge yourself:

  1. Create a calculator that runs until the user says "stop".

  2. Counts vowels in a sentence.

  3. Word Reverser.(a program that takes a sentence and prints each word backwards, then asks if the user wants to reverse another sentence.)

Tomorrow's Tutorial on Functions & Recursion will teach you to write reusable code like a pro! If loops taught you automation, functions will teach you organization and code reuse. Get ready for mind-bending recursion where functions call themselves to solve complex problems. Your code is about to look truly professional! Stay Tuned

Enjoyed today’s blog? Don’t forget to like, share it with your friends, and leave your valuable feedback – it really helps! Your support keeps the content coming.

Every expert programmer started exactly where you are now, the difference is they kept practicing and building on what they learned. So keep practicing and Happy Coding! 🚀

0
Subscribe to my newsletter

Read articles from Raj Patel directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Raj Patel
Raj Patel

Hey there! I'm Raj Patel, a passionate learner and tech enthusiast currently diving deep into Data Science, AI, and Web Development. I enjoy turning complex problems into simple, intuitive solutions—whether it's building real-world ML projects like crop disease detection for farmers or creating efficient web platforms for everyday use. I’m currently sharpening my skills in Python, Machine Learning , Javascript and love sharing what I learn through blogs and open-source contributions. If you're into AI, clean code, or building impactful tech—let’s connect!