Scripting

Python For Loops

Python For Loops

Introduction

There are 3 ways to implement loops to help with looping requirements in Python. They have the same function but different syntax and conditions.

In this article, we want to introduce you to the for loop. The for loop iterates through a sequence (a list, a dictionary, a string,…) sequentially.

And we will show you how to use the for loop in Python as you go through it below. Hope you understand.

Example

list = ["cat", "dog", "tiger"]

for x in list:

print(x)

Output:

cat

dog

tiger

Definition

The for loop iterates through a string sequentially.

The for loop doesn’t need a variable reservation.

Loop with string

We will try repeating the letters of the word “tiger”:

for x in "tiger":

print(x)

Output:

t

i

g

e

r

for loop with break statement

break statement allows stopping at the position we want.

Example 1: Exit the loop when x runs to “dog”

list = ["cat", "dog", "tiger"]

for x in list:

print(x)

if x == "dog":

break

Output:

cat

dog

Example 2: Exit the loop when x has not reached the “dog”

list = ["cat", "dog", "tiger"]

for x in list:

if x == "dog":

break

print(x)

Output:

cat

for loop with continue statement

continue statement allows to stop at the current position and continue at the next position.

Example: Don’t print “dog”

list = ["cat", "dog", "tiger"]

for x in list:

if x == "dog":

continue

print(x)

Output:

cat

tiger

for loop with pass statement

The for loop cannot be empty, but if for some reason we want to skip the loop with no content without error, then use the pass statement.

Example:

for x in [4, 5, 6. 7]:

pass

Conclusion

Hope you understood the tutorial on how to use the for loop in Python.

Thanks for reading!

Similar Posts