[go: up one dir, main page]

0% found this document useful (0 votes)
6 views5 pages

Python Day 6

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 5

Detailed Explanation of Loops in Python

1. Need for Loops

Loops are used to automate repetitive tasks in programming. For example, if we want to print
numbers from 1 to 10, we could write:

python
Copy code
print(1)
print(2)
print(3)
# ... up to 10

But this approach is inefficient, especially if we need to print up to 100 or 1000! Instead, we
use loops to repeat the same code multiple times without manually writing each line.

2. The while Loop

The while loop repeats a block of code as long as a condition is True. The condition is
checked before each iteration, so if it’s False initially, the loop will not run at all.

Syntax:

python
Copy code
while condition:
# Code to execute repeatedly

Example:

python
Copy code
# This program prints numbers from 1 to 5
i = 1
while i <= 5:
print(i)
i += 1 # Increases i by 1 each time the loop runs

Explanation:

• i = 1 is the starting point.


• The loop checks if i <= 5 is True. If yes, it executes the code inside the loop.
• Each time, i increases by 1 (i += 1), so eventually i becomes greater than 5, ending
the loop.
3. The for Loop

The for loop is best used when we know how many times we want to repeat a block of code
or when we want to iterate over a collection like a list, string, or range of numbers.

Syntax:

python
Copy code
for variable in sequence:
# Code to execute repeatedly

Example:

python
Copy code
# This program prints each fruit in the list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)

Explanation:

• fruits is a list containing three items.


• The for loop assigns each item in fruits to the variable fruit and prints it.

Using range() with for Loops:

The range() function is often used with for loops when we need to repeat a task a certain
number of times.

python
Copy code
# Prints numbers from 1 to 5
for i in range(1, 6):
print(i)

range(1, 6) generates numbers from 1 up to (but not including) 6.

4. The else Statement with Loops

The else statement can be used with loops. It runs only if the loop completes all iterations
without being interrupted by a break statement.

Example:

python
Copy code
for i in range(5):
print(i)
else:
print("Loop completed without a break.")

• The else statement here will execute after the for loop finishes, since there’s no
break in the loop.

5. The continue Statement

The continue statement is used to skip the current iteration and move to the next one. It’s
helpful when we want to skip certain values or conditions within a loop.

Example:

python
Copy code
for i in range(1, 6):
if i == 3:
continue # Skip the rest of the loop when i is 3
print(i)

Explanation:

• This loop prints 1, 2, 4, and 5. When i is 3, continue causes the loop to skip
print(i) for that iteration.

6. The break Statement

The break statement is used to exit a loop immediately, regardless of the loop’s condition.
It’s useful when we want to stop a loop early based on a condition.

Example:

python
Copy code
for i in range(1, 6):
if i == 3:
break # Exit the loop when i is 3
print(i)

Explanation:

• This loop will print 1 and 2, then stop completely when i is 3 because of the break
statement.

Combining Loops with break, continue, and else


These statements allow us to control the flow of a loop in powerful ways, making it possible
to handle complex conditions and control when the loop should stop or skip an iteration.

Evaluation Questions
These questions are designed to test your understanding of loops and control flow statements.
Try writing Python programs to solve each question.

1. Using while Loop (2 Marks)

• Write a Python program that uses a while loop to print numbers from 10 down to 1.

Hint: Start with i = 10 and decrement i each time in the loop until i is less than 1.

2. Using for Loop (3 Marks)

• Write a Python program that prints each character in the string "Hello World" on a
new line using a for loop.

Hint: Treat the string as a sequence of characters and iterate over it.

3. Using else with Loops (3 Marks)

• Write a Python program that iterates through numbers 1 to 5 using a for loop. If the
loop completes without encountering a break, print "Loop completed successfully."

Hint: The else statement runs if the loop is not interrupted by break.

4. Using continue (3 Marks)

• Write a Python program that prints all numbers from 1 to 10, but skips the numbers
that are divisible by 3. Use the continue statement.

Hint: Use if i % 3 == 0 to check divisibility and continue to skip those numbers.

5. Using break (4 Marks)

• Write a Python program that asks the user to enter numbers. The program should stop
asking for input when the user enters a negative number. Use the break statement to
exit the loop.

Hint: Use an infinite loop (while True) and break out when you receive a negative number.

Expected Learning Outcomes


By the end of these exercises, you should:

• Understand the purpose and usage of while and for loops.


• Know how to control the flow of a loop with continue and break.
• Be familiar with using else with loops.
• Be able to apply loops to solve practical problems in Python.

Feel free to experiment with these concepts to deepen your understanding of loops in Python.

You might also like