Thanks to visit codestin.com
Credit goes to www.tutorialsteacher.com

Tutorialsteacher

Follow Us

Articles
  • C#
  • C# OOP
  • ASP.NET Core
  • ASP.NET MVC
  • LINQ
  • Inversion of Control (IoC)
  • Web API
  • JavaScript
  • TypeScript
  • jQuery
  • Angular 11
  • Node.js
  • D3.js
  • Sass
  • Python
  • Go lang
  • HTTPS (SSL)
  • Regex
  • SQL
  • SQL Server
  • PostgreSQL
  • MongoDB
  • Python - Get Started
  • What is Python?
  • Where to use Python?
  • Python Version History
  • Install Python
  • Python - Shell/REPL
  • Python IDLE
  • Python Editors
  • Python Syntax
  • Python Keywords
  • Python Variables
  • Python Data Types
  • Number
  • String
  • List
  • Tuple
  • Set
  • Dictionary
  • Python Operators
  • Python Conditions - if, elif
  • Python While Loop
  • Python For Loop
  • User Defined Functions
  • Lambda Functions
  • Variable Scope
  • Python Modules
  • Module Attributes
  • Python Packages
  • Python PIP
  • __main__, __name__
  • Python Built-in Modules
  • OS Module
  • Sys Module
  • Math Module
  • Statistics Module
  • Collections Module
  • Random Module
  • Python Generator Function
  • Python List Comprehension
  • Python Recursion
  • Python Built-in Error Types
  • Python Exception Handling
  • Python Assert Statement
  • Define Class in Python
  • Inheritance in Python
  • Python Access Modifiers
  • Python Decorators
  • @property Decorator
  • @classmethod Decorator
  • @staticmethod Decorator
  • Python Dunder Methods
  • CRUD Operations in Python
  • Python Read, Write Files
  • Regex in Python
  • Create GUI using Tkinter
Entity Framework Extensions - Boost EF Core 9
  Bulk Insert
  Bulk Delete
  Bulk Update
  Bulk Merge

Python - While Loop

Python uses the while and for keywords to constitute a conditional loop, by which repeated execution of a block of statements is done until the specified boolean expression is true.

The following is the while loop syntax.

Syntax:
while [boolean expression]: statement1 statement2 ... statementN

Python keyword while has a conditional expression followed by the : symbol to start a block with an increased indent. This block has statements to be executed repeatedly. Such a block is usually referred to as the body of the loop. The body will keep executing till the condition evaluates to True. If and when it turns out to be False, the program will exit the loop. The following example demonstrates a while loop.

Example: while loop
num =0

while num < 5:
    num = num + 1
    print('num = ', num)
Try it
Output
num = 1 num = 2 num = 3 num = 4 num = 5

Here the repetitive block after the while statement involves incrementing the value of an integer variable and printing it. Before the block begins, the variable num is initialized to 0. Till it is less than 5, num is incremented by 1 and printed to display the sequence of numbers, as above.

All the statements in the body of the loop must start with the same indentation, otherwise it will raise a IndentationError.

Example: Invalid Indentation
num =0
while num < 5:
    num = num + 1
      print('num = ', num)
Try it
Output
  print('num = ', num) ^ IndentationError: unexpected indent

Exit from the While Loop

Use the break keyword to exit the while loop at some condition. Use the if condition to determine when to exit from the while loop, as shown below.

Example: Breaking while loop
num = 0

while num < 5:
    num += 1   # num += 1 is same as num = num + 1
    print('num = ', num)
    if num == 3: # condition before exiting a loop
        break
Try it
Output
num = 1 num = 2 num = 3

Continue Next Iteration

Use the continue keyword to start the next iteration and skip the statements after the continue statement on some conditions, as shown below.

Example: Continue in while loop
num = 0

while num < 5:
	num += 1   # num += 1 is same as num = num + 1
	if num > 3: # condition before exiting a loop
		continue
	print('num = ', num)
Try it
Output
num = 1 num = 2 num = 3

While Loop with else Block

The else block can follow the while loop. The else block will be executed when the boolean expression of the while loop evaluates to False.

Use the continue keyword to start the next iteration and skip the statements after the continue statement on some conditions, as shown below.

Example: while loop with else block
num = 0

while num &lt; 3:
	num += 1   # num += 1 is same as num = num + 1
	print('num = ', num)
else:
    print('else block executed')
Output
num = 1 num = 2 num = 3 else block executed

The following Python program successively takes a number as input from the user and calculates the average, as long as the user enters a positive number. Here, the repetitive block (the body of the loop) asks the user to input a number, adds it cumulatively and keeps the count if it is non-negative.

Example: while loop
num=0
count=0
sum=0

while num>=0:
    num = int(input('enter any number .. -1 to exit: '))
    if num &gt;= 0:
        count = count + 1 # this counts number of inputs
        sum = sum + num # this adds input number cumulatively.
avg = sum/count
print('Total numbers: ', count, ', Average: ', avg)
Try it

When a negative number is provided by the user, the loop terminates and displays the average of the numbers provided so far. A sample run of the above code is below:

Output
enter any number .. -1 to exit: 10 enter any number .. -1 to exit: 20 enter any number .. -1 to exit: 30 enter any number .. -1 to exit: -1 Total numbers: 3, Average: 20.0
TUTORIALSTEACHER.COM

TutorialsTeacher.com is your authoritative source for comprehensive technologies tutorials, tailored to guide you through mastering various web and other technologies through a step-by-step approach.

Our content helps you to learn technologies easily and quickly for learners of all levels. By accessing this platform, you acknowledge that you have reviewed and consented to abide by our Terms of Use and Privacy Policy, designed to safeguard your experience and privacy rights.

[email protected]

ABOUT USTERMS OF USEPRIVACY POLICY
copywrite-symbol

2024 TutorialsTeacher.com. (v 1.2) All Rights Reserved.