Nested Loop Code Help
On 1/26/20 10:15 AM, ferzan saglam wrote:
> Hello people, I have written the code below which works fine, but it has one small problem. Instead of printing one (x) on the first line, it prints two.
> I have tried everything in my knowledge, but cannot fix the problem.
> Thanks for any help in advance.
> for x in range ( 0, 10):
> stars = 'x'
> count = 0
> while count < x:
> stars = stars + 'x'
> count = count + 1
> print (stars)
> Output I am trying to get Output I am getting
> x xx
> xx xxx
> xxx xxxx
> xxxx xxxxx
> xxxxx xxxxxx
> xxxxxx xxxxxxx
> xxxxxxx xxxxxxxx
> xxxxxxxx xxxxxxxxx
> xxxxxxxxx xxxxxxxxxx
First skill is to learn to act like an interpreter, and execute the
instructions one by one.
First we execute the for x in range (0, 10): statement which will set x to 0
Then we set stars to 'x'
Then we set count to 0,
since the while outdents, that ends the loop and we repeat it with x
having values 1, 2, 3, and up to 9
THEN we go to the bottom loop.
Count is 0, x is 9 so the while is satisfied, so we do a loop
stars = stars + 'x' which is 'xx'
count = count + 1 which is 1
print(stars) prints 'xx'
that ends one pass thru the while loop, so we do the test again
Count is 1, x is 9, so the while is satisfied, so we do a loop,
stars = stars + 'x', which is 'xxx'
count = count + 1, which is 2
print(stars) prints 'xxx'
this continues until count reaches 9 (the value left in x) at which it
Thus the loop ran 9 times (for starting values of count = 0, 1, 2, 3, 4,
5, 6, 7, 8
Think about what you wanted to do and what the code actually did.
The first for x in range (0, 10) doesn't really do what I think you
wanted, did you mean for the second loop to be nested in it?
If you do nest the second loop, you probably don't want the print at the
end part of the second loop.