Skip to main content

Python type() Function

When learning Python, you will work with different types of data, such as numbers, text, decimal values, and Boolean values. Python provides several built-in functions to help you work with these data types. One of the most useful functions is the type() function . The type() function tells you the data type of a value or variable. It helps you understand what kind of data Python is working with and can make debugging your programs easier. For example, consider these variables: age = 20 price = 99.50 name = "Rahul" is_student = True Although all four variables store data, their data types are different. Python allows us to check these types using type() . Let's understand how it works with simple examples. 1. What Is the type() Function in Python? The type() function is a built-in Python function that returns information about the type of an object. In beginner-level programming, you can use it to check whether a value is an integer, a floating-point number, a string,...

Kotlin Loops Made Simple: Repeat Tasks with for, while and do-while

Imagine you need to print the numbers from 1 to 100.

One approach would be to write:

println(1)
println(2)
println(3)
println(4)
println(5)

And continue until 100.

Clearly, this would be inefficient and difficult to maintain.

Programming languages provide loops to solve exactly this problem.

A loop allows a program to execute the same block of code repeatedly without requiring you to write the same instructions again and again.

In the previous article, we learned how Kotlin can make decisions using if, else, and when.

Now we will learn how Kotlin can repeat operations using:

  • for loops

  • while loops

  • do-while loops

  • Ranges

  • break

  • continue

  • Nested loops

  • Practical programs

Loops are extremely important in Android development because applications frequently need to process lists, display collections of data, repeat operations, and perform tasks until a particular condition is satisfied.


What Is a Loop?

A loop is a programming structure that repeatedly executes a block of code.

For example:

Start
  ↓
Check condition
  ↓
Execute code
  ↓
Repeat
  ↓
Condition false?
  ↓
Stop

Consider printing numbers from 1 to 5:

1
2
3
4
5

Instead of writing five separate println() statements, we can use a loop.


Why Are Loops Important?

Loops are useful whenever an operation needs to be performed repeatedly.

For example:

  • Printing numbers

  • Processing a list of students

  • Calculating totals

  • Searching through data

  • Displaying items

  • Processing API results

  • Repeating a task

  • Iterating through database records

Consider a shopping application.

If a cart contains 50 products, you don't want to write separate code for every product.

Instead:

Shopping Cart
     ↓
Loop through products
     ↓
Display each product

This is one of the fundamental uses of loops.


The for Loop

The for loop is one of the most commonly used loops in Kotlin.

A basic example is:

for (i in 1..5) {
    println(i)
}

Output:

1
2
3
4
5

Let's understand what is happening.

1..5

represents a range from 1 to 5.

The loop takes each value from the range and stores it in i.

The loop therefore executes five times.


Understanding the .. Operator

The .. operator creates an inclusive range.

For example:

1..5

represents:

1, 2, 3, 4, 5

Similarly:

10..15

represents:

10, 11, 12, 13, 14, 15

Example:

for (number in 10..15) {
    println(number)
}

Output:

10
11
12
13
14
15

Printing Numbers from 1 to 10

Let's create a simple program.

fun main() {

    for (i in 1..10) {
        println(i)
    }
}

Output:

1
2
3
4
5
6
7
8
9
10

Notice how only a few lines of code are needed to print ten numbers.

This becomes even more useful when working with hundreds or thousands of values.


Printing Numbers in Reverse

What if we want:

10
9
8
7
6
5
4
3
2
1

We can use downTo.

for (i in 10 downTo 1) {
    println(i)
}

Output:

10
9
8
7
6
5
4
3
2
1

Using step

Sometimes you don't want to move through every number.

For example:

2
4
6
8
10

You can use step.

for (i in 2..10 step 2) {
    println(i)
}

Output:

2
4
6
8
10

Here:

step 2

means that the value increases by 2 each time.


Odd Numbers Using step

We can also print odd numbers.

for (i in 1..10 step 2) {
    println(i)
}

Output:

1
3
5
7
9

Looping Through a String

A for loop can also process individual characters in a string.

Example:

val name = "Kotlin"

for (character in name) {
    println(character)
}

Output:

K
o
t
l
i
n

This can be useful when processing text.


Looping Through a List

Loops become particularly useful when working with collections.

For example:

val fruits = listOf("Apple", "Banana", "Mango", "Orange")

for (fruit in fruits) {
    println(fruit)
}

Output:

Apple
Banana
Mango
Orange

The loop processes each item in the list.

Later, this concept will be extremely important in Android development when displaying lists of information.


What Is a while Loop?

A while loop repeatedly executes code while a condition remains true.

Basic syntax:

while (condition) {
    // code
}

Example:

var number = 1

while (number <= 5) {
    println(number)
    number++
}

Output:

1
2
3
4
5

How Does a while Loop Work?

Let's break it down.

Initially:

number = 1

Kotlin checks:

number <= 5

Because it is true, the loop executes.

Then:

number++

increases the value.

The process continues:

1 → 2 → 3 → 4 → 5 → 6

When the value becomes 6:

6 <= 5

is false.

The loop stops.


Why Is number++ Important?

Consider this:

var number = 1

while (number <= 5) {
    println(number)
}

This loop has a problem.

The value of number never changes.

Therefore, the condition remains true forever.

This creates an infinite loop.

Always make sure that a loop has a way to eventually reach its stopping condition.


Increment and Decrement Operators

You will frequently encounter:

++
--

++ increases a value by 1.

Example:

var number = 5
number++

Now:

number = 6

Similarly:

var number = 5
number--

results in:

number = 4

These operators are especially useful with loops.


The do-while Loop

The third major loop is:

do-while

Its syntax is:

do {
    // code
} while (condition)

Example:

var number = 1

do {
    println(number)
    number++
} while (number <= 5)

Output:

1
2
3
4
5

while vs do-while

There is an important difference.

while

The condition is checked before the loop body executes.

while (condition) {
    // code
}

do-while

The loop body executes at least once, and the condition is checked afterward.

do {
    // code
} while (condition)

Consider:

var number = 10

while (number < 5) {
    println(number)
}

Nothing is printed because the condition is false from the beginning.

Now consider:

var number = 10

do {
    println(number)
} while (number < 5)

Output:

10

The code inside the do block executes once before the condition is checked.


When Should You Use Each Loop?

There is no single loop that is best for every situation.

Use for when:

You know what collection or range you want to iterate through.

Example:

for (i in 1..10) {
    println(i)
}

Use while when:

You want to continue until a condition changes.

Example:

while (isRunning) {
    // perform task
}

Use do-while when:

The code must execute at least once.

Example:

do {
    // perform task
} while (condition)

The break Statement

Sometimes you want to stop a loop before it reaches its normal endpoint.

Kotlin provides:

break

Example:

for (i in 1..10) {

    if (i == 6) {
        break
    }

    println(i)
}

Output:

1
2
3
4
5

When i becomes 6, the break statement stops the loop.


The continue Statement

The continue statement skips the current iteration and moves to the next one.

Example:

for (i in 1..5) {

    if (i == 3) {
        continue
    }

    println(i)
}

Output:

1
2
4
5

When i is 3, Kotlin skips that iteration.

The loop continues with 4.


break vs continue

Remember the difference:

break
  ↓
Stops the loop completely

while:

continue
  ↓
Skips the current iteration

Example:

for (i in 1..10) {

    if (i == 5) {
        break
    }

    println(i)
}

Stops completely at 5.

But:

for (i in 1..10) {

    if (i == 5) {
        continue
    }

    println(i)
}

skips 5 but continues with 6, 7, 8, 9, and 10.


Nested Loops

A loop can be placed inside another loop.

This is called a nested loop.

Example:

for (i in 1..3) {

    for (j in 1..3) {
        println("i = $i, j = $j")
    }
}

Output:

i = 1, j = 1
i = 1, j = 2
i = 1, j = 3
i = 2, j = 1
i = 2, j = 2
i = 2, j = 3
i = 3, j = 1
i = 3, j = 2
i = 3, j = 3

Nested loops are useful for working with tables, grids, matrices, and other multidimensional data.


Creating a Multiplication Table

Let's use a loop to create a multiplication table.

fun main() {

    val number = 5

    for (i in 1..10) {
        println("$number × $i = ${number * i}")
    }
}

Output:

5 × 1 = 5
5 × 2 = 10
5 × 3 = 15
5 × 4 = 20
5 × 5 = 25
5 × 6 = 30
5 × 7 = 35
5 × 8 = 40
5 × 9 = 45
5 × 10 = 50

This is a simple example of how loops can eliminate repetitive code.


Calculating a Sum

Loops can also be used to calculate totals.

Example:

fun main() {

    var sum = 0

    for (i in 1..10) {
        sum += i
    }

    println("Sum = $sum")
}

Output:

Sum = 55

The program adds:

1 + 2 + 3 + ... + 10

and stores the result in sum.


Finding Even Numbers

Let's print all even numbers from 1 to 20.

fun main() {

    for (i in 1..20) {

        if (i % 2 == 0) {
            println(i)
        }
    }
}

Output:

2
4
6
8
10
12
14
16
18
20

Here we combine two concepts:

Loop + Condition

This combination is extremely common in programming.


Finding Odd Numbers

We can modify the same program:

fun main() {

    for (i in 1..20) {

        if (i % 2 != 0) {
            println(i)
        }
    }
}

Output:

1
3
5
7
9
11
13
15
17
19

Counting Numbers in a List

Suppose we have:

val numbers = listOf(10, 25, 40, 15, 50)

We want to count numbers greater than 20.

var count = 0

for (number in numbers) {

    if (number > 20) {
        count++
    }
}

println("Count = $count")

Output:

Count = 3

The numbers greater than 20 are:

25
40
50

Looping Through a List in Android

Loops become especially important when working with application data.

Imagine an Android application receives:

Apple
Banana
Mango
Orange

from a database or API.

The application needs to process each item.

Conceptually:

Data
 ↓
List
 ↓
Loop
 ↓
Process each item
 ↓
Display results

Modern Android applications often use higher-level collection and UI tools rather than manually writing loops for every display operation, but understanding loops remains essential because the underlying programming logic still depends on iteration.


A More Practical Example: Shopping Cart

Imagine a shopping application.

The cart contains:

val prices = listOf(500, 250, 1000, 750)

We want to calculate the total.

var total = 0

for (price in prices) {
    total += price
}

println("Total = ₹$total")

Output:

Total = ₹2500

The same basic concept can be used when processing data received from a database or API.


Common Loop Mistakes

1. Creating an Infinite Loop

Incorrect:

var i = 1

while (i <= 10) {
    println(i)
}

The value of i never changes.

Correct:

var i = 1

while (i <= 10) {
    println(i)
    i++
}

2. Incorrect Range

Remember that:

1..5

includes 5.

So it represents:

1, 2, 3, 4, 5

If you need an end-exclusive range, Kotlin also provides:

1..<5

which represents:

1, 2, 3, 4

This distinction is useful when working with indexes and collections.


3. Modifying the Wrong Variable

Consider:

var i = 1

while (i <= 10) {
    println(i)

    // Incorrect variable changed here
}

Make sure the variable controlling the condition is updated appropriately.


4. Using break Unnecessarily

break is useful, but excessive use can make logic harder to understand.

Before adding break, consider whether the loop itself can be designed more clearly.


Practice Exercises

Now it's your turn.

Try solving these problems without looking at the solutions.

Exercise 1: Print Numbers

Print numbers from 1 to 100 using a for loop.

Exercise 2: Reverse Counting

Print:

100
99
98
...
1

using downTo.

Exercise 3: Even Numbers

Print all even numbers between 1 and 50.

Exercise 4: Odd Numbers

Print all odd numbers between 1 and 50.

Exercise 5: Multiplication Table

Take a number and print its multiplication table from 1 to 10.

Exercise 6: Sum of Numbers

Calculate the sum of numbers from 1 to 100.

Exercise 7: Factorial

Calculate the factorial of a number using a loop.

For example:

5! = 5 × 4 × 3 × 2 × 1

Therefore:

5! = 120

Exercise 8: Find the Largest Number

Given a list of integers, use a loop to find the largest value.

Exercise 9: Count Positive Numbers

Given a list of integers, count how many values are positive.

Exercise 10: Search a List

Given a list and a target number, determine whether the target exists in the list.


A Quick Look at Looping Through Indexes

Sometimes you need both the index and the value.

For example:

val fruits = listOf("Apple", "Banana", "Mango")

You can use:

for ((index, fruit) in fruits.withIndex()) {
    println("$index: $fruit")
}

Output:

0: Apple
1: Banana
2: Mango

This becomes useful when you need to know both what item you are processing and where it appears in the collection.


Why Loops Matter for Android Developers

Loops may appear to be a basic programming topic, but they are used throughout software development.

Consider an Android application displaying a list of students:

Student 1
Student 2
Student 3
Student 4
...
Student 100

The application doesn't need 100 separate blocks of logic.

It can process the collection programmatically.

Similarly, an application may receive hundreds of products from an API:

API
 ↓
JSON Data
 ↓
Objects/List
 ↓
Process Data
 ↓
Display UI

Understanding iteration is therefore essential before working with collections, databases, APIs, and real-world Android projects.


What You Learned Today

In this article, we learned:

  • What loops are

  • Why loops are useful

  • for loops

  • Ranges

  • ..

  • ..<

  • downTo

  • step

  • while

  • do-while

  • Increment and decrement

  • break

  • continue

  • Nested loops

  • Looping through strings

  • Looping through lists

  • Practical programming examples

You now know three major looping structures in Kotlin.

for
while
do-while

What's Coming Next?

Our Kotlin programs can now:

Store values
     ↓
Make decisions
     ↓
Repeat operations

There is another major programming concept we need before moving deeper into Android development:

Functions.

Instead of placing an entire program inside one large block, functions allow us to divide our code into smaller, reusable pieces.

For example:

Application
     │
     ├── loginUser()
     ├── calculateTotal()
     ├── validateInput()
     └── displayResult()

In the next article, we will learn:

  • What functions are

  • Creating functions

  • Parameters

  • Arguments

  • Return values

  • Default arguments

  • Named arguments

  • Single-expression functions

  • Practical Kotlin functions

Understanding functions will be especially important when we begin building more structured Android applications.


Final Thoughts

Loops are one of the most powerful basic tools in programming.

They allow you to replace hundreds of repetitive statements with a few lines of well-designed code.

Comments

Popular posts from this blog

Understanding Comments in Java: A Beginner’s Guide

When learning Java programming, one of the first concepts you’ll come across is comments . Comments may not affect how a program runs, but they play a crucial role in making code more understandable, readable, and maintainable. Let’s dive deeper into what comments are, why they’re important, and the different types of comments in Java. What are Comments in Java? A comment in Java is a piece of text written within a program that is ignored by the compiler . In other words, comments are notes for humans, not instructions for machines. They help developers explain the purpose of code, describe logic, or temporarily disable certain lines of code without deleting them. Why are Comments Important? 📌 Readability – Comments make code easier to understand for you and others. 📌 Maintenance – When you revisit your code after months, comments remind you what you were doing. 📌 Collaboration – In team projects, comments explain code to fellow developers. 📌 Debugging – You c...

Java Program to Check Voting Eligibility

In this program, we’ll take the user’s age as input and check whether the person is eligible to vote or not. In India, the minimum age required to vote is 18 years . 💻 Program Code // Java Program to Check Voting Eligibility import java.util.Scanner; public class VotingEligibility { public static void main(String[] args) { // Create Scanner object to take input from user Scanner sc = new Scanner(System.in); // Ask user to enter age System.out.print("Enter your age: "); int age = sc.nextInt(); // Check eligibility if (age >= 18) { System.out.println("You are eligible to vote."); } else { System.out.println("You are not eligible to vote yet."); System.out.println("You can vote after " + (18 - age) + " year(s)."); } sc.close(); // Close the scanner } } 🧠 Explanation import java.util.Scanner; → Imp...

Java Program to Calculate Total Marks and Average of Five Subjects

💡 Program Explanation In this program: The user will input marks of five subjects . The program will calculate the total marks and average . It will then display both results clearly. 🧑‍💻 Java Code: // Java Program to Calculate Total Marks and Average of Five Subjects import java.util.Scanner; // Importing Scanner class for user input public class TotalAndAverage { public static void main(String[] args) { // Creating Scanner object to take input from user Scanner sc = new Scanner(System.in); // Declaring variables for five subjects double subject1, subject2, subject3, subject4, subject5; // Taking marks input for each subject System.out.print("Enter marks of Subject 1: "); subject1 = sc.nextDouble(); System.out.print("Enter marks of Subject 2: "); subject2 = sc.nextDouble(); System.out.print("Enter marks of Subject 3: "); subject3 = sc.nextDo...