 Conditional statements in Python

Program 5:

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

if test_expression:
Body starts
else:
Body ends

while loop syntax

while test_expression:
Body of while

for loop syntax

for value in sequence:
Body of for

if-else statement:

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.
else:
print(‘small number’)

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’
else:
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’.

Output:

Small
Small
Big
Big
Big
All numbers are over

The use of if-elif-else  to implement multiple conditions in a single program:

For example,

x=4
if x<2:
print(‘small’)
elif x<10:
print(‘medium’)
else:
print(‘large’)
print(‘all numbers over’)
output:

medium
all numbers over

Relevant exercises

POST A NEW COMMENT

• Input (stdin)

Output (stdout)

Input (stdin)

Expected Output

Compiler Message

Input (stdin)

2    3