Loopsinpython 2 230520083813 9a86fc17
Loopsinpython 2 230520083813 9a86fc17
Programming Language
Submitted By:
Maghfoor Ahmad
MCA TYC 2nd Sem
Roll No: 27512100052
Introduction
Sometimes, there is a need to tell a computer
to repeat an action without writing separate
code for each repetition. In programming, this
concept is called loops.
Loops
A loop can be used to tell a program to execute
statements repeatedly. Or we can say that a loop
repeatedly executes the same set of instructions
until a termination condition is met.
Loops changes the control flow of program
that’s why they are also called Control Structure.
Why is it important?
Suppose that you need to display a
string (e.g., Good Morning! ) a
hundred times.
print(“Good Morning!“)
Output:
1
2
3
4
5
6
7
8
9
10
for Loop
A for loop is used for iterating over a sequence (that is either a range, a list, a tuple, a
dictionary, a set, or a string)
The syntax of a for loop in Python is:
Output:
apple
banana
cherry
Output:
Hello
Hello
Hello
Nested Loops
A nested loop is a loop inside the body of a loop. It can be for loop inside a for loop or
while inside a while loop. It can also be for inside a while loop and vice versa.
The syntax of a nested loop in Python programming language is:
For each iteration, the outer loop will executes once and the inner loop will
executes till completion.
Output:
Key Differences
while Loop for Loop
While loop is used when the For loop is used when the
1.
number of iteration is not known. number of iteration is known.
It shows an error if no condition is It iterates infinite time, if no
2.
given. condition is given.
Initialization, condition checking,
Only initialization and condition
3. and iteration statements are
checking is written at the top
written at the top.
Thankyou!
Bibliography
1. Reddy, Priyanka. “Introduction to Loops in Coding”. Codingal, 2021.
https://www.codingal.com/blog/coding-for-kids/loops-in-programming/