Python, a "for loop" is used to iterate over a sequence, such as a list, tuple, string, or any other iterable object. It allows you to perform a set of operations repeatedly for each item in the sequence without the need to write repetitive code.
The general syntax of a for loop in Python is as follows:
for item in iterable:
# Code block to be executed for each item in the iterable
Here's a breakdown of the components:
for: This keyword signals the start of the for loop.
item: This is a temporary variable that takes on the value of each element in the iterable on each iteration. You can use any valid variable name here.
in: This keyword is used to specify the iterable over which the loop will iterate.
iterable: This is the collection or sequence of items that the for loop will go through.
The loop executes the code block for each item in the iterable, and once the loop iterates through all the items, it terminates, and the program continues with the next line of code after the loop.
Here's an example to illustrate how a for loop works:
# Example: Printing each element in a list
fruits = ['apple', 'banana', 'orange']
for fruit in fruits:
print(fruit)
Output:
apple
banana
orange
In this example, the for loop iterates over each element in the fruits list, and the fruit variable takes on the value of each item on each iteration. The print(fruit) statement is executed three times, once for each fruit in the list.
You can use the for loop to perform various operations on the elements of an iterable, such as performing calculations, filtering data, or modifying the elements.
Keep in mind that the indentation is crucial in Python. The code block following the for statement must be indented to indicate that it is a part of the loop. The indentation is what Python uses to define the scope of the loop.
for i in range(1, 6): # The range function generates numbers from 1 to 5 (inclusive).
print(i)
Output:
1
2
3
4
5
numbers = [1, 2, 3, 4, 5]
sum = 0
for num in numbers:
sum += num
print("Sum:", sum)
Output:
Sum: 15
message = "Hello, World!"
for char in message:
print(char)
Output:
H
e
l
l
o
,
W
o
r
l
d
!
fruits = ['apple', 'banana', 'orange']
search_item = 'banana'
found = False
for fruit in fruits:
if fruit == search_item:
found = True
break
if found:
print(search_item, "is in the list.")
else:
print(search_item, "is not in the list.")
Output:
banana is in the list.
numbers = [1, 2, 3, 4, 5]
squared_numbers = []
for num in numbers:
squared_numbers.append(num ** 2)
print(squared_numbers)
Output:
[1, 4, 9, 16, 25]
These examples demonstrate how versatile the for loop is in Python, allowing you to perform various tasks efficiently by iterating over the elements of an iterable.
Python, the while loop is used to execute a block of code repeatedly as long as a specified condition is true. The syntax for the while loop is as follows:
while condition:
# Code block to be executed while the condition is true
# ...
The loop will continue to run as long as the condition remains True. Once the condition evaluates to False, the loop terminates, and the program continues with the code after the while loop.
Here's a simple example of using a while loop to print numbers from 1 to 5:
count = 1
while count <= 5:
print(count)
count += 1
Output:
1
2
3
4
5
In this example, the count variable is initialized to 1, and the while loop continues executing the code block inside it as long as count is less than or equal to 5. After each iteration, the value of count is incremented by 1 (count += 1), so the loop prints numbers from 1 to 5.
It is crucial to ensure that the condition in the while loop will eventually become False. Otherwise, you might end up in an infinite loop, causing the program to run indefinitely. To prevent infinite loops, you can use appropriate logic or update the loop control variable (count in the example) within the loop's body, so the condition becomes False eventually.
Here's an example of a potential infinite loop:
# This is an infinite loop because the condition will always be True
while True:
print("This is an infinite loop!")
Remember to use break statement inside the loop or make sure the condition is updated correctly to exit the loop when needed.