Informatics Practices
Write the output of the following code:
for i in range (2) :
for j in range (1) :
if i+2 == j:
print ("+",end=" ")
else:
print ("o",end=" ")
Python Control Flow
3 Likes
Answer
o o
Working
Let’s break down the code step-by-step:
Outer Loop:
for i in range(2):
→ This loop iterates over the range of numbers starting from 0 up to but not including 2. So,i
will take on the values: 0, 1.Inner Loop:
for j in range(1):
→ For each value ofi
in the outer loop,j
will iterate over the range of numbers starting from 0 up to but not including 1. So,j
will take on the only value: 0.if i + 2 == j:
→ This condition checks ifi + 2
is equal toj
.print("+", end=" ")
→ If the conditioni + 2 == j
is true, this statement prints a "+", followed by a space, without moving to a new line.print("o", end=" ")
→ If the conditioni + 2 == j
is false, this statement prints an "o", followed by a space, without moving to a new line.
Let’s analyze the loops iteration by iteration:
- First iteration of the outer loop (i = 0):
- Inner loop (j = 0):
i + 2 == j
becomes0 + 2 == 0
, which is2 == 0
, is false.- Therefore, the
else
block is executed, and the output iso
- Second iteration of the outer loop (i = 1):
- Inner loop (j = 0):
i + 2 == j
becomes1 + 2 == 0
, which is3 == 0
, is false.- Therefore, the
else
block is executed, and the output iso
So, combining the outputs of all iterations, the full output will be:
o o
Each "o" is followed by a space, and there is no new line between them due to the end=" "
parameter in the print
function.
Answered By
1 Like
Related Questions
Write the output of the following:
for x in range (10, 20): if (x % 2 == 0): continue print (x)
Write the output of the following program on execution if x = 50:
if x > 10: if x > 25: print ( 'ok' ) if x > 60: print ( 'good' ) elif x > 40: print ( 'average' ) else: print ('no output')
WAP to display even numbers between 10 and 20.
WAP to perform all the mathematical operations of a calculator.