Table of Contents
Printing Numbers Using a for Loop
# Python program to print numbers from 1 to 5 # Iterating through numbers from 1 to 5 for number in range(1, 6): print(number)
12345
Printing Numbers Using a while Loop
# Python program to print numbers from 1 to 5 using a while loop number = 1 # Running the loop while number is less than or equal to 5 while number <= 5: print(number) # Increasing the value of number number += 1
12345
Looping Through a List
# Python program to print elements of a list fruits = ["Apple", "Banana", "Mango"] # Iterating through each fruit for fruit in fruits: print(fruit)
AppleBananaMango
Looping Through a String
# Python program to print each character of a string word = "Python" # Iterating through each character for character in word: print(character)
Python
Printing Even Numbers
# Python program to print even numbers from 2 to 10 # Increasing the number by 2 in every iteration for number in range(2, 11, 2): print(number)
246810
Printing Numbers in Reverse Order
# Python program to print numbers from 5 to 1 # Decreasing the number by 1 in every iteration for number in range(5, 0, -1): print(number)
54321
Finding the Sum of Numbers
# Python program to find the sum of numbers from 1 to 5
total = 0
# Adding each number to the total
for number in range(1, 6):
total += number
print("Sum:", total)
Sum: 15
Using break in a Loop
The break statement is used to immediately terminate a loop when a specified condition is met.
Example:
# Python program to stop a loop using break for number in range(1, 10): print(number) # Stopping the loop when number reaches 5 if number == 5: break
Output:
1
2
3
4
5
Explanation: The loop normally would continue until 9. However, when number becomes 5, the break statement terminates the loop immediately.
Using continue in a Loop
The continue statement skips the current iteration and moves to the next iteration of the loop.
Python uses indentation to determine which statements belong to the loop.
# Python program to skip an iteration using continue for number in range(1, 6): # Skipping the number 3 if number == 3: continue print(number)
Output:
1
2
4
5
Explanation: When number becomes 3, the continue statement skips the remaining code for that iteration. The loop then continues with 4.
Looping Through a Dictionary
A for loop can be used to access keys and values stored in a dictionary.
Example:
# Python program to iterate through a dictionary
student = {
"Name": "Rahul",
Age": 18,
"Course": "Python"
}
# Printing each key and its value
for key, value in student.items():
print(key, ":", value)
Output
Name : Rahul
Age : 18
Course : Python
Explanation: The items() method returns both the keys and their corresponding values. The for loop stores them in key and value and prints them together.
Using enumerate() with a Loop
The enumerate() function is useful when you need both the index and the value of each element.
Example:
# Python program to display list elements with their index subjects = ["Python", "Java", "C++"] # Getting both index and subject for index, subject in enumerate(subjects, start=1): print(index, "-", subject)
Output:
1 - Python
2 - Java
3 - C++
Explanation: enumerate() provides the index and the corresponding element during each iteration. Here, start=1 makes the index begin from 1 instead of 0.
Nested for Loop
A nested loop is a loop placed inside another loop. It is useful when working with patterns, tables, and two-dimensional data.
Example:
# Python program to demonstrate a nested for loop # Outer loop for i in range(1, 3): # Inner loop for j in range(1, 4): print(i, j)
Output:
1 1
1 2
1 3
2 1
2 2
2 3
Explanation: The inner loop runs completely for every iteration of the outer loop. When i is 1, the inner loop prints three combinations. The same process is repeated when i becomes 2.
Using a while Loop with break
A while loop can be combined with break to stop when a particular condition is reached.
Example:
# Python program to stop a while loop using break number = 1 while True: print(number) # Increasing the value of number number += 1 # Stopping the loop after 5 if number > 5: break
Output:
1
2
3
4
5
Explanation: while True creates a loop that can continue indefinitely. The break statement provides a controlled exit when number becomes greater than 5.
Common Beginner Mistakes
1. Forgetting to Update the Variable in a while Loop: If the variable is not updated, the condition may always remain True, creating an infinite loop.
Wrong:
number = 1
while number <= 5:
print(number)
Correct:
number = 1
while number <= 5:
print(number)
number += 1
2. Forgetting the Colon (:): The colon is required at the end of the for or while statement.
Wrong:
for number in range(5)
print(number)
Correct:
for number in range(5):
print(number)
3. Incorrect Indentation: Python uses indentation to determine which statements belong to the loop.
Wrong:
for number in range(5):
print(number)
Correct:
for number in range(5):
print(number)
4. Confusing break with continue: Beginners sometimes use break when they only want to skip one iteration. However, break stops the entire loop, while continue skips only the current iteration.
Wrong:
# Python program demonstrating an incorrect use of break
for number in range(1, 6):
# Trying to skip the number 3
if number == 3:
break
print(number)
Correct:
# Python program to skip an iteration using continue
for number in range(1, 6):
# Skipping the number 3
if number == 3:
continue
print(number)
5. Forgetting That the range() Stop Value Is Not Included: Beginners often expect the last value given to range() to be included in the loop.
Wrong Expectation:
# Python program to demonstrate the range() function
# Trying to print numbers from 1 to 5
for number in range(1, 5):
print(number)
Correct:
# Python program to print numbers from 1 to 5
# Using 6 as the stop value because it is not included
for number in range(1, 6):
print(number)
Conclusion
Python loops provide a simple way to repeat operations and process multiple pieces of data efficiently. The for loop is commonly used for iterating over sequences and collections, while the while loop is useful when repetition depends on a condition.
By practicing different loop examples, such as iterating through lists and strings, generating number sequences, performing calculations, and using break, continue, and nested loops, beginners can develop a strong understanding of how repetition works in Python. These concepts form an important foundation for writing more complex Python programs.
Frequently Asked Questions (FAQs)
1. What are loops used for in Python?
Loops are used to execute a block of code repeatedly. They help reduce repetitive code and make programs easier to manage.
2. What are the main types of loops in Python?
Python mainly provides two types of loops: the for loop and the while loop.
3. When should I use a for loop?
A for loop is generally useful when you want to iterate over a sequence or collection, or when the number of iterations is known.
4. When should I use a while loop?
A while loop is useful when the number of iterations is not known in advance and the loop should continue while a particular condition remains True.
5. What does break do in a loop?
The break statement immediately terminates the loop and transfers control to the statement following the loop.
6. What does continue do in a loop?
The continue statement skips the remaining statements in the current iteration and moves to the next iteration.
0 Comments