Thursday, 20 June 2019

break Statement in Java

In this tutorial you’ll learn about break statement in Java. When you are working with loops where loop body is repeatedly executed, you may have a scenario where you want to skip the execution of statements inside the loop or you may want to terminate the loop altogether. To handle these two scenarios there are two control statements in Java- continue and break. In this tutorial you’ll learn about Java break statement along with usage examples.

Where do you use break statement in Java

break statement in Java can be used in following scenarios-

  1. For terminating a loop– If there is a break statement with in a for loop, while loop or do-while loop the loop is terminated and the control moves to the statement immediately following the loop.
  2. For terminating switch statement– In Java switch statement if a case is followed by a break statement then the switch statement is terminated. For usage of break statement with switch statement in Java refer this post- Switch-Case Statement in Java
  3. Using labeled break statement– You can use labeled break statement to exit out of a labelled block.

break statement Java examples

1- Using break statement to break out of a for loop. In the example a list of cities is iterated and searched for a specific city. If the city is found loop is terminated using a break statement.

public class BreakJava {

    public static void main(String[] args) {
        List<String> cities = Arrays.asList("Beijing", "London", "Santiago", "St. Petersburg", "Helsinki");
        for(String city : cities) {
            if(city.equals("Santiago")) {
                System.out.println("Found city - " + city);
                // terminate loop
                break;
            }                
        }
        System.out.println("Out of for loop");
    }
}

Output

Found city - Santiago
Out of for loop

2- Using break statement to terminate an infinite while loop.

public class BreakJava {

    public static void main(String[] args) {
        int i = 1;
        while(true){
            // terminate loop when i is greater than 5
            //display i's value otherwise
            if(i > 5)
                break;
            System.out.println("i- " + i);
            i++;
        }
    }
}

Output

i- 1
i- 2
i- 3
i- 4
i- 5

3- When break statement is used with nested loops, break statement terminates the innermost loop in whose scope break is used.

public class BreakJava {

    public static void main(String[] args) {
        for(int i = 1; i <= 3; i++){
            System.out.print(i + "- ");
            for(int j = 0; j < 10; j++){
                System.out.print("*");
                // terminate inner loop
                if(j == 6)
                    break;
            }
            System.out.println();                   
        }        
        System.out.println("Out of loop");
    }
}

Output

1- *******
2- *******
3- *******
Out of loop

Here break statement is used in the scope of outer loop so outer for loop is terminated.

public class BreakJava {

    public static void main(String[] args) {
        for(int i = 1; i <= 6; i++){
            if(i == 4)
                break;
            System.out.print(i + "- ");
            for(int j = 0; j < 10; j++){
                System.out.print("*");
            }
            System.out.println();                   
        }        
        System.out.println("Out of loop");
    }
}

Output

1- **********
2- **********
3- **********
Out of loop

4- With unlabeled break statement you can come out of the innermost loop. If you want to come out of a deeply nested loop you can use labeled break statement which helps in coming out of more than one blocks of statements.

For example in the following code two for loops are there and labeled break statement helps in coming out of both the loops.

public class BreakJava {

    public static void main(String[] args) {
        int[][] array = { 
            {1, 2, 3 },
            {4, 5, 6 },
            {7, 8, 9 }
        };
        int searchedNum = 5;
        boolean flag = false;
        int i = 0, j = 0;
        // label
        outer:
        for (i = 0; i < array.length; i++) {
            for (j = 0; j < array[i].length; j++) {
                if (array[i][j] == searchedNum) {
                    flag = true;
                    // lebeled break
                    break outer;
                }
            }
        }
        if(flag) {
            System.out.println("Found element " + searchedNum + " at index " + i + " and " + j );
        }else {
            System.out.println("Element " + searchedNum + " not found in the array" );
        }
    }
}

Output

Found element 5 at index 1 and 1

That's all for this topic break Statement in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. if else Statement in Java With Examples
  2. Arithmetic And Unary Operators in Java
  3. this Keyword in Java With Examples
  4. Constructor in Java
  5. Abstract Class in Java

You may also like -

  1. BigInteger in Java
  2. String Vs StringBuffer Vs StringBuilder in Java
  3. Map.Entry Interface in Java
  4. Deadlock in Java Multi-Threading
  5. Selection Sort Program in Java
  6. How to Display Pyramid Patterns in Java - Part1
  7. Python First Program - Hello World
  8. How MapReduce Works in Hadoop

Wednesday, 19 June 2019

pass Statement in Python

In this tutorial you'll learn about pass statement in Python which acts as a placeholder.

Python pass statement

pass statement is a null operation, when it is executed, nothing happens. It is useful as a placeholder when a statement is required syntactically, but you don't want to do any operation.

For example you have an array of numbers and you want to display only those numbers which are less than 100.

numbers = [89, 102, 45, 234, 67, 10, 333, 32]
for num in numbers:
    if num > 100:
        #do nothing
        pass
    else:
        print('number is', num)

Output

 
number is 89
number is 45
number is 67
number is 10
number is 32

As you can see here if-else statement is used to check whether number is greater than or 100 or not. In case it is then you do nothing and that is indicated by using pass statement.

In most of the cases where pass statement is used you can very well write the code without using pass statement too but using pass statement do increases readability.

Python pass statement also ensures that indentation error is not thrown. For example suppose there is a Person class where you have a method to display Person data. You are planning to implement method that will fetch Person details from DB so you want to keep a method as a TODO reminder.

class Person:
    def __init__(self, name, age):
        print('init called')
        self.name = name
        self.age = age

    def display(self):
        print('in display')
        print("Name-", self.name)
        print("Age-", self.age)

    def retrieveData(self):
        #TODO has to be implemented to fetch details from DB

person = Person('John', 40)
person.display()

But running this class gives an error “IndentationError: expected an indented block

In such case adding pass statement with unimplemented method ensures that IndentationError is not thrown.

    def retrieveData(self):
        #TODO has to be implemented to fetch details from DB
        pass

So, you can see that Python pass statement can be used where you need a place holder be it with in a for loop, while loop or if-else statement, after def or even after class and in exception handling too.

pass statement with class

Suppose you are deriving from Exception class to create a user defined exception class with out adding new behavior, then you can just use pass statement.

class MyException(Exception):
    pass

pass statement with exception handling

If you don’t want to do anything for a specific type of Exception after catching it you can use pass statement.

numbers = [89, 102, 0, 234, 67, 10, 333, 32]
for num in numbers:
    try:
        result = 1000/num
        print('Result is',result)
    except ZeroDivisionError:
        print('Division by Zero')
        result = 0
    except AttributeError:
        pass

That's all for this topic pass Statement in Python. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Name Mangling in Python
  2. Operator Overloading in Python
  3. Passing Object of The Class as Parameter in Python
  4. Global Keyword in Python With Examples
  5. Abstraction in Python

You may also like -

  1. Association, Aggregation And Composition in Java
  2. What Are JVM, JRE And JDK in Java
  3. Java Program to Detect And Remove Loop in a Linked List
  4. How to Read Input From Console in Java
  5. How HashMap Internally Works in Java
  6. Spring depends-on Attribute
  7. How to Create Ubuntu Bootable USB
  8. Word Count MapReduce Program in Hadoop

Tuesday, 18 June 2019

Java do-while Loop With Examples

In Java programming language there are three types of loops- do-while loop, while loop, and for loop. In this post we’ll learn about do-while loop in Java along with usage examples.

do-while loop in Java

A do-while loop in Java repeatedly executes a statement or a block of statements while the given condition is true. Java do-while loop is similar to while loop except that the condition in do-while loop is evaluated after the loop body is executed.

Syntax of the do-while loop in Java is as follows-

 
do {
     // loop body
} while (condition);

In do-while loop condition that controls the loop is at the bottom of the loop so the loop always executes at least once where as in while loop if condition evaluates to false at the first time itself then the loop body is not executed at all.

Java do while loop execution flow

Java do while loop examples

1- Using do-while loop to print numbers 1..5.

 
public class DoWhileDemo {

    public static void main(String[] args) {
        int i = 1;
        do {
            System.out.println(i);
        } while (++i <= 5);
    }
}

Output

1
2
3
4
5

2- Since do-while loop is executed at least once so this loop is a good choice if you want to present a simple menu to the user, because you will definitely want menu to be displayed at least once.

public class DoWhileDemo {

    public static void main(String[] args) throws IOException {
        Scanner sc = new Scanner(System.in);
        int choice;
        do {
            System.out.println("----Language Menu----: ");
            System.out.println(" 1. Java");
            System.out.println(" 2. Python");
            System.out.println(" 3. C#");
            System.out.print("Enter your preferred language (1-3): ");
            choice = sc.nextInt();
            //while choice is not between 1..3 be in the loop
        } while( choice < 1 || choice > 3);
        sc.close();
        switch(choice) {
            case 1:
                System.out.println("Preferred Language- Java");            
                break;
            case 2:
                System.out.println("Preferred Language- Python");
                break;
            case 3:
                System.out.println("Preferred Language- C#");
                break;
        }
    }
}

Output

----Language Menu----: 
 1. Java
 2. Python
 3. C#
Enter your preferred language (1-3): 5
----Language Menu----: 
 1. Java
 2. Python
 3. C#
Enter your preferred language (1-3): 1
Preferred Language- Java

As you can see when 5 is entered, loop is repeated only when the choice is between 1..3 loop is terminated.

That's all for this topic Java do-while Loop With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. Arithmetic And Unary Operators in Java
  2. if else Statement in Java With Examples
  3. Type Wrapper Classes in Java
  4. static Keyword in Java With Examples
  5. Array in Java

You may also like -

  1. try-catch Block in Java Exception Handling
  2. Type Casting in Java
  3. ArrayList in Java
  4. How HashSet Works Internally in Java
  5. AtomicLong in Java Concurrency
  6. Python First Program - Hello World
  7. Spring Bean Life Cycle
  8. What is Big Data

if else Statement in Java With Examples

To control the execution flow Java programming language provides two types of conditional statements if-else and switch-case statement. In this post we'll talk about if and if-else statements in detail along with usage examples.

if-else statement in Java

The Java if statement is used to test a condition and take the execution path based on whether the condition is true or false. There are many combinations in which if statement can be used in Java.

  • if statement
  • if-else statement
  • if-else-if ladder
  • nested if statement

if statement in Java

Syntax of the Java if statement is as follows-

if(condition){
    //statement(s)
}

Here condition is a boolean expression that evaluates to either true or false. If the condition evaluates to true then the block of code enclosed in curly braces is executed. If the condition evaluates to false then the if block is skipped.

If there is only a single statement with in the if condition then the curly braces are optional.

Java if statement flow

if condition java

Java if statement examples

1- Testing a condition to check if passed number is greater than 5 or not.

public class IfDemo {

    public static void main(String[] args) {
        int i = 10;
        if(i > 5) {
            System.out.println("Value of i is greater than 5");
        }
        System.out.println("After if statement");
    }
}

Output

Value of i is greater than 5
After if statement

2- You can also use conditional operators like Conditional-AND (&&) and Conditional-OR (||) to create a condition.

public class IfDemo {

    public static void main(String[] args) {
        int i = 10;
        String test = "Hello";
        if(i > 5 && test.equals("Hello"))
            System.out.println("Inside if");
        System.out.println("After if statement");
    }
}

Output

Inside if
After if statement

Java if-else statement

Syntax of the Java if-else statement is as follows-

if(condition){
    // if block
}else{
    // else block
}

Here condition is a boolean expression that evaluates to either true or false. If the condition evaluates to true then if block is executed. If the condition evaluates to false then the else block is executed.

Java if-else statement flow

if else Java

Java if-else statement examples

public class IfDemo {

    public static void main(String[] args) {
        int i = 10;
        String test = "Hello";
        if(i > 20 && test.equals("Hello")) {
            System.out.println("Inside if");
        }else {
            System.out.println("Inside else");
        }
        System.out.println("After if-else statement");
    }
}

Output

Inside else
After if-else statement

In the example condition fails therefore else block is executed.

Java if-else-if ladder

You can also have an if statement followed by one or more else-if statements and an optional else statement at the end. Each if and else-if statement has a condition and a particular block is executed if the condition associated with that block evaluates to true. If none of the conditions evaluate to true then the else block (if present) is executed.

Syntax of Java if-else-if syntax is as follows-

if(condition1){
    statement(s);
}else if(condition2){
    statement(s);
}else if(condition3){
    statement(s);
}
.
.
.
else{
    statement(s);
}

Java if-else-if examples

Suppose you have requirement to add 10% to amount if amount is greater than 5000.
Add 15% if amount is more than 3000 but less than or equal to 5000.
Add 20% if amount is more than 1000 but less than or equal to 3000.
Otherwise add 25% to the amount.

public class IfDemo {

    public static void main(String[] args) {
        int amount = 5000;
        if(amount > 5000) {
            // add 10%
            amount = amount + (amount*10/100);
        }else if (amount > 3000 && amount <= 5000) {
            // add 15%
            amount = amount + (amount*15/100);
        }else if (amount > 1000 && amount <= 3000) {
            // add 20%
            amount = amount + (amount*20/100);
        }else {
            //add 25%
            amount = amount + (amount*25/100);
        }
        System.out.println("Amount is- " + amount);
    }
}

Output

Amount is- 5750

Java nested if-else statements

It is possible to have an if-else statement inside a if-else statement in Java. It is known as a nested if-else statement.

public class IfDemo {

    public static void main(String[] args) {
        int amount = 8000;
        if(amount > 5000) {
            if(amount > 7000 && amount <=10000) {
                amount = amount + (amount*10/100);
            }else {
                amount = amount + (amount*5/100);
            }    
        }else {
            if (amount > 3000 && amount <= 5000) {
                amount = amount + (amount*15/100);
            }else {
                amount = amount + (amount*20/100);
            }
        }
        System.out.println("Amount is- " + amount);
    }
}

Output

Amount is- 8800

That's all for this topic if-else Statement in Java With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. Java for Loop With Examples
  2. Equality And Relational Operators in Java
  3. String in Java Tutorial
  4. static Block in Java
  5. Marker Interface in Java

You may also like -

  1. finally Block in Java Exception Handling
  2. BigDecimal in Java
  3. How to Loop or Iterate an Arraylist in Java
  4. Java Collections Interview Questions And Answers
  5. Producer-Consumer Java Program Using ArrayBlockingQueue
  6. How to Convert String to Date in Java
  7. Operator Overloading in Python
  8. Data Access in Spring Framework

Monday, 17 June 2019

Java while Loop With Examples

In Java programming language there are three types of loops- while loop, do while loop and for loop. In this post we’ll learn about while loop in Java along with usage examples.

while loop in Java

While loop repeatedly executes a statement or a block of statements while its condition is true.

Syntax of the while loop in Java is as follows-

 
while (condition) {
    // loop body
}

Here condition is a boolean expression that evaluates to either true or false.

while loop body is repeatedly executed as long as the conditional expression is true. When condition evaluates to false, control comes out of the loop. The curly braces are not necessary if loop body consists of a single statement.

Java while loop execution flow

while loop in Java

Java while loop examples

1- Using while loop to print numbers 1..5.

 
public class WhileLoopDemo {
    public static void main(String[] args) {
        int i = 1;
        while(i <= 5){
            System.out.println(i);
            i++;
        }
    }
}

Output

1
2
3
4
5

The condition (i <= 5) is evaluated first in the while loop if it’s true loop body is executed and in each iteration condition is evaluated to verify whether it is true or false.

In the loop body value of i is incremented by 1 in each iteration so that the condition eventually evaluates to false when i is greater than 5.

2- Using while loop to print table of 7.

 
public class WhileLoopDemo {
    public static void main(String[] args) {
        int number = 7;
        int i = 1;
        while(i <= 10){
            System.out.println(number + " X " +i + " = " + (i*7));
            i++;
        }
    }
}

Output

7 X 1 = 7
7 X 2 = 14
7 X 3 = 21
7 X 4 = 28
7 X 5 = 35
7 X 6 = 42
7 X 7 = 49
7 X 8 = 56
7 X 9 = 63
7 X 10 = 70

Java while loop with no loop body

You can have a while loop with no loop body. Consider the following example where while loop is repeated as long as i is note greater than 10.

 
public class WhileLoopDemo {
    public static void main(String[] args) {
        int i = 1;
        while(!(++i > 10));
        System.out.println("Value of i- " + i);
    }
}

Output

Value of i- 11

Infinite while loop

Since while loop is evaluated as long as the condition remains true so you can have an infinite while loop by using condition as true. Consider the following example which has to be terminated manually to come out of an infinite while loop.

 
public class WhileLoopDemo {
    public static void main(String[] args) {
     while(true){
      System.out.println("This is an infinite while loop");
     }
    }
}

Usually you use such an infinite while loop with a break statement along with a condition to break out of loop.

 
public class WhileLoopDemo {
    public static void main(String[] args) {
        int i = 1;
        while(true){
            i++;
            // condition to break out of loop
            if(i > 20)
                break;
        }
        System.out.println("Value of i- " + i);
    }
}

Output

Value of i- 21

Same program can also be written using a boolean flag to control the while loop.

 
public class WhileLoopDemo {
    public static void main(String[] args) {
        boolean flag = true;
        int i = 1;
        while(flag){
            i++;
            // condition to turn flag to false
            if(i > 20)
                flag = false;
        }
        System.out.println("Value of i- " + i);
    }
}

Output

Value of i- 21

That's all for this topic Java while Loop With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. Ternary Operator in Java
  2. Difference Between equals() Method And equality Operator == in Java
  3. Why no Multiple Inheritance in Java
  4. Package in Java
  5. Class in Java

You may also like -

  1. this Keyword in Java With Examples
  2. Java Exception Handling Tutorial
  3. StringBuffer Class in Java
  4. How HashMap Internally Works in Java
  5. Race Condition in Java Multi-Threading
  6. Factorial Program in Java
  7. Magic Methods in Python With Examples
  8. Spring JavaConfig Example Program

Friday, 14 June 2019

Java for Loop With Examples

In Java programming language there are three types of loops- for loop, while loop and do while loop. In this post we’ll learn about for loop in Java along with usage examples.

for loop in Java

In Java there are two forms of for loop.

  1. Traditional for loop– Available from the beginning.
  2. Enhanced for loop (for-each loop)- Added in Java 5.

Syntax for traditional for loop in Java

Syntax of the traditional for loop is as follows-

 
for(initialization; condition; increment\decrement) {
    // loop body
}

Statements that are part of loop body are enclosed with in curly braces. If there is only one statement with in a for loop then curly braces are optional.

It is not mandatory to do initialization and increment\decrement with in the for loop statement.

There are three parts in a for loop-

  1. Initialization– Initialization step is used to set the initial value of the variable which controls the for loop. Initialization is the first step in for loop execution and it is executed only once. The initilized variable is later incremented or decremented in the increment\decrement step of the loop.
  2. Condition– Condition is a boolean expression that is evaluated in each iteration. If condition is true then the loop body is executed, if condition is false then the loop terminates.
  3. Increment\decrement– The variable that controls the loop is incremented or decremented in this step.

Java for loop execution flow

Flow of the for loop can be explained using the following flow chart.

Java for loop

Java for loop examples

1- Using for loop to print numbers 1..5.

 
public class ForLoopDemo {
    public static void main(String[] args) {
        for(int i = 1; i <=5; i++){
            System.out.println(i);
        }
    }
}

Output

1
2
3
4
5
  1. In the initialization part of for loop statement, variable i is declared and initialized to 1.
  2. Condition part (i <= 5) is evaluated in each iteration, returning true if value of i is less than or equal to 5 and returning false when value of i becomes greater than 5 and the condition evaluates to false which terminates the for loop.
  3. Third part of the for loop increments the variable i.

2- Using for loop to print table of 7.

 
public class ForLoopDemo {
    public static void main(String[] args) {
        int number = 7;
        for(int i = 1; i <=10; i++){
            System.out.println(number + " X " +i + " = " + (i*7));
        }
    }
}

Output

7 X 1 = 7
7 X 2 = 14
7 X 3 = 21
7 X 4 = 28
7 X 5 = 35
7 X 6 = 42
7 X 7 = 49
7 X 8 = 56
7 X 9 = 63
7 X 10 = 70

3- Using for loop to print numbers in reverse order 5..1

 
public class ForLoopDemo {
    public static void main(String[] args) {
        for(int i = 5; i > 0; i--){
            System.out.println(i);
        }
    }
}

Output

5
4
3
2
1

In this example value of i is decremented in the increment\decrement part.

4- As already stated it is not mandatory to do initialization and increment\decrement as part of for loop statement. Previous example of printing number in reverse order can also be written as follows.

 
public class ForLoopDemo {
    public static void main(String[] args) {
        int i = 5;
        for(; i > 0;){
            System.out.println(i);
             i--;
        }
    }
}

Output

5
4
3
2
1

As you can see in this example initialization and increment/decrement part is done outside the for loop statement but you still need semicolons with in the for loop statement.

Java for-each loop (Enhanced for loop)

for-each loop or enhanced for loop is available Java 5 onward. This version of for loop is used to iterate a collection of objects like an array, list or set sequentially.

Java for-each loop syntax

 
for(type var : collection){
    //loop body
}
  • type specifies the type of the elements in the collection.
  • var is assigned the next element from the collection in each iteration.
  • collection is the Collection that is iterated.

Java for-each loop examples

1- Using for-each loop to iterate an ArrayList and displaying its elements.

 
public class ForLoopDemo {
    public static void main(String[] args) {
        List<String> avengers = new ArrayList<String>();
        avengers.add("Iron Man");
        avengers.add("Captain America");
        avengers.add("Hulk");
        avengers.add("Thor");
        avengers.add("Black Widow");
        avengers.add("Hawkeye");        
        for(String avenger : avengers){
            System.out.println(avenger);
        }
    }
}

Output

Iron Man
Captain America
Hulk
Thor
Black Widow
Hawkeye

2- Iterating an array using for-each loop and finding the max element in the array.

 
public class ForLoopDemo {
    public static void main(String[] args) {
        int arr[] = {6, 7, 34, -23, 45, 48, 9, 4, 10, 21};
        int max = 0;
        for(int number: arr) {
            if(number > max)
                max = number;
        }
        System.out.println("Max elements in the array- " + max);        
    }
}

Output

Max elements in the array- 48

Nested for loop in Java

You can have a for loop (or any other loop) inside another for loop, such loops are known as nested loops.

In a nested for loop, for each iteration of the outer for loop, inner for loop is iterated until the condition in the inner for loop evaluates to false.

Java Nested for loop example

If you want to display the following pyramid pattern in Java.

     1
    1 2
   1 2 3
  1 2 3 4
 1 2 3 4 5
1 2 3 4 5 6
 
import java.util.Scanner;
public class PatternsDemo {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter number of rows in the pyramid (1-9) - "); 
        int noOfRows = sc.nextInt();
        // calling method
        printPattern(noOfRows);
    }
    
    private static void printPattern(int num){
        // Outer for loop
        for(int i = 1; i <= num; i++){
            // this nested loop prints the spaces after which the
            // number has to be printed
            for(int j = 0; j < num - i; j++){
                System.out.print(" ");
            }
            // this loop prints the number
            for(int k = 1; k < i; k++){
                System.out.print(k + " ");
            }
            System.out.println();
        }            
    }
}

That's all for this topic Java for Loop With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. Switch-Case Statement in Java
  2. Conditional Operators in Java
  3. Object Creation Using new Operator in Java
  4. Java Pass by Value or Pass by Reference
  5. Core Java Basics Interview Questions

You may also like -

  1. Ternary Operator in Java
  2. Constructor in Java
  3. How to Format Date in Java Using SimpleDateFormat
  4. Linked List Implementation Java Program
  5. How to Loop Through HashSet in Java
  6. Creating a Thread in Java
  7. Python Conditional Statement - if, elif, else Statements
  8. Dependency Injection in Spring Framework

Wednesday, 12 June 2019

Python while Loop With Examples

In Python programming language there are two loops for..in loop and while loop. In this tutorial you’ll learn about while loop in Python which is used to repeatedly execute the loop body while the given condition evaluates to true.


Syntax of Python while loop

Full syntax of while loop in Python is as given below.

while condition:
 while_suite
else:
 else_suite

Here condition is a boolean expression that evaluates to either true or false. Initially condition is checked and if it evaluates to true the statements making up the while_suite are executed. Control then goes back to the start of the loop and condition is checked again if it evaluates to true the statements making up the while_suite are executed again. Same process is followed repeatedly while the condition evaluates to true. When the condition evaluates to false control comes out of the while loop.

The else statement in the while loop is optional. The else_suite is executed if the while loop terminates normally and if the optional else statement is present.

while loop flow

Python while Loop

Python while loop examples

1- To display numbers 1..10 using while loop in Python.

i = 1
while i <= 10:
    print(i)
    i+=1

print('Out of while loop')

Output

1
2
3
4
5
6
7
8
9
10
Out of while loop

In the example i <= 10 is the condition for the while loop. While this condition is true loop body which are the following two indented statements are executed.

    print(i)
    i+=1

When value of i becomes greater than 10 control comes out of while loop.

2- Displaying table of 5 using while loop in Python.

i = 1
while i <= 10:
    print(5, 'X', i, '=', (i*5))
    i+=1

Output

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

Python while loop with else statement

In Python, while loop has an optional else statement too. If the while loop runs till completion and terminates the else-suite is executed.

If while loop doesn’t run completely because of any of the following reason, else statement is not executed.

  • while loop is terminated abruptly due to a break statement
  • while loop is terminated abruptly due to a return statement
  • if an exception is raised

In the following example else_suite is executed as the while loop completes normally.

i = 1
while i <= 10:
    print(i)
    i+=1
else:
    print('in else block')

Output

1
2
3
4
5
6
7
8
9
10
in else block

Now, if we break the while loop abruptly, else-suite won’t be executed.

i = 1
while i <= 10:
    print(i)
    i+=1
    if i > 5:
        break
else:
    print('in else block')

Output

1
2
3
4
5

Nested while loop in Python

while loop can be nested which means you can have one while loop inside another (or even for loop inside while loop). In the nested loops for each iteration of the outer while loop, inner while loop is iterated while the condition of inner while loop evaluates to true.

Python Nested while loop example

Suppose you want to print inverted right triangle using asterisk (*) symbol, following example shows one way to do it using nested while loops in Python.

rows = 6
while rows > 0:
    j = 1
    # inner while
    while j <= rows:
        # end='' to ensure print remains on the same line
        print('* ', end='')
        j += 1
    # for outer while
    rows = rows - 1
    print()

Output

* * * * * * 
* * * * * 
* * * * 
* * * 
* * 
* 

That's all for this topic Python while Loop With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Python Conditional Statement - if, elif, else Statements
  2. Python First Program - Hello World
  3. Polymorphism in Python
  4. self in Python
  5. Local, Nonlocal And Global Variables in Python

You may also like -

  1. Constructor Overloading in Java
  2. Private Methods in Java Interface
  3. Converting String to double - Java Program
  4. Matrix Multiplication Java Program
  5. How to Sort an ArrayList in Descending Order in Java
  6. HashMap Vs LinkedHashMap Vs TreeMap in Java
  7. Autowiring in Spring Using XML Configuration
  8. Sending Email Using Spring Framework Example