Master Control Statements in Python with Examples (Updated 2025)

Harika Last Updated : 04 Dec, 2024
8 min read

Introduction

This article is a Python tutorial to help you learn the fundamentals of Loops and Control Statements in python with plenty of practice exercises. Loops are an essential part of any programming course, be it Python, Java, Javascript or PHP, etc. Using while loops are essential in data science and python interview questions. In machine learning, python loop control statement are useful for iterating over large datasets, running algorithms multiple times with different parameters, and automating repetitive tasks. Loops in Python programming language allow programmers to process data efficiently and concisely and perform iterations.

Control Statements in Python and Their Importance

In a programming language, a loop is a statement that contains instructions that continually repeat until a certain condition is reached.

Loops help us remove the redundancy of code when a task has to be repeated several times. With the use of loops, we can cut short those hundred lines of code to a few. Suppose you want to print the text “Hello, World!” 10 times. Rather than writing a print statement 10 times, you can use loops by indicating the number of repetitions needed.

hello world loop

Python Loop Types

The three types of loops in Python programming are while loop control statement, for loop control statement, and nested loop control statement.

While Loop

It continually executes the statements (code) as long as the given condition is TRUE. It first checks the condition and then jumps into the instructions. While loops can be used inside python functions also.

Syntax:

while condition:
    statements(code)

Inside the while loop, the statement (code) can be a single statement or a block of statements. The condition may be anything per our requirement, and we can use if, elif, or else in the code. The loop stops running when the condition fails (become false), and the execution will move to the next line of code. Indentation (also called white space) is necessary while defining a statement or code to be executed. Indentation is used to specify program structure and to group statements together in blocks.

Flow Diagram for While Loop

flow diagram while loop | Control Statements in Python

Image 1

It first checks the condition, executes the conditional code if it is TRUE, and checks the condition again. Program control exits the loop if the condition is FALSE.

Example 1: Print the text “Hello, World!” 5 times.

num_of_times = 1

while num_of_times <= 5:
  print("Hello, World!")
  num_of_times += 1

Explanation: The loop control statement runs as long as the num_of_times variable is less than or equal to 5. num_of_times increments by 1 after each iteration.

(if you are a beginner, use the Thonny IDE to see the step-by-step execution)

Output:

output while loop | Loops and Control Statements

Example 2: Create a list of all the even numbers between 1 and 10

num = 1
even_numbers = []
while num <= 10:
if num % 2 == 0:
even_numbers .append(num)
num += 1
print("Even Numbers list: ", even_numbers )

Explanation: The loop runs as long as the condition is true, i.e., the num variable is less than or equal to 10. If the condition is TRUE, the program control enters the loop and appends the num to the even_numbers list if the number is cleanly divisible by 2.

Output: 

even number list | Loops and Control Statements

Example 3: Creating an infinite loop

A loop runs infinite times when the condition never fails to meet. We can assign a boolean value like True or False to a variable to make a condition. Here in the example, we are assigning True to variable1; the program control will keep executing the code until our variable is true.

i = True
while i:
    print("Condition satisfied")

Output:

infinite loop | Control Statements in Python

Example 4: use else with a while loop

When an else statement is used along with a while loop, the control goes to the else statement when the condition is False.

  • var = 1
  • while var <= 4:
  • print(f”Condition is TRUE: {var} <= 4″)
  • var += 1
  • else:
  • print(f”Condition is FALSE: {var} > 4″)

Output:

else with while loop | Control Statements in Python

For Loop

A python for loop control statement is used to iterate over data structures like python lists, arrays, dictionaries, sets, tuples or even strings.

Loop statements will be executed for each item of the sequence.

Syntax of for loop:

for item in iterator:
    statements(code)

Flow Diagram of For Loop

flow diagram while loop | Control Statements in Python

Image 2 

Takes the first item of the iterable, executes the statement and moves the pointer to the next item until it reaches the last item of the sequence.

Example 1: Print the text “Hello, World!” 5 times.

list = [1, 2, 3, 4, 5]
for num in list:
    print("Hello, World!")

The variable num is not used in the code so that we can use the below syntax (use underscore):

list = [1, 2, 3, 4, 5]
for _ in list:
    print("Hello, World!")

Output:

output while loop

Example 2: Create a list of all the even numbers between 1 and 10

(using the range function to return a sequence of numbers from 1 to 10. Read more about it here)

even_nums = []
for i in range(1, 11):
    if i % 2 == 0:
        even_nums.append(i)
print("Even Numbers: ", even_nums)

Output:

if in for loop

Example 3: Creating an infinite loop

An infinite loop can be created using a loop by appending a new element to the list after every iteration.

num = [0]
for i in num:
    print(i)
    num.append(i+1)

Output: infinite output

Example 4: use else with a for loop

iterator = (1, 2, 3, 4)
for item in iterator:
    print(item)
else:
    print("No more items in the iterator")

Output:

else with a for loop

Example 5: Display the items in a dictionary

example = {
    'iterator': 'dictionary',
    'loop': 'for',
    'operation': 'display dictionary elements'
}
for key in example:
    print(f"{key}: {example[key]}")

The key value of a dictionary can be directly accessed using .items()

for key, value in example.items():
print(f"{key}: {value}")

Output:

for loop example | Loops and Control Statements in Python

Nested Loops

Nested loops mean using a loop inside another loop. We can use any type of loop inside any type of loop. We can use a while loop inside for loop, a for loop inside a while loop, a while loop inside a while loop, or a for loop inside a for  loop.

nested loops | Loops and Control Statements in Python

Image by Author

Example: Create a list of even numbers between 1 and 10

even_list = []
for item in range(1, 11):
    while item % 2 == 0:
        even_list.append(item)
        break
print("Even Numbers: ", even_list)

Output:

sample output | Loops and Control Statements

Loop Control Statements in Python

Loop control statements are used to change the flow of execution. These can be used if you wish to skip an iteration or stop the execution.

The three types of loop control statements in python are break statement, continue statement, and pass statement.

Break Statement

Based on the given condition, the break statement stops the execution and brings the control out of the loop. There can be many cases when a break statement can be used. For example, if we want to stop the execution when an item is of a certain datatype (int, dict or str, etc.) or if it equals a certain value, we can use the break statement.

Example: Create a list of the odd numbers between 1 and 20 (use while, break)

num = 1
odd_nums = []
while num:
    if num % 2 != 0:
        odd_nums.append(num)
    if num >=20:
        break
    num += 1
print("Odd numbers: ", odd_nums)

Example: Stop the execution if the current number is 5 (use for, break)

for num in range(1, 11):
    if num == 5:
        break
    else:
        print(num)

Continue Statement

The Continue statement is used to skip the current iteration when the condition is met and allows the loop to continue with the next iteration. It does not bring the control out of the loop and unline the break statement.

Example: Skip the iteration if the current number is 6 (use while, continue)

num = 0
while num < 10:
    num += 1
    if num == 6:
        continue
    print(num)

Example: Skip the iteration if the current number is 6 (use for, continue)

for num in range(1, 11):
    if num == 6:
        continue
    print(num)

Pass Statement

A Pass statement is used when we want to do nothing when the condition is met. It doesn’t skip or stop the execution; it just passes to the next iteration. Sometimes we use comment which is ignored by the interpreter. Pass is not ignored and can be used with loops, functions, classes, etc.

It is useful when we do not want to write functionality at present but want to implement it in the future.

Example: while, pass statement

num = 1
while num <= 10:
    if num == 6:
        pass
    print(num)   
    num += 1

Example: for, pass statement

for num in range(1, 11):
    if num == 6:
        pass
    print(num)

As an exercise, run the code snippets and see how the control statements in python work.

Conclusion

In Python, Loops are used to iterate repeatedly over a block of code. To change the way a loop is executed from its usual behavior, we use control statements in python. Control statements are used to control the flow of the execution of the loop based on a condition.

A loop repeats a sequence of instructions until a specific condition is met. Loops allow you to repeat a process over & over without having to write the same instructions each time you want your program to perform a task.

Key Takeaways

  • There are two types of loops in python: for loop and while loop.
  • For loops are used to iterate over a data structure or sequence of elements, such as a list, string, or dictionary, and execute a block of code for each element in the sequence. On the other hand, while loops are used to repeat a block of code until a certain condition is met.
  • The “break” statement is used to exit a loop, while the “continue” statement skips the current iteration and continues with the next iteration.

Frequently Asked Questions

Q1. What is the difference between a “for” loop and a “while” loop in Python?

A. The main difference is how the flow of execution is controlled. A “for” loop is used to iterate over a sequence of elements. The loop automatically increments the index and terminates when all elements have been processed.
On the other hand, a “while” loop is used to repeat a block of code as long as a condition is met. The condition is checked at the start of every iteration, and the loop continues to execute as long as the condition remains true.

Q2. How does the break statement work in a Python loop?

A. The break statement is used to exit a loop (for loop or while loop) in Python. When the break statement is executed within a loop, the loop terminates immediately, and the program moves on to execute the next line of code.

Q3. How do you prevent infinite loops in Python?

A. To prevent infinite loops in Python, it’s important to ensure that the loop condition can eventually become false. For example, we can use a counter to keep track of the number of iterations using a variable and include a condition in the loop that causes it to stop.

Hi, my name is Harika. I am a Data Engineer and I thrive on creating innovative solutions and improving user experiences. My passion lies in leveraging data to drive innovation and create meaningful impact.

Responses From Readers

Clear

Janaka
Janaka

Harlika actually a great tutorial i appreciated this you did a nice work so happy i got a lot of knowledge ....! Thanks

We use cookies essential for this site to function well. Please click to help us improve its usefulness with additional cookies. Learn about our use of cookies in our Privacy Policy & Cookies Policy.

Show details