Skip to main content

How to use Loops in Python? Explain with Examples

 In Python, loops are powerful tools for repeating a block of code multiple times. They allow you to automate tasks, iterate over sequences of data, and create dynamic behavior in your programs. Here's an explanation of the two main types of loops and how to use them with examples:

1. for Loop:

The for loop iterates over a sequence of items, executing a block of code for each item. It's commonly used for tasks like processing lists, strings, tuples, or dictionaries.

Syntax:

Python
for item in sequence:
    # code to execute for each item

Example:

Python
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
    print(f"I like {fruit}.")

This code will print:

I like apple.
I like banana.
I like orange.

2. while Loop:

The while loop continues to execute a block of code as long as a condition is True. It's suitable for situations where you don't know beforehand how many times the loop should run.

Syntax:

Python
while condition:
    # code to execute while the condition is True

Example:

Python
count = 0
while count < 5:
    print(count)
    count += 1

This code will print:

0
1
2
3
4

Additional Tips:

  • Use break to exit a loop prematurely if a certain condition is met.
  • Use continue to skip to the next iteration of the loop.
  • Use nested loops to create more complex loops within loops.
  • Choose the right loop type based on your need: for for iterating over sequences, while for unknown number of iterations.

Further Examples:

  • Looping through a dictionary:
Python
person = {"name": "Alice", "age": 30, "city": "New York"}
for key, value in person.items():
    print(f"{key}: {value}")
  • Using range function for numerical loops:
Python
for i in range(5):  # iterates from 0 to 4 (excluding 5)
    print(i * i)
  • Looping with conditional execution:
Python
numbers = [1, 2, 3, 4, 5]
for number in numbers:
    if number % 2 == 0:
        print(f"{number} is even.")
    else:
        print(f"{number} is odd.")


Sure, here are some more examples of loops in Python:

1. Nested loops:

Python
# Create a multiplication table
for i in range(1, 11):
    for j in range(1, 11):
        product = i * j
        print(f"{i} x {j} = {product}")

# Iterating over nested data structures
data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in data:
    for element in row:
        print(element, end=" ")
    print()

2. Looping with enumerate:

Python
# Accessing index and element together
for index, name in enumerate(["Alice", "Bob", "Charlie"]):
    print(f"Person {index+1}: {name}")

# Modifying elements in a loop
numbers = [1, 2, 3, 4]
for i, number in enumerate(numbers):
    numbers[i] = number * 2
print(numbers)  # Output: [2, 4, 6, 8]

3. Infinite loops (use with caution):

Python
# Example of an infinite loop (use responsibly!)
while True:
    user_input = input("Enter 'exit' to quit: ")
    if user_input == "exit":
        break
    print("You entered:", user_input)

4. Looping with break and continue:

Python
# Printing even numbers only
for i in range(1, 11):
    if i % 2 != 0:
        continue  # Skip odd numbers
    print(i)

# Finding the first even number greater than 5
for i in range(1, 11):
    if i % 2 == 0 and i > 5:
        print(f"First even number greater than 5: {i}")
        break

5. Looping with generators:

Python
# Generator for Fibonacci sequence
def fibonacci(n):
    a, b = 0, 1
    for i in range(n):
        yield a
        a, b = b, a + b

# Using the generator with a for loop
for num in fibonacci(10):
    print(num)

Remember to choose the appropriate loop type and use break and continue cautiously to avoid infinite loops or unexpected behavior. These are just a few examples, and the possibilities with loops are vast! Experiment and explore to master loop-based tasks in Python.


By understanding and using loops effectively, you can write more efficient and flexible Python code. Remember to experiment and explore different scenarios to enhance your coding skills!

Comments

Popular posts from this blog

What is Branching in python and how to use with examples

  In Python,   branching   refers to the ability to control the flow of your program based on certain conditions.   This allows your code to make decisions and execute different blocks of code depending on the outcome of those conditions. There are three main types of branching statements in Python: 1.  if  statement: The  if  statement allows you to execute a block of code only if a certain condition is True. The basic syntax is: Python if condition: # code to execute if condition is True Here's an example: Python age = 25 if age >= 18 : print( "You are an adult." ) else : print( "You are not an adult." ) 2.  if...elif...else  statement: This allows you to check multiple conditions and execute different code blocks for each condition. The  elif  branches are checked sequentially until one of them is True. If none are True, the  else  block is executed (optional). Python score = ...

Is JavaFX worth to learn in 2024? What are the advantages and disadvantages?

  Whether JavaFX is worth learning in 2024 depends on your specific goals and interests.   Here's a breakdown of its advantages and disadvantages to help you decide: Advantages: Platform-independent:  JavaFX applications can run on Windows, macOS, Linux, and some mobile platforms.This cross-platform compatibility can be valuable if you want to target a wider audience. Modern UI framework:  JavaFX offers a rich set of UI components and features for building modern and visually appealing applications. It includes animation, effects, transitions, and support for touch gestures. Integration with Java:  JavaFX integrates seamlessly with the Java ecosystem, allowing you to leverage existing Java libraries and tools. This can be helpful if you're already familiar with Java development. Large community:  JavaFX has a large and active community of developers, providing resources, tutorials, and support. Dis...

How to build website on Amazon Web service AWS

  Building a website on AWS can be done in various ways depending on your needs and technical expertise.   Here's a breakdown of options with increasing complexity: 1. Simple Static Website: Use  Amazon S3  as a static file storage bucket. Upload your website's HTML, CSS, and JavaScript files to the bucket. Configure public access for the bucket to allow everyone to see your website. Optionally, use  Amazon CloudFront  as a Content Delivery Network (CDN) for faster global reach. 2. Website with a Content Management System (CMS): Use  AWS Lightsail  to launch a virtual server instance pre-configured with a popular CMS like WordPress, Joomla,or Drupal. Manage your website content through the CMS admin interface. Secure your server with additional tools like security groups and firewalls. 3. Serverless Website with Backend Functionality: Use  AWS Amplify  for serverless website deployment and hosting. Create static websi...