Chapter 10 While Loop

12
Chapter 10 While Loop Bernard Chen 2007

description

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 - PowerPoint PPT Presentation

Transcript of Chapter 10 While Loop

Page 1: Chapter 10 While Loop

Chapter 10 While Loop

Bernard Chen 2007

Page 2: Chapter 10 While Loop

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

Page 3: Chapter 10 While 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

Page 4: Chapter 10 While Loop

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>

Page 5: Chapter 10 While Loop

While Loop Examples

Print from 0 to 10

>>> count=0>>> while count<=10:

print countcount=count+1

Page 6: Chapter 10 While Loop

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:]

Page 7: Chapter 10 While Loop

While Loop Examples

Infinite loop example (always keep the test true)

>>> while 1:… print “Type Ctrl-C to

stop me!!”

Page 8: Chapter 10 While Loop

While Loop Examples So how to print

*********************by using while loop?

Page 9: Chapter 10 While Loop

While Loop Examples

>>> num=6>>> while num>0:

print ‘*’ * numnum = num-1

Page 10: Chapter 10 While Loop

While Loop Examples Then, how to print*********************by using while loop?

Page 11: Chapter 10 While Loop

While Loop Examples

>>> num=0>>> while num<=6:

print ‘*’ * numnum = num+1

Page 12: Chapter 10 While Loop

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