1 / 12

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

aadi
Download Presentation

Chapter 10 While Loop

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

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

More Related