In this article While Loop in Python we give the information about While Loop in Python is used when we have to repeat a task repeatedly until a condition remains true. This loop continues as long as its condition remains true.
While Loop in Python
While Loop in Python is used when we have to repeat a task repeatedly until a condition remains true. This loop continues as long as its condition remains true.
While Loop
syntax
while condition:
Code # This code will run as long as the condition is true
Important points:
- While Loop checks the condition.
- If the condition is True, then the code inside runs.
- As soon as the condition becomes False, the loop ends.
- We have to make sure that the condition is never False, otherwise the loop can become infinite.
While Loop
i = 1
while i<=5:
print(“Hello!”) # This will print as long as i<=5
i += 1 #increase i by 1 each time
Output:
hello!
hello!
hello!
hello!
hello!
Printing numbers
n = 1
while n <= 10:
print(n) # print n
n += 1 # increase n by 1 each time
n = 1
while n <= 10:
print(n) # print n
n += 1 # increase n by 1 each time
Output:
1
2
3
4
5
6
7
8
9
10
Infinite Loop
Infinite Loop in Python is a loop that never ends. This happens when the condition of the loop is always true. This loop runs continuously and requires manual intervention to stop the program.
How is Infinite Loop formed?
- When the condition is always true:
while True:
print(“This is an infinite loop.”)
- When the condition is never false:
i = 1
while i>0: # i will always be greater than 0
print(“This loop will never end.”)
How to stop Infinite Loop?
- Interrupt from keyboard:
Press Ctrl + C to stop the program.
This will end your loop manually.
- How to make the condition correctly:
Make sure the condition in the loop can become False at any time.
Example:
i = 1
while i<=5:
print(i)
i += 1 #increment i by 1 each time
Use break:
Use break to exit the Infinite Loop.
while True:
user_input = input(“Type ‘stop’ to stop the loop: “)
if user_input == “stop”:
print(“Loop terminated.”)
break
If the condition never becomes False, the loop will continue indefinitely.
while True:
print(“This is an infinite loop.”) # Press Ctrl+C from keyboard to stop it
n = 1
while n <= 10:
print(n)
if n == 5: # end the loop when n becomes 5
break
n += 1
Output:
1
2
3
4
5
Conclusion:
Infinite Loop can be useful, but it is important to manage it.
Control it by using break and correct conditions.
Write code carefully to avoid accidentally creating Infinite Loops.
Continue Statement
Continue is used to skip a particular iteration (round) and the loop moves to the next round.
n = 0
while n < 10:
n += 1
if n == 5:
continue will skip #5
print(n)
Output:
1
2
3
4
6
7
8
9
10
While Loop (Nested While Loop)
Another While Loop can be written inside one While Loop.
Example:
i = 1
while i<= 3: # outer loop
j = 1
while j <= 3: # inner loop
print(f”i={i}, j={j}”)
j += 1
i += 1
Output:
i=1,j=1
i=1,j=2
i=1, j=3
i=2,j=1
i=2,j=2
i=2, j=3
i=3,j=1
i=3, j=2
i=3, j=3
Use of While Loop: Real Life Example
Getting the correct password from the user:
password=”python123″
user_input = “”
while user_input != password:
user_input = input(“Enter password: “)
print(“Correct password!”)
Conclusion:
- While Loop is useful when we have to run the code repeatedly based on the condition.
- Make sure the condition is never False, so that the loop is not infinite.
- Loop can be controlled by break and continue.
- It can be used to create more interactive programs.
For Loop in Python
For Loop in Python is used to access each item of a sequence such as a list, string, tuple, or range one by one and perform operations on it.
Syntax
for variable in sequence:
Code # This code will run for every item in the order
Important points:
- for Loop accesses each item of the sequence one by one.
- Each item is assigned to a variable, and then the operation is performed on it.
- The loop continues until all items in the sequence are exhausted.
Example:
numbers = [1, 2, 3, 4, 5]
for number in numbers:
print(num) #will print every number in the list
Output:
1
2
3
4
5
Example: For Loop on String
text = “Python”
for char in text:
print(char) #will print every character of the string
Output:
P
y
t
h
o
n
For Loop with Range
The range() function is used to create a series of a certain number of values.
range(start, stop, step)
start: start number (default: 0)
stop: As far as the desired range (does not include this)
step: difference in range (default: 1)
Example
for i in range(1, 6):
print(i) # will print 1 to 5
Output:
1
2
3
4
5
Step with:
for i in range(0, 10, 2):
print(i) # will print 0, 2, 4, 6, 8
Output:
0
2
4
6
8
Nested For Loop
Another For Loop can be written inside the For Loop.
for i in range(1, 4):
for j in range(1, 4):
print(f”i={i}, j={j}”)
output:
i=1,j=1
i=1,j=2
i=1, j=3
i=2,j=1
i=2,j=2
i=2, j=3
i=3,j=1
i=3, j=2
i=3, j=3
Use of Break and Continue in For Loop
Break:
To stop the loop midway.
for number in range(1, 10):
if number == 5:
break #will stop at loop 5
print(number)
output:
1
2
3
4
Continue:
To skip a particular iteration (round).
for number in range(1, 10):
if number == 5:
continue will skip #5
print(number)
Output:
1
2
3
4
6
7
8
9
For Loop with Else
For Loop with else is used when the loop ends normally without any break.
for number in range(1, 6):
print(number)
otherwise:
print(“Loop ended.”)
Output:
1
2
3
4
5
Loop ended.
With breakElse:
for number in range(1, 6):
if num == 3:
break
print(number)
otherwise:
print(“Loop ended.”)
Output:
1
2
Real-Life Example
Find the sum of all the numbers in the list:
numbers = [10, 20, 30, 40]
total = 0
for number in numbers:
total += num
print(f”Total: {total}”)
output:
numbers = [10, 20, 30, 40]
total = 0
for number in numbers:
total += num
print(f”Total: {total}”)
output:
Total: 100
Multiplication Table of a number:
n = int(input(“Enter number: “))
for i in range(1, 11):
print(f”{n} x {i} = {n * i}”)
Output:
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
……..
……..
5 x 10 = 50
Conclusion:
- For Loop is extremely useful for working with serialized data in Python.
- It can be used for lists, strings, ranges and other sequences.
- It can be made more effective with break, continue, and nested loops.
Iterating by Sequence Index:
In Python, you can use several methods to iterate over any sequence (such as a list, tuple, or string) along with its index. The most popular and Pythonic way is to use enumerate(). Its different methods are explained in detail below:
- Use of enumerate()
enumerate() is a Python built-in function, which returns each item of the sequence along with its index.
my_list = [‘a’, ‘b’, ‘c’, ‘d’]
# Getting both index and value
for index, value in enumerate(my_list):
print(f”Index: {index}, Value: {value}”)
Output:
Index: 0, Value: a
Index: 1, Value: b
Index: 2, Value: c
Index: 3, Value: d
- Starting custom indexing with enumerate()
If you want indexing to start at a particular number (like 1), use the start parameter of enumerate() :
for index, value in enumerate(my_list, start=1):
print(f”Index: {index}, Value: {value}”)
Output:
Index: 1, Value: a
Index: 2, Value: b
Index: 3, Value: c
Index: 4, Value: d
- Use of range(len(sequence))
If you only need the index, range(len(sequence)) can be used. This way is less Pythonic but can be useful in some cases:
for i in range(len(my_list)):
print(f”Index: {i}, Value: {my_list[i]}”)
Output:
- Iterate only on index
If you only need the index and not the values, you can use range() :
for i in range(len(my_list)):
print(f”Index: {i}”)
Output:
Index: 0
Index: 1
Index: 2
Index: 3
- Using index and value with list comprehension
If you need to make some changes to the sequence based on index and value, you can use list comprehension:
modified_list = [f”{i}-{value}” for i, value in enumerate(my_list)]
print(modified_list)
Output:
[‘0-a’, ‘1-b’, ‘2-c’, ‘3-d’]
Key Points:
- Using enumerate() is more Pythonic and easier.
- Use range(len(sequence)) when indexing needs to be done manually.
- If custom indexing needs to be started, use enumerate(start=n).
Some More:
POP- Introduction to Programming Using ‘C’
OOP – Object Oriented Programming
DBMS – Database Management System
RDBMS – Relational Database Management System
Join Now: Data Warehousing and Data Mining