Header Ads Widget

⚡ Premium Tools Hub • EXE Apps + Full Python Source Code
Lite • Pro • Bundle Packs • Instant Download

Jython Loops Tutorial: for, while, break, continue & Nested Loops

Introduction

Loops are one of the most essential programming concepts in Jython. They allow you to execute a block of code repeatedly without writing the same statements multiple times. Since Jython combines Python's elegant syntax with the power of the Java Virtual Machine (JVM), loops can also be used to iterate through Java collections such as ArrayList, HashMap, and HashSet.

Whether you're processing user input, reading files, automating repetitive tasks, or working with Java APIs, loops make your programs more efficient, readable, and maintainable.

In this tutorial, you'll learn:

  • What loops are
  • Types of loops in Jython
  • The for loop
  • The while loop
  • The range() function
  • Nested loops
  • Loop control statements (break, continue, pass)
  • The else clause with loops
  • Iterating through Java collections
  • Common mistakes
  • Best practices
  • Frequently asked questions

What Are Loops?

A loop repeatedly executes a block of code as long as a condition is met or until all items in a collection have been processed.

Without loops:

print("Welcome")
print("Welcome")
print("Welcome")
print("Welcome")
print("Welcome")

Using a loop:

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

Output:

Welcome
Welcome
Welcome
Welcome
Welcome

Loops reduce code duplication and make programs easier to maintain.


Types of Loops in Jython

Jython supports two primary loop types:

LoopPurpose
forIterate through sequences or collections
whileRepeat while a condition remains true

The for Loop

The for loop is used to iterate over a sequence such as a list, tuple, string, dictionary, or Java collection.

Syntax

for variable in sequence:
# code

Example:

fruits = ["Apple", "Orange", "Banana"]

for fruit in fruits:
print(fruit)

Output:

Apple
Orange
Banana

Using range()

The range() function generates a sequence of numbers.

Example:

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

Output:

0
1
2
3
4

range(start, stop)

for number in range(3, 8):
print(number)

Output:

3
4
5
6
7

range(start, stop, step)

for number in range(2, 11, 2):
print(number)

Output:

2
4
6
8
10

Looping Through a String

language = "Jython"

for letter in language:
print(letter)

Output:

J
y
t
h
o
n

Looping Through a List

numbers = [10, 20, 30, 40]

for number in numbers:
print(number)

Looping Through a Tuple

colors = ("Red", "Green", "Blue")

for color in colors:
print(color)

Looping Through a Dictionary

By default, dictionaries iterate over keys.

student = {
"name": "Alice",
"age": 21
}

for key in student:
print(key, student[key])

Output:

name Alice
age 21

Looping Through Dictionary Items

for key, value in student.items():
print(key, value)

The while Loop

A while loop repeats as long as its condition evaluates to True.

Syntax

while condition:
# code

Example:

count = 1

while count <= 5:
print(count)
count += 1

Output:

1
2
3
4
5

Infinite Loops

A loop whose condition never becomes false is called an infinite loop.

while True:
print("Running...")

Always provide a way to exit an infinite loop, typically using break.


The break Statement

The break statement immediately terminates the current loop.

for number in range(10):

if number == 5:
break

print(number)

Output:

0
1
2
3
4

The continue Statement

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

for number in range(6):

if number == 3:
continue

print(number)

Output:

0
1
2
4
5

The pass Statement

pass is a placeholder that performs no action.

for number in range(3):
pass

It is useful when creating code structures that will be completed later.


Nested Loops

A nested loop is a loop inside another loop.

Example:

for row in range(3):

for column in range(3):

print(row, column)

Output:

0 0
0 1
0 2
1 0
1 1
1 2
2 0
2 1
2 2

Creating a Multiplication Table

for i in range(1, 6):

for j in range(1, 6):

print(i * j, end=" ")

print()

Output:

1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25

Loop else Clause

Jython supports an optional else block after loops.

for number in range(3):
print(number)
else:
print("Loop completed.")

Output:

0
1
2
Loop completed.

The else block executes only if the loop finishes normally (not via break).


Using enumerate()

enumerate() returns both the index and value.

languages = ["Python", "Java", "Jython"]

for index, language in enumerate(languages):

print(index, language)

Output:

0 Python
1 Java
2 Jython

Iterating Through Java Collections

One of Jython's strengths is seamless interaction with Java collections.

Example using ArrayList:

from java.util import ArrayList

fruits = ArrayList()

fruits.add("Apple")
fruits.add("Orange")
fruits.add("Banana")

for fruit in fruits:
print(fruit)

Output:

Apple
Orange
Banana

Iterating Through a Java HashMap

from java.util import HashMap

student = HashMap()

student.put("Name", "Alice")
student.put("Age", 22)

for key in student.keySet():
print(key, student.get(key))

Output:

Name Alice
Age 22

Using Java Iterators

Some Java APIs provide explicit iterators.

iterator = fruits.iterator()

while iterator.hasNext():

print(iterator.next())

Practical Example: Sum Numbers

numbers = [5, 10, 15, 20]

total = 0

for number in numbers:
total += number

print(total)

Output:

50

Practical Example: Count Even Numbers

numbers = [1, 2, 3, 4, 5, 6]

count = 0

for number in numbers:

if number % 2 == 0:
count += 1

print(count)

Output:

3

Practical Example: Search in a List

names = ["John", "Emma", "Alice"]

target = "Emma"

for name in names:

if name == target:
print("Found")
break

Output:

Found

Performance Tips

  • Use for loops when iterating over collections.
  • Use while loops only when the number of iterations is unknown.
  • Avoid unnecessary nested loops for large datasets.
  • Exit loops early with break when appropriate.
  • Use Java collections directly when integrating with Java libraries.

Best Practices

Follow these recommendations when writing loops:

  • Choose meaningful loop variable names.
  • Keep loop bodies short and readable.
  • Avoid modifying collections while iterating over them.
  • Use range() for numeric iteration.
  • Prevent infinite loops by updating loop conditions.
  • Use break and continue sparingly.
  • Prefer for loops when processing sequences.
  • Add comments only for complex loop logic.

Common Mistakes

Forgetting to Update a while Loop Variable

Incorrect:

count = 1

while count <= 5:
print(count)

This results in an infinite loop.

Correct:

count = 1

while count <= 5:
print(count)
count += 1

Incorrect Indentation

Incorrect:

for number in range(3):
print(number)

Correct:

for number in range(3):
print(number)

Modifying a Collection During Iteration

Changing a collection while iterating over it can lead to unexpected behavior. Consider creating a copy or collecting changes to apply after the loop finishes.


Frequently Asked Questions (FAQ)

What is the difference between for and while loops?

  • for loops iterate over a sequence or collection.
  • while loops continue until a specified condition becomes false.

What does break do?

break immediately exits the nearest loop.


What does continue do?

continue skips the current iteration and moves to the next iteration of the loop.


Can Jython iterate over Java collections?

Yes. Jython can directly iterate through Java collections such as ArrayList, HashMap, HashSet, and LinkedList.


What is an infinite loop?

An infinite loop is a loop whose terminating condition never becomes false. Use break or update the loop condition to prevent it from running indefinitely.


Conclusion

Loops are a cornerstone of Jython programming, allowing you to automate repetitive tasks, process data efficiently, and write concise, maintainable code. Whether you're using for loops, while loops, nested loops, or loop control statements like break and continue, mastering these constructs will significantly improve your programming skills.

Combined with Jython's seamless access to Java collections and APIs, loops become an even more powerful tool for building automation scripts, enterprise applications, and JVM-based software. Understanding loop behavior and following best practices will help you write efficient, reliable, and scalable Jython programs.

Jython Loops Tutorial: for, while, break, continue & Nested Loops


Post a Comment

0 Comments