Looping in python (for & while)

 Loops


1. While loop

In general a loop helps us to repeat things a number of times. Some times though we know we wanted to repeat things but don't know how many times exactly the particular thing has to be repeated. So the number of turns varies for each problem. This is a situation that calls while loop.

The syntax for while loop is as follows,

While (condition):
        #Statements
        #your code

For example,
To print the sum of n numbers
The code goes here

N=int(input()) 
Sum =0
i=0
While (i<=N ):
      Sum =Sum +i
print(Sum)

The above code is executed using while loop. The first line gets the number of terms N from user.
A variable Sum and i are initialized as zero.
The loop runs until  the condition (i<=N) fails . And hence we get the sum of N terms as the output.

Conditional statements in loops :
To print n odd terms
The code goes on here,

N=int(input ())
Sum=0
i=0
While (i<=2N):
    if(i%2!=0):
        Sum+=i
    else:
        Continue
print (Sum)

In this case we have used the conditional statement to add up the odd numbers.

2. For loop
The syntax for "for" loop is ,

for #your condition :
      #your code

For the same example the code using for loop is demonstrated as,

#Sum of n terms
N=int(input())
Sum=0
for i in range(N):
    Sum+=i
print(Sum)

Nested loops :

For example ,

To print a square star pattern,

* * *
* * *
* * *

The code for the above pattern ,

N=int(input())
for i in range (N):
     for j in range (N):
           print ("*",end=" ")
     print ("\n")

In the above case nested for loop is used in which N denotes the length of the square pattern.

More examples using loops,

Example 1 :
To print the items in a list
Code :

l=['a','b',5,7]
for i in range(len(l)):
    print (l[i])

Otherwise,

l=['a','b',5,7]
for i in l:
   print (i)

The same problem using while loop is ,

l=['a','b',5,7]
i=0
while(i<=Len(l)):
    print (l[i])

Example 2 :
To print Factors of a number

Code ,

N=int(input())
for i in range(N):
   if(N%i==0):
      print(i)
   else:
      Continue

 For the same problem using while loop,

N=int(input ())
i=0
while(i<=N):
   if(N%i==0):
     print (i)

Comments

Popular posts from this blog

Finding the percentage in python - HackerRank solution

HackerRank challenges with solutions (Rearrangement, Formula, Word sorting, Numbers, Sentence)

What's your name, Tuple - HackerRank solution in python