Chapter 10 While Loop - PowerPoint PPT Presentation

1 / 12
About This Presentation
Title:

Chapter 10 While Loop

Description:

It repeatedly executes a block of indented statements, as long as a test at the ... a header line with a test expression, a body of one or more indented statement ... – PowerPoint PPT presentation

Number of Views:25
Avg rating:3.0/5.0
Slides: 13
Provided by: csg3
Category:
Tags: chapter | indented | loop

less

Transcript and Presenter's Notes

Title: Chapter 10 While Loop


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

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 lttestgt
  • ltstatementgt

5
While Loop Examples
  • Print from 0 to 10
  • gtgtgt count0
  • gtgtgt while countlt10
  • print count
  • countcount1

6
While Loop Examples
  • This example keeps slicing off the first
    character of a string, until the string is empty
    and hence false
  • gtgtgt xPython
  • gtgtgt while x
  • print x
  • xx1

7
While Loop Examples
  • Infinite loop example (always keep the test true)
  • gtgtgt 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
  • gtgtgt num6
  • gtgtgt while numgt0
  • print num
  • num num-1

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

11
While Loop Examples
  • gtgtgt num0
  • gtgtgt while numlt6
  • print num
  • num num1

12
While Loop Examples
  • How to simulate range function in for loop?
  • gtgtgtfor i in range(0,10,2)
  • print i
  • gtgtgti0
  • gtgtgtwhile ilt10
  • print i
  • ii2
Write a Comment
User Comments (0)
About PowerShow.com