How to use for loop in Python with break statement

How to use for loop in Python 

Python For Loops

A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string). This is less like the for keyword in other programming languages, and works more like an iterator method as found in other object-orientated programming languages.

How to use for loop in Python

Python Features Highlights 

  • Python-For Loops
  • Looping Through a String
  • The break Statement
The for loop we can execute a set of statements, once for each item in a list, tuple, set etc. Also check How to Find the Square Root using Python Program

Example


Print each city in a city list:
city = ["salem", "chennai", "Bangalore"]
for x in city:
  print(x)

Looping Through a String

Even strings are iterable objects, they contain a sequence of characters:

Example

Loop through the letters in the word "chennai":
for x in "chennai":
  print(x)

The break Statement

With the break statement we can stop the loop before it has looped through all the items:


Example

Exit the loop when x is "chennai":

city = ["salem", "chennai", "Bangalore"]
for x in city:
  print(x)
  if x == "chennai":
    break

If you any doubts, Please let me know

Previous Post Next Post

Contact Form