Control Flow & Loops in Python

In Python, control flow statements enable you to make decisions and repeat actions based on certain conditions. The two primary control flow constructs are if statements and loops. In this article, we’ll explore how to use these constructs effectively.

If Statements

If statements allow you to execute certain blocks of code only if specific conditions are met.

Basic If Statement

The basic structure of an if statement is:

if condition:
# Code to execute if the condition is True

Example:

age = 18

if age >= 18:
print("You are an adult.")

If-Else Statement

The if-else statement lets you execute one block of code if the condition is true and another block if it is false.

if condition:
# Code to execute if the condition is True
else:
# Code to execute if the condition is False

Example:

age = 16

if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")

If-Elif-Else Statement

The if-elif-else statement allows you to check multiple conditions.

if condition1:
# Code to execute if condition1 is True
elif condition2:
# Code to execute if condition2 is True
else:
# Code to execute if both conditions are False

Example:

age = 20

if age < 13:
print("You are a child.")
elif age < 20:
print("You are a teenager.")
else:
print("You are an adult.")

Loops

Loops are used to repeat a block of code multiple times.

For Loop

A for loop is used to iterate over a sequence (like a list, tuple, or string).

for item in sequence:
# Code to execute for each item

Example:

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
print(fruit)

Using Range with For Loop

The range() function generates a sequence of numbers.

for i in range(start, stop, step):
# Code to execute for each number in the range
  • start (optional): The starting value (default is 0).
  • stop: The stopping value (not inclusive).
  • step (optional): The difference between each number (default is 1).

Example:

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

While Loop

A while loop repeats as long as a condition is true.

while condition:
# Code to execute while the condition is True

Example:

count = 1

while count <= 5:
print(count)
count += 1

Breaking Out of Loops

The break statement is used to exit a loop prematurely.

Example:

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

Skipping Iterations

The continue statement skips the current iteration and proceeds to the next iteration.

Example:

for i in range(1, 11):
if i % 2 == 0:
continue
print(i)

Nested Loops

Loops can be nested within each other to perform more complex tasks.

Example:

for i in range(1, 4):
for j in range(1, 4):
print(f"i = {i}, j = {j}")

Real-Time Example: Grading System

Let’s create a simple grading system that assigns letter grades based on numerical scores.

# Grading system

score = int(input("Enter your score: "))

if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"

print("Your grade is:", grade)

Exercises

  1. Write a program that prints the first 10 Fibonacci numbers.
  2. Create a program that checks if a given number is prime.
  3. Write a script that prints a multiplication table for numbers 1 through 5.

Conclusion

In this article, we’ve covered the basics of control flow in Python using if statements and loops. These constructs are fundamental for making decisions and repeating actions in your programs. In the next article, we’ll explore functions and how to write reusable code in Python. Happy coding!

Data AI Admin

Senior AI Lead having overall Experience of 10+ years in IT, Data Science, Machine Learning, AI and related fields.

Related Posts

Exploring Different Pandas File Formats

Data handling and manipulation are fundamental in data analysis. Pandas, a powerful Python library, supports various file formats for reading, writing, and converting data. Understanding these formats and their benefits…

Read more

Making Beautiful Plots with Seaborn in Python

Welcome to the sixth tutorial in our series on data analysis with Python! In this article, we’ll introduce you to Seaborn, a powerful Python visualization library built on top of…

Read more

Leave a Reply

You Missed

Exploring Different Pandas File Formats

  • June 28, 2024
Exploring Different Pandas File Formats

Making Beautiful Plots with Seaborn in Python

  • June 28, 2024
Making Beautiful Plots with Seaborn in Python

Mastering Data Visualization with Matplotlib

  • June 28, 2024
Mastering Data Visualization with Matplotlib

Data Cleaning and Preprocessing with Pandas

  • June 27, 2024
Data Cleaning and Preprocessing with Pandas

Exploring Data with Pandas: Series and DataFrames

  • June 27, 2024
Exploring Data with Pandas: Series and DataFrames

NumPy : Basic Operations and Arrays

  • June 27, 2024
NumPy : Basic Operations and Arrays