Table of contents | |
Introduction | |
Purpose of the "for...else" Statement | |
Syntax | |
Usage and Examples | |
Sample Problems |
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.
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.
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
# ...
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.
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.
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.
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.
49 videos|38 docs|18 tests
|
|
Explore Courses for EmSAT Achieve exam
|