Python Loops and Iteration
Topic: Loops and Iteration
Mastering the power of repetition and automation.
1. The Concept of Iteration
In programming, Iteration simply means repeating a process. Instead of writing the same line of code 100 times, we use a loop. Python provides two main types of loops: the For Loop and the While Loop.
2. The "For" Loop (Fixed Repeats)
Use a for loop when you know exactly how many times the code should run. It is often paired with the range() function.
for i in range(1, 6):
print("Attempt number:", i)
range(1, 6) starts at 1 and stops at 5. It never includes the final "stop" number!
3. The "While" Loop (Condition Based)
A while loop keeps running as long as a condition is True. It is perfect for situations where you don't know when the loop will end.
while count > 0:
print("Countdown:", count)
count = count - 1
print("Blast off! ๐")
count - 1), the loop will never stop. This can crash your program!
4. Deep Dive: Six Real-World Examples
To master loops, you must understand how they apply to different scenarios. Here are three examples for each type:
A. For Loop Scenarios (The Accountant)
1. Class Attendance
Processing a list of names one by one.
for name in students:
print(name, "is present.")
2. Backward Timer
Using range to count down with a step of -1.
print("Seconds left:", sec)
3. Email Scanner
Looping through characters in a string.
for char in email:
if char == "@":
print("Found the @ symbol!")
B. While Loop Scenarios (The Security Guard)
1. Game Health Bar
Loop runs as long as the player is alive.
while hp > 0:
hp -= 20
print("Remaining HP:", hp)
2. Infinite Input
Running until the user decides to 'quit'.
while msg != "quit":
msg = input("Say something: ")
3. Savings Goal
Looping until a financial target is met.
while saved < 500:
saved += int(input("Add cash: "))
5. Additional Loop Control: The 'Continue'
While break stops the loop completely, continue skips just one iteration and moves to the next cycle.
if n == 3:
continue
print(n)
6. Nested Loops (Loops inside Loops)
A nested loop is useful for working with tables, patterns, and combinations.
for j in range(1, 3):
print("i =", i, "j =", j)
๐ป Practical Coding Lab
Challenge: The Multiplication Table
Write a program that asks for a number and prints its multiplication table from 1 to 12.
Click to view Solution Code
for i in range(1, 13):
ans = num * i
print(num, "x", i, "=", ans)
Comments
Post a Comment