×

Python Control Flow Statements

This article aims to introduce you to what control flow statements are in general and Control Flow Statements in Python programming Language, the Importance of control flow statements and look into different control statement structures like Sequential, Repetition, and Selection with examples of each structure written in Python programming language along with self-explanatory comments in the code that we will be writing.

Control Flow Statements

Programming Languages Control flow is the order in which the Program or the code we have written executes in a particular order. The Control in Programming languages differs in many ways; for instance, here in our Python Programming Language, the Control Flow is regulated by Function calls that the code does, loops like for loop, while loop, do-while loop, nested loops and also by Conditional statements.

Importance of Control Statements

The Control Flow Statements will let you give the power to have control over the flow of execution of the code that we write. In Python Programming Language or any programming language in general, the flow of an implementation of the code can be controlled by placing the looping, branching, decision making and adding some additional blocks to the code we write. It is essential to have the control flow statements because the code we write in a particular file, the flow of execution generally flows top to bottom. Still, with the help of control flow statements, we can now control certain decisions, perform tasks that require frequent repetition or jump from a specific part of a different section if needed.

The three most important types of Control Structures that we have in Python Programming Language are

  1. Sequential – it is the default mode.
  2. Repetition is generally used for looping, which means repeating a particular condition multiple times by the same piece of code.
  3. Selection – Its primary purpose is branching out code and making decisions.

Sequential Control Flow Statements

The Sequential Control Flow Statements are the by-default flow of execution statements. The flow of execution generally happens from top to bottom, and the problem with them is if the logic that we have written in the code breaks, then the complete source code file execution might break, which may cause a throwing error.

Code

## This is a Sequential statement example
 
a=20233
b=1033
c=a-b
print("Subtraction is of a-b is : ",c)

Output

Subtraction is of a-b is:  19200

Selection/Decision Control Flow Statements

In Python Programming Language, the Selection statements are also known as the branching or decision-making statements allowing us to make the code that we write go through the pass a variety of checks in between and will only execute if the condition is true

Selection Control Statements are:

If-else

Code

variety of checks in between Code
nn = 500
if nn % 2 == 0:
   print("nn is even")
else:
   print("nn is odd")

Output

nn is even

Simple if

Code

nn = 100
if nn % 2 == 0:
   print("this is an even number")

Output

this is an even number

If-elif-else

Code

x = 1500
y = 122212
if x == y:
   print("Both are Equal")
elif x > y:
    print("x is greater than y")
else:
    print("x is smaller than y")

Output

x is smaller than y

Nested if

Code

x = 1500
y = 122212
if x == y:
   print("Both are Equal")
elif x > y:
    print("x is greater than y")
else:
    print("x is smaller than y")

Output

c is bigger here

Repetition Control Flow Statements

As we have already discussed in the introduction, the Repetition Control Flow Statements are used to repeat a specific code multiple times or stop writing a particular code more times; we prefer the repetition statement where the loop passes through the statement and does the work for us.

Types of repetitive statements

For loop

Code

list_example = [1, 2, 3, 4, 5]
for i in range(len(list_example)):
     print(list_example[i], end = " ")
 
for j in range(0,10):
    print(j, end = " ")

Output

1 2 3 4 5 0 1 2 3 4 5 6 7 8 9

While loop

Code

m = 105
i = 100
while i < m:
     print(i, end = " ")
     i = i + 1
print("Ending now")

Output

100 101 102 103 104 Ending now

Related Topics

Anaconda in Python 3

What is Anaconda in Python 3? Anaconda is an open-source package combining Python and R programming languages used for data analytics and processing data. It consists of a huge number of...

4 minutes read.

Python String expandtabs() method

Python String expandtabs() method The string.expandtabs() method in Python returns a copy of the string where all tab characters are expanded using spaces. Syntax String.expandtabs([tabsize]) Parameter tabsize: This parameter specifies the number of characters to...

1 minute read.

Operator Module In Python

Introduction The operator module is used for performing operations using methods rather than utilizing operators in Python code. The operator module provides several methods for performing the operations.  The operator module contains...

7 minutes read.

Rank Based Percentile GUI Calculator using PyQt5 in Python

PyQt5: PyQt5 is one of several solutions that Python offers for creating GUI applications. Cross-platform GUI toolkit PyQt5 is a collection of Python interfaces for Qt version 5. With the capabilities...

3 minutes read.

Python String isspace() method

Python String isspace() method The string.isspace() method returns a Boolean value true if there are only whitespace characters in the given string. This function is used to check if the given...

2 minutes read.

Python String lstrip() method

Python String lstrip() method The string. lstrip () method in Python returns a copy of the string with leading characters removed (based on the string argument passed). Syntax string.lstrip([chars]) Parameter chars(optional): This parameter represents a...

1 minute read.

Raise Exception in Python

Most of the programmers/developers create large programs to solve complex tasks in Python. The code can be of 1000 lines and even more based on the need of the problem....

5 minutes read.

How To Print Colored Text in Python

Changing the colour of certain parts of a string when printing the output of a Python programme to the terminal may make it easier to read. We can approach this...

3 minutes read.

Python List clear() method

Python List clear() method The list.clear () method in Python extends the list by appending all the items from the iterable. Syntax list.clear() Parameter NA Example 1 # Python Program explaining # the list.clear() method week_list = ["Monday", "Tuesday", "Wednesday","Thursday","Friday",...

1 minute read.

Python String index() method

Python String index() method The string.index() method in Python finds the lower index of the first occurrence of the specified value or raise a ValueError if the substring is not found. Syntax index(sub[, start[, end]]) Parameter sub:...

2 minutes read.

Python TCP Server

The TCP server library is also known as the socket library. Socket programming is the method of connecting two nodes through a network to form communication between two nodes. In...

3 minutes read.

Writing to Excel using Python

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses...

3 minutes read.

Python Typing Module

An Introduction to the Typing Module The typing module is introduced in Python version 3.5 and used to provide hinting method types in order to support static type checkers and linters...

10 minutes read.

Add a key-value pair to dictionary in Python

In programming, data type defines the type of value that a variable can hold. With help of these, we can perform various mathematical, logical, or relational operations on that particular...

5 minutes read.

Python TypeError

What is TypeError in python? TypeError is one of the exceptions in the python programming language. This exception occurs when an operation is performed on an unsupported object type or can...

6 minutes read.

Python Linked List

Linked List Linked lists non-contiguous linear data structure which is made up of nodes and used to store value and a pointer pointing to the next node. It is linked with...

6 minutes read.

Python Encapsulation

What is meant by Encapsulation? The process of restricting access to the methods and variables so that accidental modification of data can be prevented is known as Encapsulation. The motive of Encapsulation:...

3 minutes read.

How to create a class in python

In any programming language, a class is a user-defined plan or blueprint using which objects or instances of the class are created. You may wonder why we need classes in programming....

5 minutes read.

Function annotations() in Python

What is Function Annotations? Function annotations provide a way related to different parts of a function at compile time with arbitrary Python expressions. It doesn’t have life in Python runtime execution....

3 minutes read.

Python variance() function

Variance The variance is the average of the square deviations from the mean. The variance will measure the spread of the dataset from its mean or median value. The greater the...

4 minutes read.