0% found this document useful (0 votes)
3 views15 pages

Loops in Python001

The document explains loops in Python, highlighting their importance for automating repetitive tasks and simplifying code. It covers the two main types of loops, for and while loops, their syntax, and practical applications such as data processing and automation. Additionally, it discusses loop control statements and the use of list comprehensions for efficient looping.

Uploaded by

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

Loops in Python001

The document explains loops in Python, highlighting their importance for automating repetitive tasks and simplifying code. It covers the two main types of loops, for and while loops, their syntax, and practical applications such as data processing and automation. Additionally, it discusses loop control statements and the use of list comprehensions for efficient looping.

Uploaded by

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

LOOPS IN

PYTHON
MASTERING ITERATION IN
PROGRAMMING
KEERTHI VARDHAN
ANUGUTALA
WHAT ARE LOOPS?
• Loops are fundamental control flow statements that enable
the repeated execution of a block of code. This is essential
for tasks that require repetition, such as processing items in a
list, generating sequences, or performing calculations
multiple times. Without loops, you would have to write
repetitive code manually, which is both inefficient and prone
WHY USE LOOPS?
to errors.

Using loops simplifies code, makes it more readable, and


reduces the chance of errors. They allow for automation
of repetitive tasks, which can save time and effort. By
mastering loops, you can write more efficient and
effective Python programs.
TYPES OF LOOPS
There are two main types of loops in Python: the for loop and the while
loop. Each serves different purposes and is suited to different types of
tasks.
• For Loop:
Used for iterating over a sequence (like a list, tuple, string, or range).
Executes a block of code a specific number of times or until the end of
the sequence is reached.
• While Loop:
Continues to execute a block of code as long as a specified condition is
true.
Useful for scenarios where the number of iterations is not known in
advance and depends on dynamic conditions.
THE FOR LOOP
Syntax of for loop
for variable in
sequence:
# code to execute
In a for loop, the variable takes on each value in
the sequence one by one, and the code block
within the loop executes for each value.
Examples:
for i in
range(5):
print(i)
This loop iterates over the range of numbers
from 0 to 4, printing each number. For loops
are versatile and can be used with various
data structures.
USING THE RANGE
FUNCTION
Range() Function in For Loops:
The range() function generates a sequence of
numbers, which is particularly useful in for loops.
It can take up to three arguments: start, stop, and
step.
Examples:
for i in range(1,
10, 2):
print(i)
This example prints odd numbers between 1 and 9. The
range() function starts at 1, stops before 10, and
increments by 2.
LOOPING THROUGH LISTS
• Iterating Over Lists: You can use a for loop to iterate over
items in a list, allowing you to process each item individually.

Examples:
fruits = ['apple', 'banana',
'cherry']
for fruit in fruits:
print(fruit)
In this example, the loop iterates over each item in the fruits
list and prints it. This is a common pattern for
processing elements in a list
LOOPING THROUGH STRINGS
• Iterating Over Strings: A for loop can be used to iterate
over each character in a string, which is useful for tasks like
string manipulation and analysis.
Examples:
for char in 'Python':
print(char)

This loop prints each character in the word


"Python" on a new line. It demonstrates how loops
can handle not just numbers but also text.
THE WHILE
LOOP
• Syntax of While
Loop
while
: condition:
# code to
execute
A while loop continues to execute the block of code as
long as the condition remains true. It's particularly useful
for tasks where the number of iterations is not
predetermined.
Examples: count = 0
while count < 5:
print(count)
count += 1

In this example, the loop prints numbers from 0 to


4. The count variable is incremented with each
iteration, ensuring the loop eventually terminates
INFINITE LOOPS
• What Are Infinite Loops?:
An infinite loop occurs when the condition in a while loop never
becomes false, causing the loop to run indefinitely. This can happen
if the loop's exit condition is not correctly defined or if the variables
involved are not updated properly.

• How to Avoid Them?:


To avoid infinite loops, ensure that the loop's condition will
eventually become false. This can be done by updating variables
within the loop and carefully defining the exit condition. Using break
statements can also help terminate loops prematurely if needed.
NESTED LOOPS
• Definition of Nested Loops:
A nested loop is a loop inside another loop. Each time the
outer loop iterates, the inner loop completes all its iterations.
Nested loops are useful for tasks that require comparing or
processing elements in multi-dimensional structures like
matrices. :
Examples for i in range(3):
for j in range(2):
print(i, j)

In this example, the outer loop runs three times, and for each
iteration, the inner loop runs twice. The output consists of
pairs of numbers representing the current iteration of each
loop.
LOOP CONTROL
STATEMENTS
• Break Statement: Exits the loop
prematurely.
for i in range(10): This loop prints numbers from 0 to 4 and then exits
if i == 5: when i equals 5.Continue Statement: Skips the rest
break of the loop and continues with the next iteration.
print(i)
for i in range(10): This loop prints only odd numbers between 0 and 9
if i % 2 == 0: by skipping even numbers.
continue
print(i)
Pass Statement: Does nothing and acts as a placeholder.
for i in range(5):
The pass statement is useful when a statement
pass # Do
is syntactically required but no action is
nothing
needed.
LOOPING THROUGH
DICTIONARIES
• Iterating Over Dictionary Items: You can use loops to
access key-value pairs in a dictionary. This is useful for tasks
like data processing and analysis.
Examples:
dict = {'a': 1, 'b': 2, 'c': 3}
for key, value in dict.items():
print(key, value)

In this example, the loop iterates over each key-value


pair in the dictionary and prints them. This allows you
to process both keys and values in a structured way.
LIST
COMPREHENSIONS
• Using List Comprehensions for Looping:
• List comprehensions provide a concise way to create lists.
They are a more readable and often more efficient alternative
to traditional for loops.
Examples:
squares = [x**2 for x in range(10)]

This list comprehension creates a list of squares of


numbers from 0 to 9. It's a compact and expressive
way to generate lists.
PRACTICAL
APPLICATIONS
• Common Use Cases for Loops:
Data Processing:
Loops are essential for processing items in datasets, such as filtering and
transforming data.
Automation Scripts: Automate repetitive tasks, like file handling and user
interactions.
Games and Simulations: Control game mechanics, generate random events, and
simulate real-world scenarios.

Real world Examples:


Summing Numbers in a List: Calculate the total of a series of numbers.
Processing User Input: Repeatedly prompt users for input until valid data is received.
Simulating a Deck of Cards: Iterate through cards to shuffle and deal in card games.
CONCLUSION
• Summary of Key Points:
For and While Loops: Essential for repetition and
automation.
Control Statements: Break, continue, and pass add
flexibility to loop execution.
Versatility: Loops can iterate over various data
structures, including lists, strings, and dictionaries.

You might also like