[go: up one dir, main page]

0% found this document useful (0 votes)
31 views7 pages

Loops

This document explains the use of `for` and `while` loops in Python, detailing their syntax, key concepts, and examples. It highlights the differences between the two types of loops, including their use cases, termination conditions, and potential pitfalls. Additionally, it covers loop control statements like `break` and `continue`, as well as the optional `else` clause for both loop types.

Uploaded by

ranajitbarik2005
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views7 pages

Loops

This document explains the use of `for` and `while` loops in Python, detailing their syntax, key concepts, and examples. It highlights the differences between the two types of loops, including their use cases, termination conditions, and potential pitfalls. Additionally, it covers loop control statements like `break` and `continue`, as well as the optional `else` clause for both loop types.

Uploaded by

ranajitbarik2005
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

FOR LOOPS

In Python, a `for` loop is used to iterate over a sequence (such as a list, tuple, string, or range) and
execute a code block for each item in the sequence. Here's the basic syntax:

for variable in sequence:

# code to be executed

Key Points:

1. `variable`: A temporary variable that takes the current item's value in the sequence during each
iteration.

2. `sequence`: The collection or iterable you're looping through (like a list, string, or range).

3. Indentation: The code block inside the loop is indented to indicate that it belongs to the loop.

Example with a list:

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:

print(fruit)

Output:

apple

banana

cherry

Example with `range()`:

The `range()` function generates a sequence of numbers.

for i in range(5): # range(5) generates numbers from 0 to 4

print(i)

Output:

1
2

Looping through a string:

You can also iterate over the characters in a string.

for letter in "Python":

print(letter)

Output:

`else` Clause:

You can use an optional `else` block with a `for` loop. The `else` part is executed when the loop
finishes iterating over the sequence without hitting a `break`.

for i in range(3):

print(i)

else:

print("Finished looping!")

Output:
0

Finished looping!

Loop Control Statements:

- `break`: Exits the loop early.

- `continue`: Skips the current iteration and moves to the next.

Example using `break`:

for num in range(5):

if num == 3:

break

print(num)

Output:

Example using `continue`:

for num in range(5):

if num == 3:

continue

print(num)

Output:
0

While Loops
A while loop in Python allows you to repeatedly execute a code block as long as a certain condition is
true. It is useful when the number of iterations is not predetermined and depends on a condition
evaluated at runtime.

Syntax:

while condition:

# Code block to execute

 The condition is a boolean expression that is evaluated before each iteration of the loop.

 If the condition is True, the loop body will execute.

 If the condition becomes False, the loop stops, and the program continues with the next
statement after the loop.

Example:

count = 0

while count < 5:

print(count)

count += 1

Explanation:

 The loop starts with count = 0.

 The condition count < 5 is checked. Since it's true, the block inside the loop is executed.

 count is incremented by 1 during each iteration.

 The loop continues until count becomes 5, after which the condition count < 5 evaluates to
False, and the loop stops.

Key Concepts of While Loops:

1. Infinite Loops: A while loop can potentially run forever if the condition never becomes False.
This is known as an infinite loop.
while True:

print("This will run forever")

This loop will continue indefinitely unless interrupted.

2. Break Statement: The break statement is used to exit the loop prematurely, even if the
condition is still true.

count = 0

while count < 10:

print(count)

if count == 5:

break # Exits the loop when count reaches 5

count += 1

3. Continue Statement: The continue statement is used to skip the remaining code in the
current iteration and proceed with the next iteration of the loop.

count = 0

while count < 5:

count += 1

if count == 3:

continue # Skip the rest of the loop when count is 3

print(count)

4. Else Block: An else block can be attached to a while loop, which executes when the loop
condition becomes False.

count = 0

while count < 3:

print(count)

count += 1

else:

print("Loop has finished!")


Output:

Loop has finished!

Use Cases of while Loops:

 User Input Validation: Keep asking for valid input until the user enters the correct value.

 Background Tasks: Continuously check for some background process until a condition is met.

 Repetition Until a Condition: For tasks that need to repeat until a certain condition is
achieved.

Common Pitfalls:

1. Infinite Loop by Accident: If you forget to update the condition within the loop, it may result
in an infinite loop.

x = 10

while x > 5:

print(x)

# Forgot to update x, loop runs forever!

2. Logical Errors in Conditions: Incorrect conditions can lead to loops that either don’t execute
at all or exit prematurely.

The while loop is powerful when you need flexibility in determining how many times to iterate. If you
know beforehand how many times to loop, a for loop is often preferred.

FOR vs WHILE
Feature For Loop While Loop
Use case They are used when the number They are used when the number of
of iterations is known or finite iterations is not known in advance
(iterating over sequences like and depends on a condition.
lists, strings, etc.).
Syntax for variable in sequence: while condition:
Iterates Over a sequence of items (like As long as the condition remains
lists, tuples, strings, ranges). True.
Condition evaluation Implicitly based on the sequence Explicitly evaluates a condition
(no explicit condition needed). before each iteration.
Termination Terminates after going through all Terminates when the condition
items in the sequence. becomes False.
Infinite loops Typically, doesn't result in an Can result in infinite loops if the
infinite loop unless intentionally condition never becomes False.
written as such.
Readability Easier to read and more compact Requires more careful handling for
for known iterations. conditional and indefinite loops.
Break and continue Supports `break` and `continue` Supports `break` and `continue` to
to control loop flow. control loop flow.
Else block Can have an `else` block that Can also have an `else` block that
executes after the loop ends executes if the loop ends naturally.
naturally.
Performance Ideal for iterating over collections Ideal for loops that need to run
efficiently. based on conditions rather than
collections.

You might also like