while expression: statement(s)
In Python, all the statements indented by the same number of character spaces after a programming construct are considered to be part of a single block of code. Python uses indentation as its method of grouping statements.
#!/usr/bin/python count = 0 while (count < 9): print 'The count is:', count count = count + 1 print "Good bye!"
The Infinite Loop
#!/usr/bin/python var = 1 while var == 1 : # This constructs an infinite loop num = raw_input("Enter a number :") print "You entered: ", num print "Good bye!"
Using else Statement with Loops
Python supports to have an else statement associated with a loop statement.
- If the else statement is used with a for loop, the else statement is executed when the loop has exhausted iterating the list.
- If the else statement is used with a while loop, the else statement is executed when the condition becomes false.
#!/usr/bin/python count = 0 while count < 5: print count, " is less than 5" count = count + 1 else: print count, " is not less than 5"
Single Statement Suites
Similar to the if statement syntax, if your while clause consists only of a single statement, it may be placed on the same line as the while header.
Here are the syntax and example of a one-line while clause −
#!/usr/bin/python flag = 1 while (flag): print 'Given flag is really true!' print "Good bye!"
- Python while Loop Statements: http://www.tutorialspoint.com/python/python_while_loop.htm