PYnative

Python Programming

  • Learn Python
  • Exercises
  • Quizzes
  • Code Editor
  • Tricks
Home » Python » Python Control Flow Statements and Loops

Python Control Flow Statements and Loops

Updated on: March 18, 2021 | Python Tags: Basics Python

TweetF  sharein  shareP  Pin

In Python programming, flow control is the order in which statements or blocks of code are executed at runtime based on a condition.

Also See:

  • Python If-else and Loops Exercise
  • Python if else and Loops Quiz

Table of contents

  • Control Flow Statements
    • Conditional statements
    • Iterative statements
    • Transfer statements
  • If statement in Python
    • If – else statement
    • Chain multiple if statement in Python
    • Nested if-else statement
    • Single statement suites
  • for loop in Python
    • Nested for loop
    • for loop with else block
    • Reverse for loop
      • Reverse for loop using range()
      • Reverse for loop using reversed() function
  • While loop in Python
    • While loop example to calculate the sum of first ten numbers
    • Nested while loop
  • Break statement in Python
  • Continue statement in python
  • Pass statement in Python

Control Flow Statements

The flow control statements are divided into three categories

  1. Conditional statements
  2. Iterative statements.
  3. Transfer statements
Python control flow statements
Python control flow statements

Conditional statements

In Python, condition statements act depending on whether a given condition is true or false. You can execute different blocks of codes depending on the outcome of a condition. Condition statements always evaluate to either True or False.

There are three types of conditional statements.

  1. if statement
  2. if-else
  3. if-elif-else
  4. nested if-else

Iterative statements

In Python, iterative statements allow us to execute a block of code repeatedly as long as the condition is True. We also call it a loop statements.

Python provides us the following two loop statement to perform some actions repeatedly

  1. for loop
  2. while loop

Let’s learn each one of them with the examples

Transfer statements

In Python, transfer statements are used to alter the program’s way of execution in a certain manner. For this purpose, we use three types of transfer statements.

  1. break statement
  2. continue statement
  3. pass statements

If statement in Python

In control statements, The if statement is the simplest form. It takes a condition and evaluates to either True or False.

If the condition is True, then the True block of code will be executed, and if the condition is False, then the block of code is skipped, and The controller moves to the next line

Syntax of the if statement

if condition:
     statement 1
     statement 2
     statement n
Python if statements
Python if statements

Let’s see the example of the if statement. In this example, we will calculate the square of a number if it greater than 5

Example

number = 6
if number > 5:
    # Calculate square
    print(number * number)
print('Next lines of code')

Output

36
Next lines of code

If – else statement

The if-else statement checks the condition and executes the ‘if’ block of code when the condition is True, and if the condition is False, it will execute the else block of code.

Syntax of the if-else statement

if condition:
    statement 1
else:
    statement 2

If the condition is True, then statement-1 will be executed If the condition is False, statement-2 will be executed. See the following flowchart for more detail.

Python if else statements
Python if else statements

Example

def password_check(password):
    if password == "PYnative@#29":
        print("Correct password")
    else:
        print("Incorrect Password")

password_check("PYnative@#29")
# Output Correct password

password_check("PYnative29")
# Output Incorrect Password

Chain multiple if statement in Python

In Python, the if-elif-else condition statement has an elif keyword used to chain multiple conditions one after another. The if-elif-else is useful when you need to check multiple conditions.

With the help of if-elif-else we can make a tricky decision. The elif statement checks multiple conditions one by one and if the condition fulfills, then executes that code.

Syntax of the if-elif-else statement:

if condition-1:  
     statement 1 
elif condition-2:
     stetement 2 
elif condition-3:
     stetement 3 
     ...         
else:            
     statement   

Example

def user_check(choice):
    if choice == 1:
        print("Admin")
    elif choice == 2:
        print("Editor")
    elif choice == 3:
        print("Guest")
    else:
        print("Wrong entry")

user_check(1)  # Admin
user_check(2)  # Editor
user_check(3)  # Guest
user_check(4)  # Wrong entry

Nested if-else statement

In Python, Nested-if-else statement is an if statement inside another if-else statement. It is allowed in Python to put any number of if statements in another if statement.

Indentation is the only way to differentiate the level of nesting. The nested-if else is useful when we want to make a series of decisions.

Syntax of the nested-if-else:

if conditon_outer:
    if condition_inner:
        statement of nested if
    else:
        statement of nested if else:
    statement ot outer if
else:
    Outer else 
statement outside if block

Example

def number_arithmetic(num1, num2):
    if num1 >= num2:
        if num1 == num2:
            print(f'{num1} and {num2} are equal')
        else:
            print(f'{num1} is greater than {num2}')
    else:
        print(f'{num1} is smaller than {num2}')

number_arithmetic(56, 15)
# Output 56 is greater than 15
number_arithmetic(56, 56)
# Output 56 and 56 are equal

Single statement suites

Whenever we write a block of code with multiple if statements, indentation plays an important role. But sometimes, there is a situation where the block contains only a single line statement.

Instead of writing a block after the colon, we can write a statement immediately after the colon.

Example

number = 56
if number > 0: print("positive") 
else: print("negative")

Similar to if statement, while loop also consists of a single statement, we can place that statement on the same line.

Example

x = 1
while x <= 5: print(x,end=" "); x = x+1

Output

1 2 3 4 5

for loop in Python

Using for loop, we can iterate over output provide by any sequence or iterable variable. The sequence can be string, list, dictionary, set, or tuple.

Syntax of for loop:

for element in sequence:
     body of for loop   

See the following flowchart for more detail.

Python for loop
Python for loop

Example to display first ten numbers using for loop

for i in range(1, 11):
    print(i)

Output

1
2
3
4
5
6
7
8
9
10

Example to iterate a list using for loop

my_list = [42, 61, 47, 46, 91, 18]
for i in my_list:
    print(i)

Output

42
61
47
46
91
18

Nested for loop

Nested for is nothing but a for loop inside another for a loop.

Syntax of nested for loop:

# outer for loop
for element in sequence 
   # inner for loop
   for element in sequence:
       body of inner for loop
   body of outer for loop
other statements

Let’s use the nested for loop to print the following pattern

*
* *
* * *
* * * *
* * * * *

Example

rows = 5
for i in range(1, rows + 1):
    for j in range(1, i + 1):
        print("*", end=" ")
    print('')

for loop with else block

In Python, for-loop can have else block, which will be executed when the loop terminates normally. Defining else part with for loop is optional.

else block will be skipped when

  • for loop terminate abruptly
  • the break statement is used to break the loop

Syntax

for element in sequence
   if condition:
      statement-1
else:
   else block statement-2

Example 1

list1 = [10, 2, 1, 9, 5]
num = 10
for i in list1:
    if i == num:
        print(num, "is present in given list")
        break
else:
    print(num, "is  not present in given list")

Output

10 is present in given list

As you can see in the output else block is not executed because we used the break statement to break the loop abruptly.

Example 2

list1 = [10, 2, 1, 9, 5]
for i in list1:
    print(i, end=", ")
else:
    print("\nfor loop executed normally")

Output

10, 2, 1, 9, 5, 
for loop executed normally

Reverse for loop

Sometimes we require to do reverse looping, which is quite useful. For example, you wanted to reverse a list.

Reverse for loop can be done in 2 ways:

  1. Reverse for loop using range()
  2. Reverse for loop using the reversed() function
Reverse for loop using range()

We can use the built-in function range() with the for loop to reverse the elements’ order.

The range() generates the integer numbers between the given start integer to the stop integer.

Example

print("Reverse numbers using for loop")
num = 5
# start = 5
# stop = -1
# step = -1
for num in (range(num, -1, -1)):
    print(num)

In the above example, we give a start as last number and end as -1 that is accessing in backword direction, with step -1.

Output

Reverse numbers using for loop
5
4
3
2
1
0

Reverse for loop using reversed() function

We can use the built-in function reversed() with for loop to change the order of elements, and this is the simplest way to perform a reverse looping

Example

# Reversed numbers using reversed() function
list1 = [10, 20, 30, 40]
for num in reversed(list1):
    print(num)

Output

40
30
20
10

Practice Problem: –

Use for loop to generate a list of numbers from 9 to 50 divisible by 2.

Show Solution
for i in range(9, 100, 2):
    print(i)

While loop in Python

In Python, while-loop is used to executed iteratively as long as the expression/condition is True. In a while-loop, every time the condition is checked at the beginning of the loop, and if it is true, then the loop’s body gets executed. When the condition became False, the controller comes out of the block.

Python while loop
Python while loop

Syntax of while-loop

while condition :
    body of while loop

While loop example to calculate the sum of first ten numbers

num = 10
sum = 0
i = 1
while i <= num:
    sum = sum + i
    i = i + 1
print("Sum of first 10 number is:", sum)

Output

Sum of first 10 number is: 55

Nested while loop

In Python, we can define while loop inside another while this is called a nested while loop

while expression:             
    while expression:    
        statemen(s) of inner loop
    statemen(s) of outer loop
other statement(s)

Example of a nested while loop

i = 1
while i <= 3:
    print("Inside outer while")
    j = 1
    while j <= 2:
        print("Inside inner")
        j = j + 1
    i = i + 1

Output

Inside outer while
Inside inner
Inside inner
Inside outer while
Inside inner
Inside inner
Inside outer while
Inside inner
Inside inner

Break statement in Python

The break statement is used inside the loop to exit out of the loop. It is useful when we want to terminate the loop as soon as the condition is fulfilled instead of doing the remaining iterations. It reduces execution time. Whenever the controller encountered a break statement, it comes out of that loop immediately

Syntax of break statement

for element in sequence:
    if condition:
        break

See the following flowchart for more detail.

Python break statement
Python break statement

Let’s see how to break a for a loop when we found a number greater than 5.

In the below example, we are iterating the value of the num variable and printing it. When the num value becomes 6, the break statement will execute and terminates the loop.

Example of using a break statement

for num in range(10):
    if num > 5:
        print("stop processing.")
        break
    print(num)

Output

0
1
2
3
4
5
stop processing.

Continue statement in python

The continue statement is used to skip the current iteration and continue with the next iteration.

Syntax of continue statement:

for element in sequence:
    if condition:
        continue

See the following flowchart for more detail.

Python continue statement
Python continue statement

Let’s see how to skip a for a loop iteration if the number is 5 and continue executing the body of the loop for other numbers

Example of a continue statement

for num in range(3, 8):
    if num == 5:
        continue
    else:
        print(num)

Output

3
4
6
7

Pass statement in Python

The pass is the keyword In Python, which won’t do anything. Sometimes there is a situation in programming where we need to define a syntactically empty block. We can define that block with the pass keyword.

A pass statement is a Python null statement. When the interpreter finds a pass statement in the program, it returns no operation. Nothing happens when the pass statement is executed.

It is useful in a situation where we are implementing new methods or also in exception handling. It plays a role like a placeholder.

Syntax of pass statement:

for element in sequence:
    if condition:
        pass

Example

months = ['January', 'June', 'March', 'April']
for mon in months:
    pass
print(months)

Output

['January', 'June', 'March', 'April']

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

Founder of PYnative.com I am a Python developer and I love to write articles to help developers. Follow me on Twitter. All the best for your future Python endeavors!

Related Tutorial Topics:

Basics Python

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ
Exercises
Quizzes

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your code </pre>

2 Comments

  Python Tutorials

  • Python Operators
  • Python Variables
  • Python Data Types
  • Python Casting
  • Python Control Flow statements
  • Python Input and Output
  • Python range function
  • Check user input is String or Number
  • Accept List as a input from user
  • Python Numbers
  • Python Lists
  • Python Tuples
  • Python Sets
  • Python Dictionaries
  • Python Functions
  • Python Modules
  • Python isinstance()
  • Python OOP
  • Python Inheritance
  • Python Exceptions
  • Python Exercise for Beginners
  • Python Quiz for Beginners

All Python Topics

Python Basics Python Exercises Python Quizzes Python Regex Python Random Python Pandas Python Databases Python MySQL Python PostgreSQL Python SQLite Python JSON
TweetF  sharein  shareP  Pin

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Legal Stuff

  • About Us
  • Privacy Policy
  • Cookie Policy
  • Terms Of Use
  • Contact Us
DMCA.com Protection Status

Copyright © 2018-2021 · [pynative.com]