DEV Community

Guna Ramesh
Guna Ramesh

Posted on Edited on

Python Tasks

The following programs clearly explain the concept of indentation and highlight common mistakes we usually make.
1.expected output is "1 1 1 1 1"

program:
count = 1
while count<=5:
print(1, end=' ') #print(1, end='\n')
count=count+1

output:
1 1 1 1 1

What happens in this program?

Initially, the variable count is assigned the value 1

The while loop checks whether count is less than or equal to 5

If the condition is true, the loop executes

Inside the loop, the value 1 is printed followed by a space

After printing, the value of count is increased by 1

Now count becomes 2, and the loop runs again

This process continues until count becomes greater than 5

When count becomes 6, the condition becomes false, and the loop stops
Enter fullscreen mode Exit fullscreen mode

Output
1 1 1 1 1

Additional Note

If you use:

print(1, end='\n')
Enter fullscreen mode Exit fullscreen mode

The output will be:

1
1
1
1
1
Enter fullscreen mode Exit fullscreen mode

Program 1
Expected Output
2 4 6 8 10 6 12
Program
count = 1
while count <= 5:
print(count * 2, end=' ')
count = count + 1

print(count, end=' ')
print(count * 2)
Explanation

Initially, count is assigned the value 1

The loop runs while count <= 5

Inside the loop, count * 2 is printed with a space

After each iteration, count is increased by 1

When the loop ends, count becomes 6

After the loop:

print(count, end=' ') prints 6
print(count * 2) prints 12
Output

2 4 6 8 10 6 12

Program 2
Expected Output
2 4 6 8 10 6
12
Program
count = 1
while count <= 5:
print(count * 2, end=' ')
count = count + 1

print(count)
print(count * 2)
Explanation

The loop works the same as in Program 1

After the loop ends, count = 6

print(count) prints 6 and moves to the next line

print(count * 2) prints 12 on a new line

Output
2 4 6 8 10 6
12
Important Concept: Indentation

If indentation is not handled correctly, the output will be unexpected.

Wrong Program
count = 1
while count <= 5:
print(count * 2, end=' ')
count = count + 1
print(count)
print(count * 2)
What happens?

The last two print statements are inside the loop because of indentation

So they execute in every iteration

This produces repeated and mixed output

Output
2 2
4
4 3
6
6 4
8
8 5
10
10 6
12
Final Key Points

Indentation decides whether code is inside or outside the loop
end=' ' prints in the same line
end='\n' prints in the next line
print() moves to the next line
Always align indentation carefully

Top comments (0)