List of basic loop in python for while loop
Basic loops in Python #forloop #while
Loops are a fundamental concept in programming that allow you to execute a block of code repeatedly. Python provides several types of loops, including for loops, while loops, and do-while loops (simulated). In this article, we’ll explore these loops with clear examples to help you understand how and when to use them.
Loops are essential for:
The for loop is used to iterate over a sequence (like a list, tuple, or string) and execute a block of code for each item in the sequence.
Syntax:
for variable in sequence:
# Code to execute
else:
# Code to execute when the loop is finished
Example:
digits = [0, 1, 4]
for i in digits:
print(i)
else:
print("No items left.")
Output:
0
1
4
No items left.
The while loop is used to execute a block of code as long as a condition is true. It is ideal when the number of iterations is unknown.
Syntax:
while condition:
# Code to execute
Example:
# Initialize variables
i = 1
n = 6
# While loop from i = 1 to 6
while i <= n:
print(i)
i = i + 1
Output:
1
2
3
4
5
6
Python does not have a built-in do-while loop, but you can simulate it using a while loop with a break
statement.
Syntax:
while True:
# Code to execute
if condition:
break
Example:
i = 1
# Simulate a do-while loop
while True:
print(i)
i = i + 1
if i > 5:
break
Output:
1
2
3
4
5
Feature | For Loop | While Loop |
---|---|---|
Usage | Iterates over a sequence. | Executes as long as a condition is true. |
Iterations | Known in advance. | Unknown in advance. |
Syntax |
for variable in sequence: |
while condition: |
Iterate over a list of names and print each name:
names = ["Alice", "Bob", "Charlie"]
for name in names:
print(name)
Keep asking for user input until a valid number is entered:
while True:
user_input = input("Enter a number: ")
if user_input.isdigit():
print("Valid input!")
break
else:
print("Invalid input. Try again.")
Simulate a do-while loop to print numbers until a condition is met:
i = 1
while True:
print(i)
i += 1
if i > 10:
break
else
with Loops: The else
block executes when the loop finishes normally (without a break
).Loops are a powerful feature in Python that allow you to repeat code blocks efficiently. Whether you use a for loop, while loop, or simulate a do-while loop, understanding these constructs is essential for writing clean and effective code. By following the examples and best practices outlined in this guide, you’ll be well-equipped to use loops in your Python projects.