Intensity Coding
  • HOME
  • TUTORIALS
    • Python
    • Natural Language Processing
  • ABOUT US
    • About Us
    • Contact Us
    • Privacy Policy
    • Terms and Conditions
    • Disclaimer

Python

Python Control Statements

Python
Python
  • Introduction To Python
  • Write Your First Python Program
  • Indentation And Comments in Python
  • Variables in Python
  • Data Types in Python
  • Booleans and Number in Python
  • Operators in Python
  • Mutable Vs Immutable Objects And Collection in Python
  • Python String
  • Python Lists
  • Python Tuples
  • Python Sets
  • Python Dictionaries
  • Python Control Statements
  • Python Functions
  • Python Lambda Functions
  • Python Regular Expressions (RegEx)
  • Python JSON

IC_Python_Tutorial-14_Python_Control_Statements.png

Control Statements in Python¶

  • Control statements determine the flow of execution in a program. They allow us to manage the order in which statements are executed, enabling decision-making, repetition, and sequential execution.

  • There are three primary types of control flow:

  1. Sequential Execution – Executes statements in the order they are written.
  2. Selection (Decision Making) – Executes different statements based on conditions.
  3. Iteration (Looping) – Repeats a block of code multiple times.

1. Sequential Control¶

  • Definition: Statements execute one after another in a linear fashion.
  • Behavior: No branching or repetition occurs.
In [ ]:
# Printing steps in sequential order
print("Step 1")  # Executes first
print("Step 2")  # Executes second
print("Step 3")  # Executes third
Step 1
Step 2
Step 3

2. Selection Control (Decision Making)¶

  • Definition: The program chooses a path based on conditions.
  • Behavior: Executes different blocks of code depending on conditions (e.g., if-else).
In [ ]:
# Define an age variable
age = 18

# Check if age is 18 or above
if age >= 18:
    print("You are eligible to vote")  # Executes if condition is True
else:
    print("You are not eligible to vote")  # Executes if condition is False
You are eligible to vote

3. Iteration Control (Looping)¶

  • Definition: Repeats a block of code until a condition is met.
  • Behavior: Executes loops (for, while).
In [ ]:
# Initialize counter variable
i = 1

# Loop until i is greater than 5
while i <= 5:
    print("Iteration:", i)  # Print the current iteration number
    i += 1  # Increment i by 1 to avoid infinite loop
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Iteration: 5

Python range() Function¶

  • The range() function in Python generates a sequence of numbers. It is commonly used in loops to iterate over a specified range without storing all values in memory, making it highly memory efficient.

Syntax¶

range(start, stop, step)

Parameter Details¶

Parameter Description Default Value Required?
start The first number in the sequence 0 Optional
stop The number before which the sequence stops N/A Required
step The difference between each number in the sequence 1 Optional

Useful Information¶

Behavior Explanation
range(n) Generates numbers from 0 to n-1
range(a, b) Generates numbers from a to b-1
range(a, b, c) Generates numbers from a to b-1 with step c
Negative step Used for reverse iteration

1. Using range(stop) – Default Start (0) and Step (1)¶

In [ ]:
# range(5) generates numbers from 0 to 4 (default start: 0, step: 1)

for index in range(5):
    print(index)

# Output:
# 0
# 1
# 2
# 3
# 4
0
1
2
3
4

2. Using range(start, stop) – Specified Start and Default Step (1)¶

In [ ]:
# Training model over epochs from 5 to 10 (inclusive of 5 but exclusive of 11)

for index in range(5, 11):
    print(index)

# Output:
# 5
# 6
# 7
# 8
# 9
# 10
5
6
7
8
9
10

3. Using range(start, stop, step) – Specified Step Value¶

In [ ]:
for index in range(1, 11, 2):
    print(index)

# Output:
# 1
# 3
# 5
# 7
# 9
1
3
5
7
9

4. Using range() with a Negative Step (Counting Backwards)¶

In [ ]:
for index in range(10, 0, -2):
    print(index)

# Output:
# 10
# 8
# 6
# 4
# 2
10
8
6
4
2

Python If...Else Statements¶

  • Python provides conditional statements to control the flow of execution based on specific conditions.

  • Python supports the following logical conditions for comparisons:

  • Equals: a == b

  • Not Equals: a != b

  • Less than: a < b

  • Less than or equal to: a <= b

  • Greater than: a > b

  • Greater than or equal to: a >= b

1. If Statements¶

In [ ]:
views = 5000
threshold = 10000

# If views are greater than the threshold, print a message
if views > threshold:
    print("Intensity Coding has reached a milestone!")

# Output: (No output because condition is False)

Indentation in If Statements¶

  • Python uses indentation to define code blocks. Incorrect indentation leads to errors.
if views > threshold:
print("Intensity Coding has reached a milestone!")  # IndentationError

2. The elif Statement¶

  • The elif keyword is used to check additional conditions when the previous if statement is false.
In [ ]:
subscribers = 10000
goal = 10000

if subscribers > goal:
    print("Intensity Coding has exceeded its subscriber goal!")
elif subscribers == goal:
    print("Intensity Coding has reached its subscriber goal!")

# Output:
# Intensity Coding has reached its subscriber goal!
Intensity Coding has reached its subscriber goal!

3. The else Statement¶

  • The else block executes when none of the preceding conditions are met.
In [ ]:
likes = 150
required_likes = 200

if likes > required_likes:
    print("Intensity Coding video is trending!")
elif likes == required_likes:
    print("Intensity Coding video is gaining attention!")
else:
    print("More likes are needed for trending!")

# Output:
# More likes are needed for trending!
More likes are needed for trending!
In [ ]:
# If there is no need for an `elif`, you can use only `else`:

views = 3000
required_views = 5000

if views > required_views:
    print("Intensity Coding tutorial is getting popular!")
else:
    print("Keep sharing the tutorial to reach more people!")

# Output:
# Keep sharing the tutorial to reach more people!
Keep sharing the tutorial to reach more people!

4. Short-Hand If Statement¶

  • When an if statement has only one line, it can be written in a single line.
In [ ]:
if views > required_views: print("Tutorial is going viral!")
# Output: (No output because condition is False)

5. Short-Hand If...Else (Ternary Operator)¶

  • For concise conditional expressions, Python allows a short-hand format.
In [ ]:
subscribers = 5000
goal = 10000

print("Goal Achieved!") if subscribers >= goal else print("Keep Growing!")

# Output:
# Keep Growing!
Keep Growing!
In [ ]:
# You can also use multiple conditions in one line:
subscribers = 10000
goal = 10000

print("Above Goal!") if subscribers > goal else print("On Target!") if subscribers == goal else print("Keep Pushing!")
# Output:
# On Target!
On Target!

6. Logical Operators (and, or, not)¶

Using and Operator¶

  • Both conditions must be True for the block to execute.
In [ ]:
likes = 500
comments = 50
shares = 20

if likes > 400 and comments > 30:
    print("Intensity Coding tutorial is getting engagement!")

# Output:
# Intensity Coding tutorial is getting engagement!
Intensity Coding tutorial is getting engagement!

Using or Operator¶

  • At least one condition must be True for execution.
In [ ]:
if likes > 400 or shares > 50:
    print("Tutorial is gaining visibility!")

# Output:
# Tutorial is gaining visibility!
Tutorial is gaining visibility!

Using not Operator¶

  • Reverses the result of a condition.
In [ ]:
subscribers = 5000
goal = 10000

if not subscribers > goal:
    print("Subscribers goal not reached yet.")

# Output:
# Subscribers goal not reached yet.
Subscribers goal not reached yet.

7. Nested If Statements¶

  • An if statement inside another if statement is called a nested if.
In [ ]:
views = 12000

if views > 1000:
    print("Intensity Coding tutorial is getting views!")  # Output: Intensity Coding tutorial is getting views!

    if views > 10000:
        print("Tutorial is becoming popular!")  # Output: Tutorial is becoming popular!
    else:
        print("Keep sharing the tutorial.")

# Output:
# Intensity Coding tutorial is getting views!
# Tutorial is becoming popular!
Intensity Coding tutorial is getting views!
Tutorial is becoming popular!

8. The pass Statement¶

  • Python does not allow empty if statements. However, you can use the pass keyword if an if block is required but should not execute any code.
In [ ]:
subscribers = 10000

if subscribers > 5000:
    pass  # Placeholder for future logic

Python Loops – while and for¶

  • Loops in Python allow executing a block of code multiple times. Python provides two primary loop types:

    1. while loop – Executes as long as a specified condition is True.
    1. for loop – Iterates over a sequence such as a list, tuple, dictionary, or string.

Python While Loops¶

1. while Loop¶

  • The while loop executes a block of code as long as a specified condition evaluates to True.

Syntax:¶

while condition:
   # Code block to execute
In [ ]:
# Using a while loop to print numbers from 1 to 5
i = 1
while i <= 5:
    print(i)  # Output: 1, 2, 3, 4, 5
    i += 1  # Increment to prevent an infinite loop
1
2
3
4
5

2. Infinite Loop¶

  • A while loop without a stopping condition runs indefinitely.
In [ ]:
# WARNING: This is an infinite loop! Uncomment with caution.
# while True:
#     print("This will run forever!")

3. break Statement¶

  • The break statement stops the loop even if the condition remains True.
In [ ]:
# Stop the loop when i equals 3
i = 1
while i <= 5:
    print(i)  # Output: 1, 2, 3
    if i == 3:
        break  # Exit the loop
    i += 1
1
2
3

4. continue Statement¶

  • The continue statement skips the current iteration and moves to the next.
In [ ]:
# Skip printing 3
i = 0
while i < 5:
    i += 1
    if i == 3:
        continue  # Skip when i equals 3
    print(i)  # Output: 1, 2, 4, 5
1
2
4
5

5. else Statement¶

  • The else block runs after the while loop finishes execution.
In [ ]:
# Print numbers and display a message after completion
i = 1
while i <= 5:
    print(i)  # Output: 1, 2, 3, 4, 5
    i += 1
else:
    print("Loop completed!")  # Output: Loop completed!
1
2
3
4
5
Loop completed!

Python For Loops¶

  • A for loop in Python is used to iterate over a sequence, such as a list, tuple, dictionary, set, or string. Unlike traditional loops in other languages that use indexing, Python's for loop works more like an iterator.

Looping Through a List¶

  • A for loop allows us to iterate through each item in a list and perform actions on them.
In [ ]:
# Define a list of programming languages
languages = ["Python", "Java", "C++", "JavaScript"]

# Iterate through the list
for lang in languages:
    print(lang)  # Output each language

# Output:
# Python
# Java
# C++
# JavaScript
Python
Java
C++
JavaScript

Looping Through a String¶

  • Strings in Python are sequences of characters, which means we can iterate through them like a list.
In [ ]:
text = "AI"

# Iterate through each character
for char in text:
    print(char)

# Output:
# A
# I
A
I

Using break in a For Loop¶

  • The break statement stops the loop when a certain condition is met.
In [ ]:
languages = ["Python", "Java", "C++", "JavaScript"]

for lang in languages:
    if lang == "C++":
        break  # Stop when "C++" is found
    print(lang)

# Output:
# Python
# Java
Python
Java

Using continue in a For Loop¶

  • The continue statement skips the current iteration and moves to the next item.
In [ ]:
languages = ["Python", "Java", "C++", "JavaScript"]

for lang in languages:
    if lang == "C++":
        continue  # Skip "C++"
    print(lang)

# Output:
# Python
# Java
# JavaScript
Python
Java
JavaScript

The range() Function in For Loops¶

  • The range() function generates a sequence of numbers, which can be useful for loops.
In [ ]:
# Loop from 0 to 4
for i in range(5):
    print(i)

# Output:
# 0
# 1
# 2
# 3
# 4
0
1
2
3
4
In [ ]:
### Specifying Start and End
for i in range(2, 6):
    print(i)

# Output:
# 2
# 3
# 4
# 5
2
3
4
5
In [ ]:
### Using a Step Value
for i in range(1, 10, 2):
    print(i)

# Output:
# 1
# 3
# 5
# 7
# 9
1
3
5
7
9

Else in a For Loop¶

  • The else block in a for loop runs when the loop finishes normally (i.e., no break).
  • If the loop is stopped with break, the else block does not execute.
In [ ]:
for i in range(3):
    print(i)
else:
    print("Loop completed!")

# Output:
# 0
# 1
# 2
# Loop completed!
0
1
2
Loop completed!
In [ ]:
#If the loop is stopped with `break`, the `else` block does not execute.
for i in range(3):
    if i == 1:
        break
    print(i)
else:
    print("Loop completed!")

# Output:
# 0
0

Nested Loops¶

  • A nested loop is a loop inside another loop.
In [ ]:
# Iterate over different types of AI models and their applications
models = ["CNN", "RNN"]
applications = ["Image Processing", "Text Analysis"]

for model in models:
    for app in applications:
        print(f"{model} is used for {app}")

# Output:
# CNN is used for Image Processing
# CNN is used for Text Analysis
# RNN is used for Image Processing
# RNN is used for Text Analysis
CNN is used for Image Processing
CNN is used for Text Analysis
RNN is used for Image Processing
RNN is used for Text Analysis

The pass Statement in a For Loop¶

  • The pass statement is used as a placeholder when a loop cannot be empty.
In [ ]:
for i in range(3):
    pass  # Placeholder, no action

# No output
Category
Python Natural Language Processing
Tag's
Python Natural Language Processing

Quick Links

  • Home
  • Tutorials
  • About Us
  • Contact Us

Tutorials

  • Python
  • Natural Language Processing

Tag's

  • Python
  • Natural Language Processing

About Intensity Coding

  • Intensity Coding is your learning hub for Data Science, Machine Learning, Deep Learning, NLP, and Generative AI. From beginner to expert level, we offer clear tutorials, real-world examples, and up-to-date insights. Our content simplifies complex topics to help you grow in your AI journey.
Intensity Coding

© 2025 Intensity Coding. All Rights Reserved.

Privacy Policy Terms and Conditions Disclaimer