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?
Submitted by IncludeHelp, on May 09, 2020

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

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.

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.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.