TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: Python While Loop Tutorial
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile Concepts Simplified
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Python BasicPython Tutorials

Python While Loop Tutorial

Last updated: Oct 30, 2023 7:21 am
By Meenakshi Agarwal
Share
7 Min Read
Python while loop
Python while loop
SHARE

This tutorial explains Python while loop, and its syntax and provides examples of how to use it in different situations.

Contents
SyntaxWhile Loop FlowchartPython While Loop ExampleElse Clause ExampleConclusion

Unlike the for loop which runs up to a certain no. of iterations, the while loop relies on a condition to complete the execution.

To go back to ☛ Python Tutorials

While coding, there could be scenarios where you don’t know the cut-off point of a loop. For example, a program asks for the user to input an indefinite number of times until he presses the ESC key or reads a file until it finds a specific token.

What is a Python While Loop?

A while loop is a control flow structure that repeatedly executes a block of code indefinite no. of times until the given condition becomes false. For example, say, you want to count the occurrence of odd numbers in a range. Some technical references call it a pre-test loop as it checks the condition before every iteration.

Syntax

while some condition (or expression) :
    a block of code

The syntax is clearly stating that Python first evaluates the condition.

If the check fails, then the control won’t enter into the loop instead will get transferred to the next statement. Whereas if the condition passes, then the statements inside the loop shall execute.

This cycle would repeat itself until the while condition fails or returns false. When such a situation occurs, the loop would break and pass control to the next executable statement.

While Loop Flowchart

Apart from the below, be aware of this insightful Loop flowchart, which shows the positive and negative aspects of the loop.

Python while loop workflow

Python While Loop Example

This example exhibits how to count the occurrences of odd numbers in a range entered by the user excluding the endpoints.

#custom debug print function
def dbgprint(x):
    if debug == True:
        print(x)

#ask user to enter the range values
debug = False
r1 = int(input("Enter the starting range value?"))
r2 = int(input("Enter the ending range value?"))
         
dbgprint("Range: %d - %d" % (r1, r2))

num = r1 + 1
count = 0

while num < r2:
    dbgprint("num: %d" % (num))
    res = num % 2
    dbgprint("res: %d" % (res))
    if (num % 2) > 0:
        count += 1
    num += 1

print("Odd count: %d" % (count))

Once you finish up the execution of the above code, you should see the following output.

Enter the starting range value? 1
Enter the ending range value? 100
Odd count: 49

In this program, we are using the following four variables.

1. r1 – starting range value

2. r2 – ending range value

3. num – the variable we are testing for an odd number

4. count – the counter variable, incremented upon every positive test

We’ve initialized the “num” variable with the starting offset plus one and the counter variable with a zero. The loop is testing if “num” remains less than the ending offset value, it’ll break otherwise.

In each iteration, the code block inside the loop calculates the remainder of the “num” variable. A non-zero result would mean the number is odd and the “count” var would get incremented by one.

The last statement in the while loop is stepping up the value of “num” by one, and it goes through for re-execution. The loop shall stop only after the value of the “num” is equal to or more than the ending range offset, i.e., “r2”.

Else Clause with Python While Loop

In Python, we can add an optional else clause after the end of the “while” loop.

The code inside the else clause would always run but after the while loop finishes execution. The one situation when it won’t run is if the loop exits after a “break” statement.

Using the else clause would make sense when you wish to execute a set of instructions after the while loop ends, i.e., without using a break statement.

Let’s now see an example to demonstrate the use of “else” in the Python while loop.

Else Clause Example

def while_else_demo():

    count = 0
    while count < 5 :
        num = int(input("Enter number between 0-100?"))
        if (num < 0) or (num > 100):
            print("Aborted while: You've entered an invalid number.")
            break
        count += 1
    else:
        print("While loop ended gracefully.")

while_else_demo()

The above program runs the while loop until the count is less than 5.

It takes a number between 0-100 as input. If you enter a valid number 5 times, then the while loop runs successfully, and the message from the else clause will be displayed.

If you enter an invalid number, then the loop will get aborted without executing the code in the else.

Iteration#1 While loop finishes with success and the “else” clause executes.

Enter number between 0-100?1
Enter number between 0-100?2
Enter number between 0-100?3
Enter number between 0-100?4
Enter number between 0-100?5
While loop ended gracefully.

Iteration#2 While loop aborts and “else” clause won’t execute.

Enter number between 0-100?1
Enter number between 0-100?101
Aborted while: You've entered an invalid number.

Conclusion

In this tutorial, we covered “Python while Loop” and provided examples to use it in real Python programs. If you have any questions about this topic, please do write to us.

Also, if you found it useful, then do share it with your colleagues. Also, connect to our social media accounts to receive all future updates in time.

Recommended Post:

  • For Loop in Python

You Might Also Like

How to Connect to PostgreSQL in Python

Generate Random IP Address (IPv4/IPv6) in Python

Python Remove Elements from a List

How to Use Extent Report in Python

10 Python Tricky Coding Exercises

Meenakshi Agarwal Avatar
By Meenakshi Agarwal
Follow:
Hi, I'm Meenakshi Agarwal. I have a Bachelor's degree in Computer Science and a Master's degree in Computer Applications. After spending over a decade in large MNCs, I gained extensive experience in programming, coding, software development, testing, and automation. Now, I share my knowledge through tutorials, quizzes, and interview questions on Python, Java, Selenium, SQL, and C# on my blog, TechBeamers.com.
Previous Article Python for loop, syntax and examples Python For Loop Tutorial
Next Article Use Python if else statement for decision making Python If Else Explained

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x