Class Topic: Loops in Programming
In this class, we covered the concept of loops in programming, including 'for', 'while', 'break',
'continue', and nested loops.
1. for Loop
Used when the number of iterations is known.
for i in range(5):
print("Hello")
2. while Loop
Used when the number of iterations is unknown; continues until the condition is false.
count = 0
while count < 5:
print("Hi")
count += 1
3. break and continue
- 'break' stops the loop.
- 'continue' skips the current iteration and continues the loop.
Example of continue:
for i in range(1, 6):
if i == 3:
continue
print(i)
# Output: 1 2 4 5
Classwork (CW)
1. Print numbers from 1 to 10 using a for loop.
for i in range(1, 11):
print(i)
2. Print only even numbers from 1 to 20.
for i in range(1, 21):
if i % 2 == 0:
print(i)
3. Print "Python" 5 times using a while loop.
count = 0
while count < 5:
print("Python")
count += 1
4. Ask user to enter password until correct using while.
password = ""
while password != "1234":
password = input("Enter password: ")
print("Access granted")
Homework (HW)
1. Print all numbers from 1 to 20 using a for loop.
2. Print only even numbers from 1 to 50 using a for loop.
3. Print numbers from 1 to 10 but skip 5 using continue.
4. Use a while loop to calculate the sum of numbers from 1 to 100 and print the result.
5. Ask user for a secret code until correct (e.g., 1234) using while loop.
*Bonus Task: Ask the user for a number and print its multiplication table up to 10.