For Else | Basics of Python - Software Development PDF Download

Introduction

Python is a powerful and flexible programming language that offers various control flow statements to handle different situations. One such statement is the "for...else" loop. In this article, we will explore the "for...else" statement and understand its purpose, syntax, and usage in Python.

Purpose of the "for...else" Statement

The "for...else" statement provides a way to execute a block of code when a "for" loop completes normally, without encountering a "break" statement. It allows us to perform certain actions or handle specific conditions after iterating through all the items in an iterable.

Syntax

The syntax for the "for...else" statement in Python is as follows:

for item in iterable:

    # Code block to be executed in each iteration

    # ...

else:

    # Code block to be executed when the loop completes without encountering a 'break' statement

    # ...

  • The 'item' represents an individual element from the iterable in each iteration.
  • The 'iterable' can be a list, tuple, string, or any other iterable object.

Usage and Examples


Example 1: Finding an Element in a List

Let's say we want to find whether a specific element exists in a list. We can use the "for...else" statement to iterate through the list and perform actions based on the search result.

fruits = ["apple", "banana", "orange", "kiwi"]

# Check if 'orange' is present in the list

for fruit in fruits:

    if fruit == "orange":

        print("Found 'orange' in the list.")

        break

else:

    print("Did not find 'orange' in the list.")

# Output:

# Found 'orange' in the list.

In this example, the loop iterates through each fruit in the 'fruits' list. When it encounters the element "orange," it prints a message and breaks out of the loop. If the loop completes without finding "orange," the else block is executed, indicating that the element was not found in the list.

Example 2: Checking Prime Numbers

Let's use the "for...else" statement to check if a given number is prime.

def is_prime(number):

    if number <= 1:

        return False

    for i in range(2, number):

        if number % i == 0:

            return False

    else:

        return True

# Check if a number is prime

num = 17

if is_prime(num):

    print(f"{num} is a prime number.")

else:

    print(f"{num} is not a prime number.")

# Output:

# 17 is a prime number.

In this example, the function 'is_prime()' checks if a number is prime by iterating from 2 to the given number ('number'). If the number is divisible by any value in the range, it returns 'False'. If the loop completes without finding a divisor, it returns 'True'. We use the "for...else" statement to handle both cases accordingly.

Sample Problems

Problems 1: Write a program to find the first occurrence of a negative number in a given list. If no negative number is found, print a message saying "No negative number found."

numbers = [1, 2, -5, 4, 6, 7]

for num in numbers:

    if num < 0:

        print("Found a negative number:", num)

        break

else:

    print("No negative number found.")

# Output:

# Found a negative number: -5

Problems 2: Create a function to check if a given string is a palindrome. Print "Palindrome" if it is, and "Not a palindrome" otherwise.

def is_palindrome(string):

    if string == string[::-1]:

        return True

    else:

        return False

word = "radar"

if is_palindrome(word):

    print("Palindrome")

else:

    print("Not a palindrome.")

# Output:

# Palindrome

Problems 3: Given a list of numbers, find the sum of all the even numbers. If there are no even numbers, print "No even numbers found."

numbers = [1, 3, 5, 7]

sum_even = 0

for num in numbers:

    if num % 2 == 0:

        sum_even += num

if sum_even != 0:

    print("Sum of even numbers:", sum_even)

else:

    print("No even numbers found.")

# Output:

# No even numbers found.

Conclusion

The "for...else" statement in Python provides a useful way to execute a block of code when a "for" loop completes normally, without encountering a "break" statement. By understanding its syntax and examples, you can now incorporate this statement into your Python programs and handle various scenarios effectively.

The document For Else | Basics of Python - Software Development is a part of the Software Development Course Basics of Python.
All you need of Software Development at this link: Software Development
49 videos|38 docs|18 tests

Top Courses for Software Development

49 videos|38 docs|18 tests
Download as PDF
Explore Courses for Software Development exam

Top Courses for Software Development

Signup for Free!
Signup to see your scores go up within 7 days! Learn & Practice with 1000+ FREE Notes, Videos & Tests.
10M+ students study on EduRev
Related Searches

ppt

,

Viva Questions

,

pdf

,

practice quizzes

,

Summary

,

Objective type Questions

,

video lectures

,

shortcuts and tricks

,

For Else | Basics of Python - Software Development

,

MCQs

,

Extra Questions

,

past year papers

,

Semester Notes

,

For Else | Basics of Python - Software Development

,

Exam

,

Free

,

mock tests for examination

,

Sample Paper

,

Previous Year Questions with Solutions

,

For Else | Basics of Python - Software Development

,

Important questions

,

study material

;