0% found this document useful (0 votes)
62 views11 pages

Python Loops: PFE610S NUST 2019

The document discusses different types of loops in Python including while loops, for-in loops, and nested loops. While loops iterate over an unknown number of iterations using a control sequence. For-in loops iterate over a known number of items in a sequence. Additional loop controls like break, continue, and else are also covered. Nested loops allow loops within other loops to iterate multiple times.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
62 views11 pages

Python Loops: PFE610S NUST 2019

The document discusses different types of loops in Python including while loops, for-in loops, and nested loops. While loops iterate over an unknown number of iterations using a control sequence. For-in loops iterate over a known number of items in a sequence. Additional loop controls like break, continue, and else are also covered. Nested loops allow loops within other loops to iterate multiple times.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Python Loops

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.

Syntax of a nested for loop: Syntax of a nested while loop:


for item in sequence: while expression:
for item in sequence: while expression:
Body (statement(s)) Body (statement(s))
statement(s) statement(s)

You might also like