Computer History Notes - Herong's Tutorial Notes - v3.14, by Herong Yang
Python "while" Statement for Execution Loop
This section provides a quick introduction of 'while' statement, which executes a block of sub-statements repeatedly while the given condition is valid.
One unique feature of Python is that it uses indentation to define sub-statement blocks instead of curly brackets.
For example, a "while" statement is a compound statement that executes a block of sub-statements repeatedly while the given condition is valid.
The "while" statement syntax in Python is shown below:
while condition: sub-statement sub-statement ... else: sub-statement sub-statement ...
Here is a Python sample code, while_test.py, that shows you how to use "while" statements.
# while_test.py
#- Copyright 2011 (c) HerongYang.com. All Rights Reserved.
upperLimit = 20
i = 3
while i<upperLimit:
isPrime = True
j = 2
while j<=i//2:
isPrime = i%j > 0
if not isPrime:
break
j = j + 1
if isPrime:
print(" "+str(i)+" is a prime number.")
i = i + 1
print("Reached the upper limit "+str(upperLimit))
If you run this sample code, you should get:
herong> python while_test.py 3 is a prime number. 5 is a prime number. 7 is a prime number. 11 is a prime number. 13 is a prime number. 17 is a prime number. 19 is a prime number. Reached the upper limit 20
Notice that we have a "while" statement nested inside another "while" statement. The "break" statement inside the inner "while" statement only breaks the immediate containing "while" statement, not the outer "while" statement.
Table of Contents
2009 - Bitcoin Cryptocurrency Invented by Satoshi Nakamoto
2002 - .NET Framework Developed by Microsoft
1995 - PHP: Hypertext Preprocessor Created by Rasmus Lerdorf
1995 - Java Language Developed by Sun Microsystems
►1991 - Python Language Designed by Guido van Rossum
Using Python Shell at python.org
►Python "while" Statement for Execution Loop
Python pandas.DataFrame - The Table Class
1991 - WWW (World Wide Web) Developed by Tim Berners-Lee
1991 - Gopher Protocol Created by a University of Minnesota Team
1984 - X Window System Developed a MIT Team
1984 - Macintosh Developed by Apple Inc.
1983 - "Sendmail" Mail Transfer Agent Developed by Eric Allman
1979 - The Tcsh (TENEX C Shell) Developed by Ken Greer
1978 - Bash (Bourne-Again Shell) Developed by Brian Fox
1978 - The C Shell Developed by Bill Joy
1977 - The Bourne Shell Developed by Stephen Bourne
1977 - Apple II Designed by Steve Jobs and Steve Wozniak
1976 - vi Text Editor Developed by Bill Joy
1974 - Internet by Vinton Cerf
1972 - C Language Developed by Dennis Ritchie
1971 - FTP Protocol Created by Abhay Bhushan
1970 - UNIX Operating System Developed by AT&T Bell Labs