Repetition Structures - GramercyDatadata items. Statement(s) execute once for each item in the...

39
Repetition Structures cause statement(s) to execute repeatedly.

Transcript of Repetition Structures - GramercyDatadata items. Statement(s) execute once for each item in the...

Repetition Structures

cause statement(s) to execute repeatedly.

Agenda1. The while loop - a condition-controlled loop2. The for loop - a count-controlled loop

3. Infinite loops

4. The range() function is often used with for loops.

5. The Augmented Assignment Operators: += -= *= /= %=

The while loop is a condition-controlled loop

WHILE a condition is true,

execute conditional code.

The while loop exampleThis condition is tested.

If the condition is true, these statements are executed, and then the loop starts over.

Program output

AssignmentCould you please re-write the while loop, so that the count is only printed if it’s even:

Solution 1

Solution 2

Solution 3 w augmented assignment operator ‘+=’

Infinite Loop

CTRL+C to interrupt.

Infinite Loop Example

What will this program print?

Program Output

The augmented assignment operator ‘%=’

The for loopThe for statement is designed to work with a sequence of data items. Statement(s) execute once for each item in the sequence.

The for loop

the for loop with strings

AssignmentCould you please write a for loop that displays odd numbers 1 through 9.

Solution

The range() function is often used with for loops.

range(stop) range(start, stop [, step])

Programming Exercise

Desired program output

Solution

Letting the user control

the number of loop iterations.

Desired program output.

User Input

Calculating a running total.

Program output.

Solution

Sentinels

When a program reads the sentinel value, the loop terminates.

Program output.Using a negative number to terminate a loop...

Program

Input Validation Loops

Writing an Input Validation Loop

Retail price = wholesale cost * 2.5

Wholesale cost cannot be negative.

Nested Loops

Nested loop example