else with for/while statement in Python

Python| else with for/while statement: Here, we are going to learn how can we use else statement with for and while statements in Python programming language? By IncludeHelp Last updated : December 18, 2023

As we know that else can be used with if statement in Python and other programming languages (like C, C++, Java, etc).

Python else with for/while statement

In Python, we can use else with for/while to determine whether for/while loop is terminated by a break statement or not i.e. else statement used with for/while is executed only when for/while is not terminated by break statement.

Syntax

The syntax of the else statement with for/while is:

while condition:
    # returning True or False
    STATEMENTs BLOCK 1
else: 
    # optional part of while
    STATEMENTs BLOCK 2
For TARGET- LIST in EXPRESSION-LIST:
    STATEMENT BLOCK 1
else: # optional block
    STATEMENT BLOCK 2

Python else with for/while statement: Examples

Practice the below-given examples to understand the concept of using the else statement with a while/for loop.

Example 1

# python program to demosntrate
# example of "else with for/while"

# using else with for
for num in range(1, 10):
  print(num)
else:
  print("Full loop successfully executed")


# using else with while
string = "Hello world"
counter = 0
while(counter < len(string)):
  print(string[counter])
  counter += 1
else:
  print("Full loop successfully executed")

Output

1
2
3
4
5
6
7
8
9
Full loop successfully executed
H
e
l
l
o
 
w
o
r
l
d
Full loop successfully executed

Example 2

# python program to demosntrate
# example of "else with for/while"

# using else with for
for num in range(1, 10):
  print(num)
  if(num==5):
    break
else:
  print("Full loop successfully executed")


# using else with while
string = "Hello world"
counter = 0
while(counter < len(string)):
  print(string[counter])
  if string[counter] == ' ':
    break
  counter += 1
else:
  print("Full loop successfully executed")

Output

1
2
3
4
5
H
e
l
l
o
 

Consider both of the above examples, when we used a break statement – else statement is not executed and we didn't use break statement – else statement is executed.

Python Tutorial

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.