0% found this document useful (0 votes)
12 views13 pages

Python Loops: For and While Explained

Looping in python

Uploaded by

amankonam44
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)
12 views13 pages

Python Loops: For and While Explained

Looping in python

Uploaded by

amankonam44
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

Loops in Python

Making code repeat without repetition


Introduction to Loops

Loops are control They save time Used in almost


structures that let us and reduce every program
repeat code repetition
automatically
Types of Loops in Python

for loop while loop


repeat when repeat while a
the number of condition is true
times is known
The for Loop
OUTPUT
Hello 0
Hello 1
EXAMPLE Hello 2
for i in range(5): Hello 3
print("Hello", i) Hello 4
The range() Function
What does range do?
Example
Generates a sequence of integer
numbers for i in range(2, 10, 2):
Commonly used with ‘for loops’ print(i) # 2 4 6 8
Syntax:
range(stop) → 0 … stop-1
range(start, stop) → start...stop-1
range(start, stop, step) → with
step size
The while Loop

Code Example Code Output


count = 1 Count: 1
while count <= 5: Count: 2
print("Count:", Count: 3
count) Count: 4
count += 1
Count: 5
Loop Control
Statements

break
exits the loop Continue Pass Else
completely skips the does nothing runs if loop ends
current (placeholder) normally (no
iteration break)
BREAK EXAMPLE: Output
for i in range(1, 11) 1
if i == 5: 2
break # Exit loop when i is 5 3
print(i, end=" ") 4

CONTINUE EXAMPLE: Output


1
for i in range(1, 6):
2
if i == 3:
continue # Skip printing when i is 3
4
print(i, end=" ") 5
PASS EXAMPLE: OUTPUT:
for i in range(5): 0
if i == 3: 1
pass # Do nothing when i is
else: 2
print(i) 4
ELSE EXAMPLE:
OUTPUT:
for i in range(5):
if i == 3:
break 0
print(i) 1
else: 2
print("Loop completed without break")
Touch ups
l
for loop →
counting chairs in a
classroom
while loop →waiting for phone to
fully charge
break →leaving class early
continue →
skipping one chair while
counting
pass → doing nothing, just standing still
CONCLUSION

LOOPS FOR AND WHILE Control


save time and avoid LOOPS statements
repetition and are for = fixed number of
essential in real-life
break, continue ,pass
repetitions
coding. while = condition-based and else make loops
repetition more flexible.
THANK YOU!!
EDWARD MILLS CSC/24/01/0364
KPORVI KOFI LIVINGSTONE CSC/24/01/0139
BENEDICTA AMARKO CSC/24/01/0446
AIDOO KOFI EMMANUEL CSC/24/01/1018
MARY AMISSAH CSC/24/01/0363
PRECIOUS AGYEI CSC/24/01/0861
OFORI CINDY NANA AMA CSC/24/01/0787
PRINCESS JESSICA CSC/24/01/0506
EMMANUEL LAARI CSC/24/01/1788
JULIET ANGAANDI CSC/24/01/0447

You might also like