Reputation: 87
I was learning nested loops, and ran into this problem with line spacing between each of x's lines.
numbers = [2, 2, 2, 2, 7, 7]
for i in numbers:
for j in range(0, i):
print("x", end='')
print('\n')
Following is the output of my code:
xx
xx
xx
xx
xxxxxxx
xxxxxxx
What changes should I make in my code so that an additional line is not present between each x's line?
Upvotes: 1
Views: 986
Reputation: 11612
A simple solution to avoid an unnecessary inner for
loop:
numbers = [2, 2, 2, 2, 7, 7]
for i in numbers:
print('x' * i)
An alternative with f-strings:
filler = 'x'
for i in numbers:
print(f'{filler:{filler}<{i}}')
If you wanted you could also do this in a single print
statement (without loops) using a built-in like map
:
print(*map(lambda i: 'x' * i, numbers), sep='\n')
Upvotes: 1
Reputation: 36
This is working, I have tried
numbers = [2, 2, 2, 2, 7, 7]
for i in numbers:
for j in range(0, i):
print("x", end='')
print()
Best of luck.
Upvotes: 1
Reputation: 5387
Replace print("\n")
with print()
, as print already prints a trailing newline by default.
Upvotes: 3