Вы находитесь на странице: 1из 11

Loop Structures

Recall Structured Programming..3 basic control structures


Sequence Input Process Output Selection IF Loop Structures WHILE FOR

Dr. Hugh Melvin, Dept. of IT, NUI,G

Algorithm to record TV programmes


1. Insert a
DVD 2. If unformatted..format DVD 3. If reqd, set record quality (SP HQ) 3. Repeat steps 4 - 7 for each program 4. S date Set 5. Set start time 6. Set stop time 7. Set channel 8. Set DVD player

to timed mode
Dr. Hugh Melvin, Dept. of IT, NUI,G

Control structures
1.Sequence is a group of instructions followed in order from the first through to the last 2. Selection (decision) is used to make logical decisionsto choose between alternate actions depending on certain conditions 3. Repetition (looping) allows a group of steps to be repeated several times, usually until some condition is satisfied
4. Set date 5. Set start time 6. Set stop time 7. Set channel

2. If reqd, format disk 3. If reqd, set record Quality

3. Repeat steps 4 - 7 for each program Dr. Hugh Melvin, Dept. of IT, NUI,G

while loop
Controlled by a Boolean Expression ..TRUE or FALSE The loop executes as long as the condition is TRUE If condition FALSE, skip to statement after the loop
Start
numprogs=0

Condition is tested every time time, you need to set initial value change value within the loop..otherwise get an infinite loop

numprogs <5?

Start and end time date & channel add 1 to numprogs

End
Dr. Hugh Melvin, Dept. of IT, NUI,G

while loop
Form WHILE condition:
Indented loop body

Action

If condition i evaluated as TRUE th body of th diti is l t d TRUE, the b d f the loop is executed. Control branches to the top and condition retested etc If condition FALSE, skip to statement after loop body (1st unindented line)
Dr. Hugh Melvin, Dept. of IT, NUI,G

while
Input num

Pseudocode INPUT num WHILE num != 0 OUTPUT num INPUT num LOOP OUTPUT Done

Outputdone

Is num !=0?

Output num

Input num

WHILE is a pre-test loop the exit test is made before the loop is executed If the test fails first time, the loop is NEVER executed
Dr. Hugh Melvin, Dept. of IT, NUI,G

while loop
While .. with a counter
Counter useful to perform an operation a specified number of times Counter is initialised before entering loop, tested at start of loop and changed within loop
E 1 P Eg.1. Program reads i f d in four numbers and t t l th b d totals them Eg.2. Program prints out numbers 1 to 9 Eg.3. Program counts down

Dr. Hugh Melvin, Dept. of IT, NUI,G

Dr. Hugh Melvin, Dept. of IT, NUI,G

Dr. Hugh Melvin, Dept. of IT, NUI,G

Dr. Hugh Melvin, Dept. of IT, NUI,G

Beware!!
A loop coded so that it cannot be exited is
called an infinite loop WHILE
infinite loop if condition can never become false

B careful with code Be f l ih d

Dr. Hugh Melvin, Dept. of IT, NUI,G

Infinite loops.. but infinitely different!!

Dr. Hugh Melvin, Dept. of IT, NUI,G

while else & break


break
Used to jump out of a loop Can be useful in certain abnormal situations

else l
Similar to use in if statement Used to specify a block of code that runs iff the loop is exited normally i.e. no break

Will cover examples later


Dr. Hugh Melvin, Dept. of IT, NUI,G

for loop
Also provides for iteration in Python Most useful with strings/lists of data
Covered in more detail in Sem 2

General format
for VARIABLE in LIST: BODY

Steps through each item in list in operator intuitive


Dr. Hugh Melvin, Dept. of IT, NUI,G

for
Equivalent while loop
i = 0 while i < len(LIST): VARIABLE = LIST[i] BODY i = i + 1

Much simpler construct relative to while


No need for variable i No need to process list by incrementing variable i i = i+1 Can also be used with else
Dr. Hugh Melvin, Dept. of IT, NUI,G

for .. general format


for target in object: statements else: statements

Assigns items in sequence object to target one by one and executes loop body statements for each Optional else
Used in cases of normal loop exit
Dr. Hugh Melvin, Dept. of IT, NUI,G

for
Some for examples
Introduce 2 other functions range()
Creates lists of integers Very useful with for loop

len(LIST)
Calculates number of elements in a list

Dr. Hugh Melvin, Dept. of IT, NUI,G

range & len

Dr. Hugh Melvin, Dept. of IT, NUI,G

range & len

Dr. Hugh Melvin, Dept. of IT, NUI,G

Dr. Hugh Melvin, Dept. of IT, NUI,G

Dr. Hugh Melvin, Dept. of IT, NUI,G

Dr. Hugh Melvin, Dept. of IT, NUI,G

Dr. Hugh Melvin, Dept. of IT, NUI,G

Input Validation
Very important for robust code Eg
Grade must be in range 0 -100 Cl Class size must b positive i t be iti Avoid divide by zero

Important use of while loop

Dr. Hugh Melvin, Dept. of IT, NUI,G

Dr. Hugh Melvin, Dept. of IT, NUI,G

Dr. Hugh Melvin, Dept. of IT, NUI,G

Nested loops
Have already seen nested IF Statements Nested loops
Loop within a loop

Each loop has its own set of control variables p Can be useful in certain scenarios

Dr. Hugh Melvin, Dept. of IT, NUI,G

Nested for loops : output?

Dr. Hugh Melvin, Dept. of IT, NUI,G

Nested while loops : output?

Dr. Hugh Melvin, Dept. of IT, NUI,G

ATM exercise
Use loops to implement simulated ATM
Case A. Loop and give 3 attempts to get PIN correct Count number of attempts Case B Case A plus.. Loop until amount <= 300 euro entered
i.e. 300 is max withdrawal
Dr. Hugh Melvin, Dept. of IT, NUI,G

10

ATM
PIN=input("Enter PIN:") while PIN!=1456: PIN=input("Wrong PIN .. Enter again:") attempts=attempts+1
Gives user infinite number of attempts ! How many permutations of 4 digit code ? Need to limit attempts to 3 Use logical and operator

Similar while loop to ensure amount <= 300


No limit on attempts usually?

Dr. Hugh Melvin, Dept. of IT, NUI,G

Comparison loop structures


Either for or while can be used in most situations for
Very useful for loops that execute a pre-specified number of times. Loop iteration automatically incremented/controlled less error prone

while
Alternative to for Have to explicitly control iterations errors Specifically useful for input validation
Dr. Hugh Melvin, Dept. of IT, NUI,G

11

Вам также может понравиться