Loops in Python
Loops in Python
Loops in Python are used to repeat actions efficiently.
Types of Loops
The main types are For loops (counting through items) and While loops (based on conditions).
While Loop
while loop is used to execute a block of statements repeatedly until a given condition is satisfied. When the condition becomes false, the line immediately after the loop in the program is executed.
Ex.
count = 1
while count <= 3:
count = count + 1
print("Hello World")
Output
Hello World
Hello World
Hello World
Example
1) Generate Counting 1 to 10.
num = 1
while num<= 10:
print(num)
num = num + 1
else:
print("loop finished")
Output
1
2
3
4
5
6
7
8
9
10
loop finished
2) Create table using with Input Method
val = int(input("Enter a Number to Create a table:"))
no=1
while no<= 10:
print(no*val)
num = num + 1
else:
print("loop finished")
Output
Enter a Number to Create a table: 5
5
10
15
20
25
30
35
40
45
50
loop finished
3) Create Program Print Natural Number
a=int(input("Enter any no :"))
no = 1
while no<= 10:
print(no)
no = no + 1
else:
print("loop finished")
Output
Enter any no : 10
1
2
3
4
5
6
7
8
9
10
loop finished
4) Create Reverse Counting (10 to 1) Printing Program.
a=int(input("Enter any no :"))
no = 10
while no>= 1:
print(no)
no = no - 1
else:
print("loop finished")
Output
Enter any no : 10
10
9
8
7
6
5
4
3
2
1
loop finished
5) The continue Statement
With the continue statement we can stop the current iteration, and continue with the next:
i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)
# Note that number 3 is missing in the result
Output
1
2
4
5
6
6) The else Statement
With the else statement we can run a block of code once when the condition no longer is true:
i = 1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")

No comments: