Python While loop

Python Programming Training Certification

Flexible Hours

100 Assignments

Instructor Led online Training

50 LMS Access

24X7 Support

100% Skill Level

Enquire Now

4.9 out of 1000+ Ratings
Best Python Institute for Learning Python Course & Training, Live Project Training in Python with Django, Data Science and AI, Interview Assistance, Expert Coaching Trainers. Python Certification & Interview Assistance! Get free demo now!

Course Overview

Python is one of the world’s top programming languages used today and Python training has become the most popular training across individuals. Training Basket’s Python Training & Certification course covers basic and advanced Python concepts and how to apply them in real-world applications.Python is a flexible and powerful open-source language that is easy to learn and consists of powerful libraries for data analysis and manipulation. Our Python training course content is curated by experts as per the standard Industry curriculum. The curriculum, coding challenges and real-life problems cover data operations in Python, strings, conditional statements, error handling, shell scripting, web scraping and the commonly used Python web framework Django. Take this Python training and certification course and become job-ready now.

Python While loop

The Python while loop allows a part of the code to be executed until the given condition returns false. It is also known as a pre-tested loop.

It can be viewed as a repeating if statement. When we don’t know the number of iterations then the while loop is most effective to use.

The syntax is given below.

  • while expression:
    statements

Here, the statements can be a single statement or a group of statements. The expression should be any valid Python expression resulting in true or false. The true is any non-zero value and false is 0.

While loop Flowchart

Loop Control Statements

We can change the normal sequence of while loop’s execution using the loop control statement. When the while loop’s execution is completed, all automatic objects defined in that scope are demolished. Python offers the following control statement to use within the while loop.

Continue Statement – When the continue statement is encountered, the control transfer to the beginning of the loop. Let’s understand the following example.

Example:

  • # prints all letters except ‘a’ and ‘t’
    i = 0
    str1 = ‘javatpoint’

    while i < len(str1):
    if str1[i] == ‘a’ or str1[i] == ‘t’:
    i += 1
    continue
    print(‘Current Letter :’, a[i])
    i += 1

Output:

  • Current Letter : j
    Current Letter : v
    Current Letter : p
    Current Letter : o
    Current Letter : i
    Current Letter : n

Break Statement – When the break statement is encountered, it brings control out of the loop.

Example

  • # The control transfer is transfered
    # when break statement soon it sees t
    i = 0
    str1 = ‘javatpoint’

    while i < len(str1):
    if str1[i] == ‘t’:
    i += 1
    break
    print(‘Current Letter :’, str1[i])

i += 1

Output:

  • Current Letter : j
    Current Letter : a
    Current Letter : v
    Current Letter : a

Pass Statement – The pass statement is used to declare the empty loop. It is also used to define empty class, function, and control statement. Let’s understand the following example.

Example

  • # An empty loop
    str1 = ‘javatpoint’
    i = 0

    while i < len(str1):
    i += 1
    pass
    print(‘Value of i :’, i)

Output:

  • Value of i : 10

Example-1: Program to print 1 to 10 using while loop

  • i=1
    #The while loop will iterate until condition becomes false.
    While(i<=10):
    print(i)
    i=i+1

Output:

  • 1
    2
    3
    4
    5
    6
    7
    8
    9
    10

Example -2: Program to print table of given numbers.

  • i=1
    number=0
    b=9
    number = int(input(“Enter the number:”))
    while i<=10:
    print(“%d X %d = %d \n”%(number,i,number*i))
    i = i+1

Output:

  • Enter the number:10
    10 X 1 = 10

    10 X 2 = 20

    10 X 3 = 30

    10 X 4 = 40

    10 X 5 = 50

    10 X 6 = 60

    10 X 7 = 70

    10 X 8 = 80

    10 X 9 = 90

    10 X 10 = 100

Infinite while loop

If the condition is given in the while loop never becomes false, then the while loop will never terminate, and it turns into the infinite while loop.

Any non-zero value in the while loop indicates an always-true condition, whereas zero indicates the always-false condition. This type of approach is useful if we want our program to run continuously in the loop without any disturbance.

Example

  • while (1):
    print(“Hi! we are inside the infinite while loop”)

Output:

  • Hi! we are inside the infinite while loop
    Hi! we are inside the infinite while loop

Example 2

  • var = 1
    while(var != 2):
    i = int(input(“Enter the number:”))
    print(“Entered value is %d”%(i))

Output:

  • Enter the number:10
    Entered value is 10
    Enter the number:10
    Entered value is 10
    Enter the number:10
    Entered value is 10
    Infinite time

Using else with while loop

Python allows us to use the else statement with the while loop also. The else block is executed when the condition given in the while statement becomes false. Like for loop, if the while loop is broken using break statement, then the else block will not be executed, and the statement present after else block will be executed. The else statement is optional to use with the while loop. Consider the following example.

Example 1

  • i=1
    while(i<=5):
    print(i)
    i=i+1
    else:
    print(“The while loop exhausted”)

Example 2

  • i=1
    while(i<=5):
    print(i)
    i=i+1
    if(i==3):
    break
    else:
    print(“The while loop exhausted”)

Output:

  • 1
    2

In the above code, when the break statement encountered, then while loop stopped its execution and skipped the else statement.

Example-3 Program to print Fibonacci numbers to given limit

  • terms = int(input(“Enter the terms “))
    # first two intial terms
    a = 0
    b = 1
    count = 0

    # check if the number of terms is Zero or negative
    if (terms <= 0):
    print(“Please enter a valid integer”)
    elif (terms == 1):
    print(“Fibonacci sequence upto”,limit,”:”)
    print(a)
    else:
    print(“Fibonacci sequence:”)
    while (count < terms) :
    print(a, end = ‘ ‘)
    c = a + b
    # updateing values
    a = b
    b = c

    count += 1

Output:

  • Enter the terms 10
    Fibonacci sequence:
    0 1 1 2 3 5 8 13 21 34

Recently Trained Students

Jessica Biel

– Infosys

My instructor had sound Knowledge and used to puts a lot of effort that made the course as simple and easy as possible. I was aiming for with the help of the ZebLearn Online training imparted to me by this organization.

Richard Harris

– ITC

I got my training from Zeblearn in the Python Certification Training, I would like to say that say he is one of the best trainers. He has not even trained me but also motivated me to explore more and the way he executed the project, in the end, was mind-blowing.


Candidate’s Journey During Our Training Program

Card image cap

Expert’s Advice & Selection of Module

Choosing the right type of module for the training is half the battle & Our Team of experts will help & guide you.

Card image cap

Get Trained

Get Trained & Learn End to End Implementation from our Expert Trainer who are working on the same domain.

Card image cap

Work on Projects

We Do make our student’s work on multiple case studies , scenario based tasks & projects in order to provide real-time exposure to them.

Card image cap

Placements

We have a dedicated placement cell in order to provide placement assistance & relevant interviews to our candididates till selection

Placement Partner

×

Leave your details

×

Download Course Content