Learn Python in 30 Days - Day 5: Loops (for and while)
Welcome to Day 5! Loops are a powerful feature in Python that allow you to repeat actions or iterate through collections of data. Today, we’ll cover for and while loops, along with examples to practice.
1. What Are Loops?
A loop is a control structure that lets you execute a block of code repeatedly based on a condition or a range of values.
Types of Loops in Python:
forloop - Iterates over a sequence (e.g., list, range, string).whileloop - Repeats as long as a condition isTrue.
2. The for Loop
The for loop is used to iterate over a sequence, such as a list, range, or string.
Syntax:
for item in sequence:
# Code to execute for each item
Example 1: Looping Through a List
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
Example 2: Using range()
The range() function generates a sequence of numbers.
for i in range(5): # Loops from 0 to 4
print("Number:", i)
Output:
Number: 0
Number: 1
Number: 2
Number: 3
Number: 4
3. The while Loop
The while loop continues as long as a condition is True.
Syntax:
while condition:
# Code to execute
Example 1: Counting with while
count = 0
while count < 5:
print("Count:", count)
count += 1 # Increment the count
Output:
Count: 0
Count: 1
Count: 2
Count: 3
Count: 4
Example 2: User Input with while
password = ""
while password != "python123":
password = input("Enter the password: ")
print("Access granted!")
4. break and continue Statements
break Statement
Stops the loop immediately.
Example:
for i in range(10):
if i == 5:
break
print(i)
Output:
0
1
2
3
4
continue Statement
Skips the current iteration and moves to the next.
Example:
for i in range(5):
if i == 2:
continue
print(i)
Output:
0
1
3
4
5. Nested Loops
A loop inside another loop.
Example:
for i in range(3):
for j in range(2):
print(f"Outer loop: {i}, Inner loop: {j}")
Output:
Outer loop: 0, Inner loop: 0
Outer loop: 0, Inner loop: 1
Outer loop: 1, Inner loop: 0
Outer loop: 1, Inner loop: 1
Outer loop: 2, Inner loop: 0
Outer loop: 2, Inner loop: 1
6. Practice Tasks for Day 5
Task 1: Multiplication Table
Write a program to print the multiplication table for a given number:
num = 5
for i in range(1, 11):
print(f"{num} x {i} = {num * i}")
Task 2: Sum of Numbers
Write a program to calculate the sum of the first 10 natural numbers:
total = 0
for i in range(1, 11):
total += i
print("Sum:", total)
Task 3: Guess the Number
Write a program that lets the user guess a number until they get it right:
import random
number_to_guess = random.randint(1, 10)
guess = 0
while guess != number_to_guess:
guess = int(input("Guess the number (1-10): "))
if guess < number_to_guess:
print("Too low!")
elif guess > number_to_guess:
print("Too high!")
print("Congratulations! You guessed the number.")
7. Common Mistakes to Avoid
-
Infinite Loops:
Ensure your loop has an exit condition; otherwise, it will run forever.while True: # Avoid unless intended print("This is infinite!") -
Off-by-One Errors:
Be careful with the start and end points of loops (e.g.,range()). -
Misplaced
breakorcontinue:
These statements should only be used inside loops.
8. Pro Tips for Day 5
- Use
forloops when iterating over a sequence or range. - Use
whileloops when the number of iterations is not fixed. - Add comments to complex loops to explain their purpose.
🎯 Day 5 Goal: Practice writing programs using for and while loops. Implement tasks like multiplication tables, summing numbers, and nested loops.
Let me know when you’re ready for Day 6! 🚀

0 Comments