26
loading...
This website collects cookies to deliver better user experience
****
***
**
*
**
***
****
for i in range(4, 1, -1):
print('*' * i)
for i in range(1, 5):
print('*' * i)
range(a, b, c)
creates an iterator loop from a
to b
by c
. the a
is inclusive but b
is not. If c
is 1, you can omit it since it's the default anyway. Thus range(4, 1, -1)
generates [4,3,2]
while range(1, 5)
generates [1,2,3,4]
.i
to multiply with '*'
because python multiplication with string causes that string to be repeated i
times, e.g. '*' * 3
generates '***'
for
loop:for i in range(1, 8):
if (i < 4):
print('*' * (5 - i))
else:
print('*' * (i - 3))
[1,2,3,4,5,6,7]
to [4,3,2,1,2,3,4]
so then we took these values to get multiplied by *
. If it takes a while to grasp why I put these values on, I'll try to explain here:# i < 4
i = 1 => 5 - 1 = 4
i = 2 => 5 - 2 = 3
i = 3 => 5 - 3 = 2
# else (i >= 4)
i = 4 => 4 - 3 = 1
i = 5 => 5 - 3 = 2
i = 6 => 6 - 3 = 3
i = 7 => 7 - 3 = 4
[1,2,3,4,5,6,7]
to [4,3,2,1,2,3,4]
with a single equation. Math is powerful 💪.for i in range(1, 8):
print('*' * (abs(i - 4) + 1))
abs()
built-in without importing any modules. This reduces our code lines from 5 to 2 💪.print()
function outside the loop. This can be done with a temporary variable that holds the whole string in a loop:output = []
for i in range(1, 8):
output.append('*' * (abs(i - 4) + 1))
print('\n'.join(output))
output
and use that to print output
once. Note that we use '\n'.join(output)
which converts the array to string with \n
between values. \n
simply means a new line, for each string, we add during for loop.variable = []
for item in list:
variable.append(expression(item))
variable = [expression(item) for item in list]
print('\n'.join(['*' * (abs(i - 4) + 1) for i in range(1, 8)]))
print('\n'.join(['*'*(abs(i-4)+1)for i in range(1,8)]))