I am required to use nested for loops and print(\'*\', end=\' \')
to create the pattern shown here:
And here is my code. I have figured out the first t
print("Pattern C")
n=int(input("Enter number of rows: "))
for i in range (n,0,-1):
print((n-i) * ' ' + i * '*')
Pythonic way of doing this. Just 1 line of code (using list comprehension) for each pattern.
n = 10
# for A
print('\n'.join(['*'*i for i in range(1,n+1)]))
#output
*
**
***
****
*****
******
*******
********
*********
**********
# for B
print('\n'.join(['*'*i for i in range(n+1,0,-1)]))
#output
***********
**********
*********
********
*******
******
*****
****
***
**
*
# for C
print('\n'.join([' '*(n-i) + '*'*i for i in range(n,0,-1)]))
#output
**********
*********
********
*******
******
*****
****
***
**
*
# for D
print('\n'.join([' '*(n-i) + '*'*i for i in range(1,n+1)]))
#output
*
**
***
****
*****
******
*******
********
*********
**********
using spaces you can create different- different patterns: 1.
def pattern(limit):
for i in range(limit+1):
print((limit-i)*" "+ ' #'*i)
pattern(4)
Output:
#
# #
# # #
# # # #
2.remove one space from above code and pattern will be changed in a pyramid
def pattern(limit):
for i in range(limit+1):
print((limit-i)*" "+ ' #'*i)
pattern(4)
output: #
# #
# # #
# # # #
3: no space print((limit-i)*""+ ' #'*i) will create
#
# #
# # #
# # # #
i=0
while(i<5):
j=0
while(j<=i):
print("*",end="") #end="" is given to stay on same line
j=j+1
print("") #it will take u to new line
i=i+1
j=0
i=i-2
j=i
while(i>=0):
while(j>=0):
print("*",end="")
j=j-1
print() #will also work
i=i-1
j=i
this will also work
learn an easy way:
code1:
for n in range(0,5):
n +=1
print ("*" *(0+n))
what it does:
output:
*
**
***
****
*****
code2:
for n in range(-5,0):
n +=1
print ("*" *(0-n+1))
output:
****
***
**
*
def fun (n):
return n
n=int(raw_input("Enter the number"))
print "The given number is",n
for i in range (n,0,-1):
print "*"*i
output:
The given number is 3
***
**
*