Python Loops Practice Tutorial (4)

python Tutorial 4

 What is Loops in python with Example?

 In Python, a loop is a programming structure that allows you to repeatedly execute a block of code. There are two main types of loops in Python: for loops and while loops.

  1. for Loop:

 The for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string). Here’s a basic example:

# Example 1: Iterate over a list

fruits = [“apple”, “banana”, “cherry”]

for fruit in fruits:

    print(fruit)

# Output:

# apple

# banana

# cherry

 In this example, the for loop iterates over each element in the fruits list, and the variable fruit takes on each value in the sequence one by one.

  1. while Loop:

 The while loop is used to repeatedly execute a block of code as long as a specified condition is true. Here’s an example:

# Example 2: Using a while loop

count = 0

while count < 5:

    print(count)

    count += 1

# Output:

# 0

# 1

# 2

# 3

# 4

 In this example, the while loop continues executing as long as the condition count < 5 is true. The count variable is incremented in each iteration.

Loop Control Statements:

Python provides two loop control statements: break and continue.

break: Terminates the loop prematurely.

continue: Skips the rest of the code inside the loop for the current iteration and goes to the next iteration.

# Example 3: Using break and continue

for i in range(10):

    if i == 3:

        break  # Exit the loop when i is 3

    if i == 1:

        continue  # Skip the rest of the code for i = 1

    print(i)

# Output:

# 0

# 2

# Example 3: Using break and continue

for i in range(10):

    if i == 3:

        break  # Exit the loop when i is 3

    if i == 1:

        continue  # Skip the rest of the code for i = 1

    print(i)In this example, the loop breaks when i is equal to 3, and the code is skipped for i equal to 1 using continue.

Loops are fundamental for repetitive tasks in programming, and mastering them is essential for writing efficient and concise code.

 Why we need use for loop in python with Example

 The for loop in Python is a powerful and convenient way to iterate over a sequence (such as a list, tuple, string, or dictionary) and perform a set of operations for each element in that sequence. Here are some reasons why you might need to use a for loop in Python, along with examples:

Iterating Over a List:

# Output:

# 0

# 2

# Example 1: Print each element in a list

fruits = [“apple”, “banana”, “cherry”]

for fruit in fruits:

    print(fruit)

# Output:

# apple

# banana

# cherry

Here, the for loop simplifies the process of going through each element in the list fruits.

Generating Sequences:

# Example 2: Generate a sequence of numbers

for i in range(5):

    print(i)

# Output:

# 0

# 1

# 2

# 3

# 4

The range() function combined with a for loop is often used to generate a sequence of numbers.

Iterating Over Strings:

# Example 3: Print each character in a string

message = “Hello, Python!”

for char in message:

    print(char)

# Output:

# H

# e

# l

# l

# o

# ,

#   (space)

# P

# y

# t

# h

# o

# n

# !

The for loop makes it easy to iterate over the characters of a string.

Working with Dictionaries:

# Example 4: Iterate over dictionary keys and values

person = {“name”: “John”, “age”: 30, “city”: “New York”}

for key, value in person.items():

    print(f”{key}: {value}”)

# Output:

# name: John

# age: 30

# city: New York

The for loop is used to iterate over key-value pairs in a dictionary.

Performing a Task Multiple Times:

# Example 5: Print “Hello” five times

for _ in range(5):

    print(“Hello”)

# Output:

# Hello

# Hello

# Hello

# Hello

# Hello

If you need to repeat a task a specific number of times, a for loop with range() is a concise way to achieve that.

The for loop simplifies the process of iteration and is a fundamental construct for handling repetitive tasks in Python programming. It enhances code readability and reduces the need for duplicate code.

Where we need use for loop in python with Example?

You might need to use a for loop in Python in various situations where you want to iterate over a sequence (such as a list, tuple, string, or dictionary) and perform a specific operation for each element in that sequence. Here are some common scenarios with examples:

Iterating Over a List:

# Example 1: Calculate the sum of numbers in a list

numbers = [1, 2, 3, 4, 5]

total = 0

for num in numbers:

    total += num

print(“Sum:”, total)

# Output:

# Sum: 15

Processing Elements in a String:

# Example 2: Count the number of vowels in a string

word = “hello”

vowel_count = 0

for char in word:

    if char in “aeiou”:

        vowel_count += 1

print(“Number of vowels:”, vowel_count)

 

# Output:

# Number of vowels: 2

Iterating Over a Range of Numbers:

# Example 3: Print numbers from 1 to 5

for i in range(1, 6):

    print(i)

# Output:

# 1

# 2

# 3

# 4

# 5

Working with Dictionaries:

# Example 4: Display key-value pairs in a dictionary

student_grades = {“Math”: 90, “Science”: 85, “English”: 88}

for subject, grade in student_grades.items():

    print(f”{subject}: {grade}”)

# Output:

# Math: 90

# Science: 85

# English: 88

Creating Patterns:

# Example 5: Print a simple pattern using a for loop

for i in range(5):

    print(“*” * (i + 1))

# Output:

# *

# **

# ***

# ****

# *****

Processing Each Element in a List of Objects:

# Example 6: Display information about each person in a list

people = [

    {“name”: “Alice”, “age”: 25},

    {“name”: “Bob”, “age”: 30},

    {“name”: “Charlie”, “age”: 22}

]

for person in people:

    print(f”{person[‘name’]} is {person[‘age’]} years old.”)

# Output:

# Alice is 25 years old.

# Bob is 30 years old.

# Charlie is 22 years old.

These examples illustrate situations where for loops are useful for iterating over sequences and performing specific tasks for each element. for loops provide a clean and concise way to handle repetitive operations in Python.

What is while loop in python with Example?

In Python, a while loop is used to repeatedly execute a block of code as long as a specified condition is true. The loop continues iterating as long as the given condition remains true. Here’s the basic syntax of a while loop:

while condition:

    # Code to be executed while the condition is true

Now, let’s look at an example:

Example 1: Simple while Loop

# Example 1: Simple while loop to print numbers from 1 to 5

count = 1

while count <= 5:

    print(count)

    count += 1

In this example, the while loop prints numbers from 1 to 5. The loop continues as long as the condition count <= 5 is true. The count variable is incremented in each iteration.

Example 2: User Input and Break

# Example 2: Use a while loop to get positive input from the user

while True:

    user_input = int(input(“Enter a positive number: “))

    if user_input > 0:

        break

    else:

       print(“Please enter a positive number.”)

In this example, the while loop continues indefinitely until the user enters a positive number. The break statement is used to exit the loop when a positive number is provided.

Example 3: Infinite Loop with Break

# Example 3: Create an infinite loop that breaks on user input

while True:

    user_choice = input(“Do you want to continue? (yes/no): “)

    if user_choice.lower() == “no”:

        break

    else:

        print(“Continuing…”)

This example demonstrates an infinite loop that continues until the user decides to stop by entering “no.” The break statement is used to exit the loop based on user input.

Example 4: Factorial Calculation

# Example 4: Calculate the factorial of a number using a while loop

number = int(input(“Enter a number: “))

result = 1

while number > 0:

    result *= number

    number -= 1

print(f”The factorial is: {result}”)

In this example, the while loop is used to calculate the factorial of a given number. The loop continues until the number reaches 0, multiplying the result by the current number in each iteration.

It’s important to be cautious when using while loops to avoid infinite loops. Ensure that the loop condition will eventually become false to allow the loop to exit.

Where we need use while loop in python with Example?

A while loop in Python is useful when you want to repeatedly execute a block of code as long as a certain condition is true. Here are some scenarios where you might need to use a while loop, along with examples:

Input Validation:

# Example 1: Ensure the user enters a positive number

user_input = 0

while user_input <= 0:

    user_input = int(input(“Enter a positive number: “))

print(f”You entered: {user_input}”)

This ensures that the user enters a positive number by repeatedly prompting them until a valid input is provided.

Menu-driven Programs:

# Example 2: Menu-driven program with a while loop

while True:

    print(“1. Option 1”)

    print(“2. Option 2”)

    print(“3. Exit”)

    choice = int(input(“Enter your choice: “))

       if choice == 1:

        print(“You selected Option 1”)

    elif choice == 2:

        print(“You selected Option 2”)

    elif choice == 3:

        print(“Exiting…”)

        break

    else:

        print(“Invalid choice. Try again.”)

# Example 3: Process elements in a list using a while loop

numbers = [1, 2, 3, 4, 5]

index = 0

while index < len(numbers):

    print(numbers[index])

    index += 1

While loops can be used to iterate over elements in a list manually, providing more flexibility in certain situations.

Game Loop:

# Example 4: Simple game loop

player_health = 100

while player_health > 0:

    print(f”Player health: {player_health}”)

    # Game logic here

    player_health -= 10

print(“Game over!”)

Game loops often use while to continuously update the game state until a certain condition (like player death) is met.

Condition-Based Execution:

# Example 5: Execute code while a condition is met

count = 0

while count < 5:

    print(f”Count: {count}”)

    count += 1

You might use a while loop when you want to execute code as long as a specific condition is true.

Remember to ensure that there is a mechanism within the loop to eventually make the condition false; otherwise, you might end up with an infinite loop. Using break statements or other control flow mechanisms can help ensure the loop terminates appropriately.

Why we need use while loop in python with Example?

A while loop in Python is useful in situations where you want to repeat a block of code as long as a certain condition is true. Unlike a for loop, which iterates over a sequence, a while loop is based on a condition that determines whether the loop should continue executing. Here are some reasons why you might need to use a while loop in Python, along with examples:

Input Validation:

# Example 1: Ensure the user enters a positive number

user_input = 0

while user_input <= 0:

    user_input = int(input(“Enter a positive number: “))

print(f”You entered: {user_input}”)

Here, the while loop ensures that the user enters a positive number. It continues to prompt the user until a valid input is provided.

Dynamic Conditions:

# Example 2: Keep asking a question until a specific answer is given

answer = “”

while answer.lower() != “yes”:

    answer = input(“Do you want to continue? (yes/no): “)

This example demonstrates a scenario where the loop continues until the user provides a specific response.

Unknown Number of Iterations:

# Example 3: Keep generating random numbers until a condition is met

import random

target_number = 7

guess = 0

while guess != target_number:

    guess = random.randint(1, 10)

    print(f”Guess: {guess}”)

print(“Correct guess!”)

In this example, the loop continues until a random guess matches the target number.

Game Loops:

# Example 4: Game loop for a simple guessing game

secret_number = 42

guess = 0

attempts = 0

while guess != secret_number:

    guess = int(input(“Enter your guess: “))

    attempts += 1

    if guess < secret_number:

        print(“Too low! Try again.”)

    elif guess > secret_number:

        print(“Too high! Try again.”)

print(f”Congratulations! You guessed the number in {attempts} attempts.”)

Game loops often use while to repeatedly update the game state until a specific condition (like winning the game) is met.

Looping Until a Certain Condition is Met:

# Example 5: Keep doubling a number until it exceeds a threshold

num = 1

threshold = 100

while num < threshold:

    print(num)

    num *= 2

The loop continues until the value of num exceeds the specified threshold.

While for loops are typically used when you know the number of iterations in advance, while loops are suitable when the number of iterations is unknown or when you need to repeatedly execute a block of code based on a dynamic condition. It’s important to be cautious with while loops to avoid unintentional infinite loops, and ensure that the loop condition will eventually become false.