Looping Statements in Python
Complete Tutorial with Examples and Output
1. Introduction to Looping
Looping is a programming technique used to execute a block of statements repeatedly. Instead of writing the same statement many times, a loop allows the programmer to execute it automatically.
For example, if we want to print numbers from 1 to 5, we can use a loop instead
of writing five separate print() statements.
Python mainly provides two types of loops:
- for loop
- while loop
Python also provides loop-control statements such as break,
continue and pass.
2. for Loop
A for loop is used to iterate over a sequence such as a list,
tuple, string, range, or other iterable object.
Syntax
for variable in sequence:
statement
Example
for i in range(1, 6):
print(i)
Output
1
2
3
4
5
3. range() Function
The range() function is commonly used with a for loop.
It generates a sequence of numbers.
Example 1 – range(stop)
for i in range(5):
print(i)
Output
0
1
2
3
4
The stop value 5 is not included.
Example 2 – range(start, stop)
for i in range(2, 7):
print(i)
Output
2
3
4
5
6
Example 3 – range(start, stop, step)
for i in range(2, 11, 2):
print(i)
Output
2
4
6
8
10
4. Looping Through a String
A for loop can be used to access each character of a string.
word = "Python"
for ch in word:
print(ch)
Output
P
y
t
h
o
n
5. Looping Through a List
subjects = ["C", "Python", "Java", "DBMS"]
for subject in subjects:
print(subject)
Output
C
Python
Java
DBMS
6. Looping Through a Tuple
numbers = (10, 20, 30, 40)
for n in numbers:
print(n)
Output
10
20
30
40
7. while Loop
A while loop repeatedly executes a block of code as long as
its condition remains True.
Syntax
while condition:
statement
Example
i = 1
while i <= 5:
print(i)
i = i + 1
Output
1
2
3
4
5
8. Working of a while Loop
Initialize variable
↓
Check condition
↓
Condition True?
↓
Execute statements
↓
Update variable
↓
Check condition again
↓
Condition False → Exit Loop
9. Infinite Loop
An infinite loop occurs when the loop condition never becomes False.
For example:
while True:
print("Hello")
This loop continues indefinitely until it is stopped.
while loop has a suitable
condition or update so that it can eventually terminate when required.
10. break Statement
The break statement immediately terminates the loop.
Example
for i in range(1, 10):
if i == 5:
break
print(i)
Output
1
2
3
4
When i becomes 5, the break statement terminates the loop.
11. continue Statement
The continue statement skips the remaining statements in the
current iteration and moves to the next iteration.
Example
for i in range(1, 6):
if i == 3:
continue
print(i)
Output
1
2
4
5
The value 3 is skipped.
12. pass Statement
The pass statement does nothing. It is useful as a placeholder
when a statement is syntactically required but no action is needed yet.
for i in range(5):
pass
print("Loop completed")
Output
Loop completed
13. Nested Loops
A loop placed inside another loop is called a nested loop.
Example
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
14. Creating a Multiplication Table
Nested loops and the multiplication operator can be used to generate multiplication tables.
number = int(input("Enter a number: "))
for i in range(1, 11):
print(number, "x", i, "=", number * i)
Sample Output
Enter a number: 5
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
15. Sum of Numbers Using for Loop
total = 0
for i in range(1, 6):
total = total + i
print("Sum =", total)
Output
Sum = 15
16. Printing Even Numbers
for i in range(1, 11):
if i % 2 == 0:
print(i)
Output
2
4
6
8
10
17. Printing Odd Numbers
for i in range(1, 11):
if i % 2 != 0:
print(i)
Output
1
3
5
7
9
18. Practical Example – Factorial
The factorial of a positive integer n is:
Python Program
n = int(input("Enter a number: "))
factorial = 1
for i in range(1, n + 1):
factorial = factorial * i
print("Factorial =", factorial)
Sample Output
Enter a number: 5
Factorial = 120
19. Practical Example – Reverse a Number
number = int(input("Enter a number: "))
reverse = 0
while number > 0:
digit = number % 10
reverse = reverse * 10 + digit
number = number // 10
print("Reverse =", reverse)
Sample Output
Enter a number: 12345
Reverse = 54321
20. Practical Example – Count Digits
number = int(input("Enter a number: "))
count = 0
if number == 0:
count = 1
else:
while number != 0:
number = number // 10
count = count + 1
print("Number of digits =", count)
Sample Output
Enter a number: 98765
Number of digits = 5
21. Practical Example – Check Prime Number
A prime number is a number greater than 1 that has no positive divisors other than 1 and itself.
number = int(input("Enter a number: "))
if number < 2:
print("Not a prime number")
else:
is_prime = True
for i in range(2, number):
if number % i == 0:
is_prime = False
break
if is_prime:
print("Prime number")
else:
print("Not a prime number")
Sample Output
Enter a number: 17
Prime number
22. Practical Example – Fibonacci Series
The Fibonacci series starts with 0 and 1, and each subsequent number is the sum of the previous two numbers.
n = int(input("Enter number of terms: "))
a = 0
b = 1
for i in range(n):
print(a, end=" ")
a, b = b, a + b
Sample Output
Enter number of terms: 8
0 1 1 2 3 5 8 13
23. Practical Example – Star Pattern
Nested loops can be used to generate patterns.
for i in range(1, 6):
for j in range(i):
print("*", end=" ")
print()
Output
*
* *
* * *
* * * *
* * * * *
24. Looping with enumerate()
The enumerate() function provides both the index and the value
while iterating through a sequence.
subjects = ["C", "Python", "Java"]
for index, subject in enumerate(subjects):
print(index, subject)
Output
0 C
1 Python
2 Java
25. Looping with zip()
The zip() function can be used to iterate over multiple sequences
at the same time.
names = ["Rahul", "Amit", "Riya"]
marks = [85, 90, 78]
for name, mark in zip(names, marks):
print(name, mark)
Output
Rahul 85
Amit 90
Riya 78
26. else with a Loop
Python allows an else block to be associated with a loop.
For a for or while loop, the else
block executes when the loop finishes normally rather than being terminated
by break.
Example
for i in range(1, 4):
print(i)
else:
print("Loop completed")
Output
1
2
3
Loop completed
27. Loop else with break
for i in range(1, 6):
if i == 3:
break
print(i)
else:
print("Loop completed")
Output
1
2
The else block does not execute because the loop was terminated
using break.
28. for Loop vs while Loop
| for Loop | while Loop |
|---|---|
| Used to iterate over a sequence or iterable | Runs while a condition is True |
| Often used when the number of iterations is known | Useful when repetition depends on a condition |
Commonly used with range() |
Requires careful condition/update handling |
for i in range(5): |
while condition: |
29. Loop Control Statements
| Statement | Purpose |
|---|---|
break |
Terminates the loop immediately |
continue |
Skips the current iteration |
pass |
Does nothing; acts as a placeholder |
30. Common Errors in Loops
- Forgetting to update a while-loop variable: This can result in an infinite loop.
- Incorrect indentation: Python uses indentation to identify the loop body.
-
Incorrect range:
Remember that the stop value in
range()is excluded. - Unnecessary nested loops: Too many nested loops can make a program slower and harder to understand.
-
Incorrect use of break:
Make sure
breakis used only when the loop should terminate.
31. General Loop Flow
Start
↓
Initialize
↓
Check Condition / Get Next Item
↓
Execute Loop Body
↓
Update / Get Next Item
↓
Repeat
↓
Exit Loop
32. Summary
Looping is one of the most important concepts in Python programming. It allows a programmer to execute statements repeatedly without writing the same code again and again.
forloops are commonly used to iterate over sequences and iterables.whileloops execute while a condition remains True.range()is frequently used withforloops.- Nested loops allow one loop to execute inside another loop.
breakterminates a loop.continueskips the current iteration.passacts as a placeholder.enumerate()provides index and value while iterating.zip()allows multiple sequences to be processed together.
Created by Bijan Krishna Paul
Computer Science • Python Programming • Data Science
No comments:
Post a Comment