Site icon Full-Stack

Loops in Python: Mastering for and while Loops with Examples

Introduction: Why Loops Are Essential in Python

An essential component of programming is loops. Loops in Python enable you to run a piece of code more than once, increasing code efficiency and decreasing repetition. Loops are essential for processing a list of user inputs, reading files, and automating operations.

With the help of clear examples and practical applications, this blog will teach you how to use Pythonโ€™s for and while loops.

๐Ÿ“Œ What Are Loops in Python?

A loop is a control structure that repeatedly executes a block of code until a certain condition is met. Python supports two main types of loops:

โœ… Python for Loop Explained

๐Ÿ”น Syntax:

for variable in sequence:
    # Code to execute

๐Ÿ”น Example 1: Loop through a list

fruits = ["apple", "banana", "mango"]
for fruit in fruits:
    print(fruit)

Output:

apple
banana
mango

๐Ÿ”น Example 2: Use of range() function

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

Output:

0
1
2
3
4

๐Ÿ”น Use Case: Sum of numbers using a for loop

total = 0
for num in range(1, 11):
    total += num
print("Sum:", total)

You can also read for:- If Else Statement Java With Examples-2024

Python while Loop Explained

๐Ÿ”น Syntax:

while condition:
    # Code to execute

๐Ÿ”น Example 1: Print numbers 1 to 5

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

๐Ÿ”น Example 2: Basic Login System

password = "python123"
user_input = ""

while user_input != password:
    user_input = input("Enter password: ")
print("Access granted.")

๐Ÿšซ Infinite Loops in Python

You risk creating an endless loop that never ends if youโ€™re not careful.

Example:

while True:
    print("This will run forever!")

Use break or a proper condition to avoid infinite loops.


๐Ÿ”„ Loop Control Statements in Python

๐Ÿ”ธ break โ€“ exits the loop

for i in range(10):
    if i == 5:
        break
    print(i)

๐Ÿ”ธ continue โ€“ skips the current iteration

for i in range(5):
    if i == 2:
        continue
    print(i)

๐Ÿ”ธ else with loops

for i in range(3):
    print(i)
else:
    print("Loop completed!")

โš™๏ธ Real-Life Applications of Loops in Python

๐Ÿง  Final Thoughts: Master Loops, Master Python

You may advance your proficiency with Python by mastering the for and while loops. Learning loops is a crucial step in becoming a competent Python developer, regardless of programming experience level.

You might be like this:-

Java vs. Kotlin: Which One Should You Learn for Backend Development?

Where to Find Your Salesforce Organization ID

How Salesforce Stands Out from Other CRMs

Exit mobile version