Escolar Documentos
Profissional Documentos
Cultura Documentos
PFE610S
NUST 2019
Python Loops
• While loop
– To iterate over an undefined or unknown number
of iterations
– Requires a control sequence
• For-in loop
– Iterates over items for a known or predetermined
number of iterations
Userful_link:
https://www.ntu.edu.sg/home/ehchua/programming/webprogramming/Python1_Basics.html#zz-7.
The while loop
The syntax:
while conditional_expression:
Body (statement(s))
The while loop example
i=0
while i < 5:
print(“The count is {}”.format(i))
i +=1
OR
i=0
while i != 10:
print(“The count is {}”.format(i))
i +=1
The for-in loop
The syntax:
for item in sequence:
Body (statement(s))
The for-in loop example
OR
Additional loops controls
The loop control break example
Note:
The break statement
breaks out of the
inner most loop.
The loop control continue example
Note:
The continues statement skips the
remaining statement of the loop and
continues the next iteration.
The loop control else example
Note:
The else block is optional and is executed if
the loop exits normally without encountering
a break statement.
Nested loops
• We can have a loops within a loop
• e.g to print the pattern of 4 by 4 stars shown below.
****
****
****
****
• The loop code below can be used.