Python Tutorial
What is Python ??
Python Get Started
Python Syntax
Python Variables and Types
Python Data Types
Python Operators
Python Input and Output
Python If ... Else
Python While Loops
Python For Loops
Python Strings
Python Functions
Python Lambda Function
Author Profile Altaf Shaikh
Altaf Shaikh

BE Engg | Python Dev | Content Writer | Founder of TeachMeBro | Blockchain Dev | Django

Python While Loops

January 17th 2020

Python While Loops
Python While Loops

Control Statements

Loops

In general, statements are executed sequentially − The first statement in a function is executed first, followed by the second, and so on. There may be a situation when you need to execute a block of code several number of times. A loop statement allows us to execute a statement or group of statements multiple times.

Python programming language provides the following types of loops to handle looping requirements.

  • while loop
  • for loop
  • nested loops

Loop Control Statements

The Loop control statements change the execution from its normal sequence. When the execution leaves a scope, all automatic objects that were created in that scope are destroyed.

Python supports the following control statements.

  • break: Terminates the loop statement and transfers execution to the statement immediately following the loop.
  • continue: Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.
  • pass: Used when a statement is required syntactically but you do not want any command or code to execute.

iterable

It is a sequence of values like stringlisttupledictionaryrange()

Syntax:

for item in iterable:
    # do something on item

Syntax:

while expression:
    # iterates till the condition is true

The while Loop

Repeats a statement or group of statements while a given condition is TRUE. It tests the condition before executing the loop body.

Syntax:

while expression:
    # iterates till the condition is true

Example:

The break Statement

With the break statement we can stop the loop even if the while condition is true:

Example:

The continue Statement

With the continue statement we can stop the current iteration, and continue with the next:

Example: