In this post, we will have a look on various type of looping constructs in Ruby.

*Note: First of all keep in mind that Python is very strict on tab keys. Each tab key represents child statement.

Loops are program constructs that are used to repeat statements inside its body until some condition is satisfied.

Following are the type of loops we can use in Python:

1. While Loop

While loop executes its statements till the condition is true. The syntax of while loop is:

Syntax

while condition:

Example:

i = 1
n = 5

while i <= 10:
  print("%d * %d = %d" % (i, n, i*n))
  i +=1
2. Single line While Loop

We can write the while loop on single line as well.

Example

i = 1
n = 5

while i <= 10:  print("%d * %d = %d" % (i, n, i*n)); i+=1
3. For Loop

For loops are used to iterate over a predefined set of data. For example, iterate over an array or iterate over a given range.

a. Counter based for loop

This loop executes its statements by updating a loop counter. When loop counter reaches the maximum specified value, the loop execution stops. Here is the syntax:

Syntax

for counter in range(start, end+1)

end

Let us say, we have to run the loop from 1 to 10, the range for this will have start=1 and end=10+1. The loop counts up to one less than end value.

Let us check an example that calculates the sum of first 10 numbers.

Example

sum = 0
for counter in range(1,11):
    sum = sum + counter

print("Sum %d" % sum)

By default, the loop counter increments by 1. If you want to increment loop counter by some other value, you can do:

for counter in range(1,11,2):
    print(counter);

b. For loop iterating over array

This type of for loop is used to iterate over a collection like array. The syntax is:

Syntax

for variable in collection:

Example

languages = ["Python", "PHP", "Java", "C#"] 
for x in languages:
    print(x)
Breaking the loop

We can stop the execution of a loop in the middle with the help of break statement. Here is an example:

n = 1
while n%10 != 0:
  print("n = %d" % n)
  n +=1

  if n>5:
    break
Skipping loop statements

We can skip rest of the loop and jump to next iteration with the help of continue. Here is an example that prints odd numbers from 1 to 10:

n = 1
while n<10:

  n +=1

  if n%2 == 0:
    continue

  print("n = %d" % n)