The looping simplifies the complex problems into the easy ones. It enables us to alter the flow of the program so that instead of writing the same code again and again, we can repeat the same code for a finite number of times.
There are the following loop statements in Python.
for loop
The for loop in Python is used to iterate the statements or a part of the program several times. It is frequently used to traverse the data structures like list, tuple, or dictionary.
Syntax:-
for iterating_var in sequence:
statement(s)
Example:
str = "Python"
for i in str:
print(i)
Output:-
P
y
t
h
o
n
For loop Using range() function
The range() function is used to generate the sequence of the numbers. If we pass the range(10), it will generate the numbers from 0 to 9.
Syntax:-
range(start,stop,step size)
Example:
for i in range(10):
print(i,end = ' ')
Output:-
0 1 2 3 4 5 6 7 8 9
Exercises:-
- Write a py program to print all natural numbers from 1 to n.
- Write a py program to print all even numbers between 1 to 100.
- Write a py program to print multiplication table of any number.
- Write a py program to calculate factorial of a number.
- Write a py program to check whether a number is Prime number or not.
While Loop
The Python while loop allows a part of the code to be executed until the given condition returns false. It is also known as a pre-tested loop.
Syntax:-
while expression:
statements
Exercises:-
- Write a py program to print all natural numbers in reverse (from n to 1).
Comments
Post a Comment