Expected Output is 5 4 3 2 1
Print the Program using Python
count=1
price=5
while count<=5:
print(price,end=' ')
price=price-1
count=count+1
- What happens here? Step 1: Create a variable named count and assign the value 1.
Step 2:
Create a variable named price and assign the value 5.
Step 3 (Condition):
The loop runs as long as the value of count is less than or equal to 5.
If count becomes greater than 5, the loop stops.
How the loop works
First, the loop checks the value of count. Initially, it is 1.
The condition count <= 5 is true, so the loop starts.
It prints the value of price and adds a space using end=' '.
Then:
count is increased by 1
price is decreased by 1
Now:
count = 2
price = 4
Again, the condition is checked. Since 2 <= 5, it is still true.
This process continues until count becomes 6. At that point, the condition becomes false, and the loop stops.
Output
5 4 3 2 1
Why is the output horizontal instead of vertical?
Normally, print() moves to the next line after printing.
But here we use:
end=' '
This means:
After printing, a space is added instead of a new line.
So the cursor stays on the same line.
Different end examples
end=' ' → 5 4 3 2 1
end='.' → 5.4.3.2.1.
end='' → 54321
Top comments (0)