Download
chapter 10 while loop n.
Skip this Video
Loading SlideShow in 5 Seconds..
Chapter 10 While Loop PowerPoint Presentation
Download Presentation
Chapter 10 While Loop

Chapter 10 While Loop

125 Views Download Presentation
Download Presentation

Chapter 10 While Loop

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

  1. Chapter 10 While Loop Bernard Chen 2007

  2. 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

  3. While Loop • It repeatedly executes a block of indentedstatements, 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

  4. 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>

  5. While Loop Examples • Print from 0 to 10 >>> count=0 >>> while count<=10: print count count=count+1

  6. 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 x x=x[1:]

  7. While Loop Examples • Infinite loop example (always keep the test true) >>> while 1: … print “Type Ctrl-C to stop me!!”

  8. While Loop Examples • So how to print ****** ***** **** *** ** * by using while loop?

  9. While Loop Examples >>> num=6 >>> while num>0: print ‘*’ * num num = num-1

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

  11. While Loop Examples >>> num=0 >>> while num<=6: print ‘*’ * num num = num+1

  12. 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 i i=i+2