By the end of this lesson, you will be able to:
🎯 Use while loops with conditions
🎯 Use break and continue statements
🎯 Use for loops to iterate through ranges, lists, and strings
This lesson, you'll learn how to automate repetitive tasks using loops. You'll explore while and for loops, along with break and continue statements. You'll also learn to iterate over lists and strings.
Python Code
count = 1
while count <= 5:
print("Count is", count)
count += 1
Open Google Colab, create a new notebook, and run the examples above in new code cells.
Python Code
x = 1
while x < 10:
if x == 5:
break
print(x)
x += 1
Run the examples above in new code cells.
Python Code
x = 0
while x < 10:
x += 1
if x % 2 == 0:
continue
print(x)
Run the examples above in new code cells.
Python Code
for i in range(1, 6):
print(i)
Run the examples above in new code cells.
Python Code
names = ["Ali", "Bala", "Chan"]
for name in names:
print(name)
Run the examples above in new code cells.
➏ For loop through a string
Python Code
word = "hello"
for letter in word:
print(letter)
Run the examples above in new code cells.
🧠 Answer these to test your understanding.
What does continue do in a loop?
How many times will this code print a value?
for i in range(3):
print(i)
🔧 Instructions:
Write a program to sum numbers until user enters 0.
Write a program to double each number in a list and print.
Write a program to print only even numbers between 1 and 20.
You now understand how to:
Control flow using if, elif, and else
Repeat tasks using while and for loops
Use break and continue for more control inside loops
Iterate through sequences like lists and strings