I want to print the following:
*
**
***
****
But both
for i in range(5):
for j in reversed(range(5)):
if j < i:
print('*', end='')
print()
and
for i in range(5):
for j in range(5):
if j < i:
print('*', end='')
print()
gives the same answer. isn't the code with reversed supposed to give this?
*
**
***
****
CodePudding user response:
You need to understand what is happening when you run those codes.
for i in range(5): # 0,1,2,3,4
for j in range(5): # 0,1,2,3,4
if j < i:
# when i = 0, no stars printed. j is never less than 0:
# when i = 1, one star printed. when j is 0, print a star.
# when i = 2, two starts printed. when j is 0,1 print stars.
print('*', end='')
print()
for i in range(5): # 0,1,2,3,4
for j in reversed(range(5)): # 4,3,2,1,0
if j < i:
# when i = 0, no stars printed. j is never less than 0:
# when i = 1, on last iteration when j = 0 one start printed.
# when i = 2, two starts printed. when j is 1,0 print stars.
print('*', end='')
print()
So basically both of the for loops are doing the same thing. you are just printing stars. If you want to print spaces, you have to tell the program to print spaces.
for i in range(5): # 0,1,2,3,4
for j in reversed(range(5)): # 4,3,2,1,0
if j < i:
print('*', end='')
else:
print(' ', end='') # telling to print the spaces.
print()
CodePudding user response:
You can use ljust
and rjust
to help:
x = 5
for i in range(x):
print(('*'*i).ljust(x, ' '))
# Output:
*
**
***
****
for i in range(x):
print(('*'*i).rjust(x, ' '))
# Output:
*
**
***
****
CodePudding user response:
Reversing the range doesn't work because it still prints the asterisks the same amount of times in the same way since you are not doing anything with the numbers. As the comments have said, the correct way to do this would be to print spaces before your asterisks. Here is a way to do this:
for i in range(5):
print(" "*(5-i) "*" * i)