Loops in Python:
Note: In python we use indentation to mark the length of the loops. In other words, we use specific gaps/ spaces to mark the region of the loop. The syntax for the conditional statements are listed below.
if-else statement syntax
while loop syntax
Body of while
for loop syntax
for value in sequence:
Body of for
if is a conditional statement which executes only if the condition declared is True. For example,
x=4 #declared a variable with an integer value of 4.
if x > 2: # remember to give a colan, check if condition is true
print(‘big number’) # indentation (gap) refers to the body of the loop.
In the above code, if the condition x>2 is True: then all the lines in the indent followed by the ‘if’ conditional statement are executed
Let us consider another example program for ‘for loop’
S=[1,2,3,4,5] #declare a list of numbers
for I in S: # for every I in the list S
if i>2: # check if the current value of I is greater than 2
print(‘big’) # if condition true, print ‘big’
print(‘small’) #if above condition is false, print ‘small’
print(‘all numbers are over’) # observe indentation. The print statement is in line with for statement, stating that it is no more in the ‘for loop’.
All numbers are over
The use of if-elif-else to implement multiple conditions in a single program:
print(‘all numbers over’)
all numbers over