Loops Example in Python
Sure! Here are some examples of loops in Python:
**1. For Loop:**
For loops are used to iterate over a sequence (list, tuple, string, etc.) and execute a block of code for each item in the sequence.
Example 1 - Iterate over a list:
```python
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(fruit)
# Output: apple
# banana
# orange
```
Example 2 - Iterate over a string:
```python
message = "Hello"
for char in message:
print(char)
# Output: H
# e
# l
# l
# o
```
**2. While Loop:**
While loops continue to execute a block of code as long as the specified condition is True.
Example 1 - Simple while loop:
```python
count = 1
while count <= 5:
print(count)
count += 1
# Output: 1
# 2
# 3
# 4
# 5
```
Example 2 - While loop with user input:
```python
password = ""
while password != "secret":
password = input("Enter the password: ")
print("Access granted!")
# Output: Enter the password: 123
# Enter the password: secret
# Access granted!
```
**3. Nested Loops:**
You can use loops inside other loops to perform more complex iterations.
Example - Nested for loop:
```python
for i in range(1, 4):
for j in range(1, 4):
print(i, j)
# Output: 1 1
# 1 2
# 1 3
# 2 1
# 2 2
# 2 3
# 3 1
# 3 2
# 3 3
```
**4. Loop Control Statements:**
You can use control statements like `break` and `continue` to modify the behavior of loops.
Example - Using `break` to exit a loop early:
```python
numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num == 3:
break
print(num)
# Output: 1
# 2
```
Example - Using `continue` to skip an iteration:
```python
numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num == 3:
continue
print(num)
# Output: 1
# 2
# 4
# 5
```
These are some examples of using loops in Python. Loops are powerful tools that allow you to execute repetitive tasks efficiently and are an essential part of programming.
Comments
Post a Comment