Posts

Showing posts with the label for loop

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