Chapter 10 While Loop
description
Transcript of Chapter 10 While Loop
Chapter 10 While Loop
Bernard Chen 2007
Loop In this chapter, we see two main looping
constructs --- statements that repeat an action over and over
The for statement, is designed for stepping through the items in a sequence object and running a block of code for each item
The while loop, provides a way to code general loop
While Loop
It repeatedly executes a block of indented statements, as long as a test at the top keeps evaluating to a true statement.
The body never runs if the test is false to begin with
While Loop General Format
The while statement consists of a header line with a test expression, a body of one or more indented statement
while <test>: <statement>
While Loop Examples
Print from 0 to 10
>>> count=0>>> while count<=10:
print countcount=count+1
While Loop Examples This example keeps slicing off the
first character of a string, until the string is empty and hence false:
>>> x=‘Python’>>> while x:
print xx=x[1:]
While Loop Examples
Infinite loop example (always keep the test true)
>>> while 1:… print “Type Ctrl-C to
stop me!!”
While Loop Examples So how to print
*********************by using while loop?
While Loop Examples
>>> num=6>>> while num>0:
print ‘*’ * numnum = num-1
While Loop Examples Then, how to print*********************by using while loop?
While Loop Examples
>>> num=0>>> while num<=6:
print ‘*’ * numnum = num+1
While Loop Examples How to simulate “range” function in for loop?
>>>for i in range(0,10,2):print i
>>>i=0>>>while i<10:
print ii=i+2