A loop in Python is a control flow statement that allows you to execute a block of code repeatedly. There are two types of loops in Python:
for loop and
for loop: The
for loop is used to iterate over a sequence (such as a list, tuple, string, or range) and execute the block of code for each item in the sequence.
for item in sequence: # Code block to be executed for each item
fruits = ['apple', 'banana', 'orange'] for fruit in fruits: print(fruit)
while loop: The
while loop is used to repeatedly execute a block of code as long as a specified condition is true.
while condition: # Code block to be executed as long as the condition is true
count = 1 while count <= 5: print(count) count += 1
Both types of loops are powerful constructs that help you automate repetitive tasks or process data iteratively. Be careful when using loops to ensure they don’t result in infinite loops, where the condition is never met, causing the loop to run indefinitely. Always include a way to break out of the loop if needed.
Python loop examples
Here are some more Python loop examples to illustrate various use cases:
1. Looping through a list and calculating the sum of elements:
numbers = [1, 2, 3, 4, 5] sum_result = 0 for num in numbers: sum_result += num print("Sum of elements:", sum_result)
2. Looping through a string and printing each character:
message = "Hello, World!" for char in message: print(char)
3. Looping through a range of numbers and printing them:
for i in range(1, 6): print(i)
4. Using a
while loop to find the first power of 2 greater than 100:
power_of_two = 1 while power_of_two <= 100: power_of_two *= 2 print("First power of 2 greater than 100:", power_of_two)
continue to skip odd numbers and print only even numbers:
for num in range(1, 11): if num % 2 != 0: continue print(num)
break to exit the loop when a certain condition is met:
fruits = ['apple', 'banana', 'orange', 'pear', 'grape'] for fruit in fruits: if fruit == 'orange': break print(fruit)
These are just a few examples to showcase the flexibility and utility of loops in Python. You can use loops in various combinations and with different data structures to accomplish a wide range of tasks.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.