You are on page 1of 33

Loops

for: determinate loops


The number of repetitions are determined
in advance.
while: indeterminate loops
The condition to end a loop is only satis-
fied during the execution of the loop itself.
The while Loop
• while condition:
k=1
statement while k < 5:
– True : execute statement print( k )
– False : quit the loop k += 1
– Condition: <, >, >=, <=, !=, ==

For vs while for k in range(1, 5):


- for: repeat 횟수가 정해진 경우 print( k )
- while: repeat 횟수가 불확실한 경우
Example
• Display 1.0, 1.5, 2.0, 2.5, 3.0 using while loop. k=1
for k in range(1,6): while k ????:
print(k/2+0.5) print(?????)
k += ??
• Display odd integer between 1 and 5.
k=1
for k in range(1,6,2):
while k ????:
print(k)
print(??????)
k += ??
• Factorials! n !  1 2  3  ...  ( n  1)  n
• Compute 10!
fact = 1 fact = 1
for k in range(1,10): k=0
fact = k * fact while k ????:
print(fact) k += ??
fact = k * fact
print(fact)
while: indeterminate repetition
• A guessing game
– Generate integer
– Ask user for guess import random
matnum = random.randint(1,9)
– While guess is wrong
guess = eval(input( 'Your guess please(1~10):' ))
while guess != matnum:
• If guess is too high if guess > matnum:
– Tell her it is too high print( 'Too high' )
• Otherwise else:
– Tell her it is too low print( 'Too low' )
guess = eval(input( 'Your next guess please: '))
print( 'At last!' )
• Ask user for new guess

– Polite congratulations
– Stop
Excercise
• A guessing game
– Quit the while loop when the user input the number 11
– Otherwise never stop the game
– If user input correct number, then make new random number

import random
matnum = random.randint(1,9)
guess = eval(input( 'Your guess please(1~10, 11 quit):' ))
while guess != matnum:
if guess > matnum:
print( 'Too high' )
else:
print( 'Too low' )
guess = eval(input( 'Your next guess please: '))
print( 'At last!' )
Excercise
• A guessing game
– Quit the while loop when the user input the number 11
– Otherwise never stop the game

import random
matnum = random.randint(1,9)
guess = eval(input( 'Your guess please(1~10, 11 quit):' ))
while guess != 11:
if guess > matnum:
print( 'Too high' )
elif guess < matnum:
print( 'Too low' )
else:
print( ‘At last!’)
guess = eval(input( 'Your next guess (1~10, 11 quit): '))
while: example
• More than 2 conditions?
• while condition1 and condition2: k=0
while k < 4 and k != 2:
statement k += 1;
print( k )
• while condition1 or condition2:

statement
– True : execute statement
– False : quit the loop
– Condition: <, >, >=, <=, !=, ==
Excercise
• A guessing game
– Quit the while loop if the guess is same as matnum or if the user in-
put the number 11

import random
matnum = random.randint(1,9)
guess = eval(input( 'Your guess please(1~9 , 11 quit):' ))
while guess != matnum:
if guess > matnum:
print( 'Too high' )
else:
print( 'Too low' )
guess = eval(input( 'Your next guess please: '))
print( 'At last!' )
Excercise
• A guessing game
– Quit the while loop if the guess is same as matnum or if the user in-
put the number 11

import random
matnum = random.randint(1,9)
guess = eval(input( 'Your guess please(1~9 , 11 quit):' ))
while guess != matnum and guess != 11:
if guess > matnum:
print( 'Too high' )
else:
print( 'Too low' )
guess = eval(input( 'Your next guess please(1~10 , 11 quit): '))
print( 'At last!' )
break and continue
• If there are a number of different conditions to stop a while loop, you
may be tempted to use a for with the number of repetitions set to some
accepted cut off value (or even inf) but enclosing if statements which
break out of the for when the various conditions are met.
BREAK Terminate execution of WHILE or FOR loop.
BREAK terminates the execution of FOR and WHILE loops.
In nested loops, BREAK exits from the innermost loop only.
BREAK is not defined outside of a FOR or WHILE loop.
Use RETURN in this context instead.

CONTINUE Pass control to the next iteration of FOR or WHILE loop.


CONTINUE passes control to the next iteration of FOR or WHILE loop
in which it appears, skipping any remaining statements in the body
of the FOR or WHILE loop.
In nested loops, CONTINUE passes control to the next iteration of
FOR or WHILE loop enclosing it.
continue
Excercise
• A guessing game
– Quit the while loop when the user input the number 11 (use break)
– Skip the single repetition when user input the number 12 (use continue)

import random
matnum = random.randint(1,9)
guess = eval(input( 'Your guess please(1~9 , 11 quit, 12 skip):' ))
while guess != matnum:
if guess > matnum:
print( 'Too high' )
else:
print( 'Too low' )
guess = eval(input( 'Your next guess please: '))
print( 'At last!' )
Excercise
• A guessing game
– Quit the while loop when the user input the number 11 (use break)
– Skip the single repetition when user input the number 12 (use continue)

import random
matnum = random.randint(1,9)guess = eval(input( 'Your guess
please(1~9 , 11 quit, 12 skip):' ))
while guess != matnum:
if guess == 11:
break
if guess == 12:
continue
if guess > matnum:
print( 'Too high' )
else:
print( 'Too low' )
guess = eval(input( 'Your next guess please: '))
print( 'At last!' )
ch3.3,
10, 11, 12, 15, 20, 21, 22, 23, 24, 31
The while Loop
• Executes a block of code repeatedly
• while loop repeatedly executes an in-
dented block of statements
– As long as a certain condition is met
• Form

• Continuation condition is a boolean ex-


pression
The while Loop
• Example 1: Program displays 1 – 5, after
loop terminates, num will be 6
The while Loop

FIGURE 3.22 Flowchart


for Example 1.
The while Loop
• Example 2: Input validation.
The while Loop
• Example 3: Find min, max, average.
The while Loop
• Example 3: Find min, max, average.
The while Loop
• Example 4: Stores the numbers in a list,
and then uses list methods and functions
to determine the requested values.
The while Loop
• Example 5: Determines when bank de-
posit
reaches one million dollars
The break Statement
• Causes an exit from anywhere in the
body of a loop
• When break is executed
– Loop immediately terminates
• Break statements usually occur in if
statements
The break Statement
• Example 6: Program uses break to avoid
two input statements.
The break Statement

FIGURE 3.23 Flowchart for Example 6


The continue Statement

• When continue executed in a while loop


– Current iteration of the loop terminates
– Execution returns to the loop’s header
• Usually appear inside if statements.
The continue Statement
• Example 7: Searches a list for the first int
object that is divisible by 11.
Creating a Menu
• Example 8: Uses a menu to obtain facts
about the United States.
The continue Statement
• Example 8: Uses a menu to obtain facts
about the United States.
Infinite Loops
• Example 9: Condition number >= 0 al-
ways true.
Infinite Loops

FIGURE 3.24 Pro-


gram Containing
an Infinite Loop.

You might also like