Loops in Python

a loop allows us to execute same statements multiple times,and reduces lie of code,and user-friendly ,any one can understand ,instead of rewriting same code multiple times we use loops

there are two types of loops

  • While Loop

  • For Loop

While Loop

the loop is controlled by the condition,as long as the condition is true the statement executes,when the condition is false then loop breaks

while condition:
<indented statement 1>
<indented statement 2>
...
<indented statement n>
<non-indented statement 1>
<non-indented statement 2>

here,the first line is called while clause,whole indented lines are called body of the while loop.

first the while condition is evaluated ,its a Boolean expression so it returns True or False,If the condition is true than the indented lines body of the loop will be evaluated ,then again the controller goes to the condition of the loop and checks whether the condition is True or False ,if the condition is True than same process will be repeated and ,if the condition is False then the While Loop breaks.

Example

x=int(input("enter number"))
sum = 0
while i
enter number334
sum is 55083

check out the while loop example for the sum until given number given above. Condition is I < x, by the end of the while loop there is an iteration, increasing I value by 1 for every loop and sum variable is updated with the addition of the next number in every loop. when the condition I < x fails then the while loop stops and controller goes to the next line after the while loop

For Loop

for loop is used for iterating sequences,because sequences re index in the number manner.

syntax is given below:**

for i in sequence:
# loop body
<indented statement 1>
<indented statement 2>
...
<indented statement n>

we will discuss more about sequences in the coming posts,but now we will see example of for loop

list example

for i in [32,2,42,4,254,4,5]:
print(i)
32
2
42
4
254
4
5

string example

for i in "codeskulls":
print(i)
c
o
d
e
s
k
u
l
l
s
Last updated on by vishal devxo