The else
statement can also be used with loops, such as for
and while
loops, to execute a block of code after the loop has completed its iterations without any break
statements being encountered.
for i in range(5):
print(i)
else:
print("Loop completed without encountering a break statement")
In this case, the else
block will be executed only if the loop completes all its iterations without any early termination using the break
statement.
Note: the else
block is optional, and you can use it according to your specific programming needs.
Python for else example
Here are a few more examples of how the else
statement is used in Python:
Checking Prime Numbers
num = 17
if num > 1:
for i in range(2, num):
if num % i == 0:
print(num, "is not a prime number")
break
else:
print(num, "is a prime number")
else:
print(num, "is not a prime number")
In this example, we’re checking if a given num
is a prime number. The else
block is used with the for
loop to print whether the number is prime or not after completing all iterations.
Handling User Input
username = input("Enter your username: ")
if username == "admin":
print("Welcome, admin!")
else:
print("Welcome,", username)
This program asks the user for their username and uses the else
block to provide a customized welcome message based on the input.
Finding Factors
num = 28
factors = []
for i in range(1, num + 1):
if num % i == 0:
factors.append(i)
print("Factors of", num, "are:", factors)
Here, the else
block is not used, but this example shows how you might find factors of a number and create a list of those factors.
Using else
with a while
Loop
count = 0
while count < 5:
print("Count:", count)
count += 1
else:
print("Loop completed")
Output:
In this example, the else
block is executed when the while
loop completes all iterations without any break
statement.
These examples should help you understand how the else
statement is used in various contexts in Python to handle different scenarios.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.