python while
By: Ashley J
Python while statement repeats execution of a statement or block of statements, until the loop condition is true. The syntax of the while statement:
while expression:
statement(s)
A while statement can also include an else clause, and break and
continue statements.
Here’s a typical while statement:
count = 0
while x > 0:
x //=
2
# truncating division
count += 1
print('The approximate log2 is', count)
First, Python evaluates expression, which is known as the loop condition. When the condition is false, the while statement ends. When the loop condition is true, the statement or statements that make up the loop body execute again and again. Once the loop body finishes executing, Python evaluates the loop condition again from the top to check whether another iteration should execute. This process continues until the loop condition is false, at which point the while statement ends.
The loop body should contain code that eventually makes the loop condition false; otherwise, the loop becomes an infinite loop (unless the body raises an exception or executes a break statement). A loop within a function’s body also ends if the loop body executes a return statement, since in this case the whole function ends.
Archived Comments
Comment on this tutorial
- Data Science
- Android
- AJAX
- ASP.net
- C
- C++
- C#
- Cocoa
- Cloud Computing
- HTML5
- Java
- Javascript
- JSF
- JSP
- J2ME
- Java Beans
- EJB
- JDBC
- Linux
- Mac OS X
- iPhone
- MySQL
- Office 365
- Perl
- PHP
- Python
- Ruby
- VB.net
- Hibernate
- Struts
- SAP
- Trends
- Tech Reviews
- WebServices
- XML
- Certification
- Interview
categories
Related Tutorials
How to install Jupyter in Ubuntu and make it accessible through Apache Reverse Proxy
Python Basics - Setting up your Python Development Environment
Schwartzian Transform in python
Multidimensional list (array) in python
Remove duplicates from a list in python
Convert number to string in python
Perl's chomp() equivalent for removing trailing newlines from strings in python