Python Loops - Part 2
Theory: A for loop repeats code for each item in a sequence. A
while loop repeats while its condition is True. if/elif/else are
used to make decisions. continue skips the current iteration
and break exits the loop immediately.
1. Odd and Even
for i in range(1, 6):
if i % 2 == 0:
print(i, "is Even")
else:
print(i, "is Odd")
2. Multiples of 3
for i in range(1, 11):
if i % 3 == 0:
print(i)
3. Positive, Negative and Zero
numbers = [5, -2, 0, 9, -8]
for num in numbers:
if num > 0:
print(num, "Positive")
elif num < 0:
print(num, "Negative")
else:
print(num, "Zero")
4. Using continue
for i in range(1, 6):
if i == 3:
continue
print(i)
# continue skips the current iteration.
5. Using break
for i in range(1, 10):
if i == 6:
break
print(i)
# break immediately stops the loop.
While Loop Theory
A while loop repeats a block of code as long as its condition
remains True.
1. Print 1 to 5
i = 1
while i <= 5:
print(i)
i += 1
2. Countdown
count = 5
while count > 0:
print(count)
count -= 1
print("Blast Off!")
3. User Input
name = ""
while name == "":
name = input("Enter your name: ")
print("Hello", name)