HudaTutorials.com

Python Looping Statements

Last updated on

Looping Statements in Python

Python Loops

Loops in Python

Looping statements in Python are used to execute a block of statements repeatedly until a given condition in a loop is satisfied.

How Many Types of Looping Statements in Python ?

There are two types of looping statements in Python. Following are the list of looping statements in Python.

  • for loop
  • while loop

What is while Loop in Python ?

The while loop in Python is used to execute a block of statements repeatedly until a given condition in a while loop is satisfied. In other words the while loop we can execute a set of statements as long as a condition is true.

The while keyword is used to create a while loop. The statements inside a while loop continue to execute until the condition for the while loop evaluates to False or a break statement is encountered.

Python while Loop Example

# WHILE LOOP EXAMPLE
x = 1
while x <= 10:
    print(x)
    x = x + 1

Python while Loop with else

Python while loop also has an optional else block. The else part of while loop is executed, if the condition in the while loop evaluates to False.

The while loop can be terminated with a break statement. In such cases, the else part is ignored. The while loop else part runs if no break occurs and the condition is false. You can read more about Python branching statements.

Python while Loop with else Example

# WHILE LOOP WITH ELSE EXAMPLE
 
while_loop_counter = 0
 
while while_loop_counter > 7:
    print("Inside while loop")
    while_loop_counter = while_loop_counter + 1
else:
    print("Inside while loop with else")

What is for Loop in Python ?

The for loop is used for iterating over a sequence either a list, a tuple, a dictionary, a set, or a string. The for keyword is used to create a for loop.

We use for when we know the number of times we want to loop. In Python for keyword is used to iterate through a sequence, list and tuple.

Python for Loop Example

# FOR KEYWORD EXAMPLE
# FOR LOOP EXAMPLE
for i in range(1, 11):
    print(i)

Python for Loop Example with Array

# PYTHON FOR LOOP EXAMPLE WITH ARRAY
numbers_array = [7, 2, 9, 1, 3]
for i in numbers_array:
    print(i)

Python Looping Through String using for Loop

Strings are iterable objects in Python. They contain a sequence of characters. So we can loop through string in Python.

Python Looping Through String using for Loop Example

# LOOPING THROUGH STRINGS USING FOR LOOP EXAMPLE
for c in "I like Apple":
    print(c)

Python for Loop with else

The else keyword in a for loop specifies a block of code to be executed when the loop is finished successfully.

Python for Loop with else Example

# PYTHON FOR LOOP WITH ELSE EXAMPLE
numbers_array = [7, 2, 9, 1, 3]
for i in numbers_array:
    print(i)
else:
    print("Numbers Printed Successfully")