Wednesday, February 19, 2020

For loop pattern printing in python


for i in range(5):
    print("anil")
output:
anil
anil
anil
anil
anil

example:
for i in range(0,5,2):
    print("anil",i)

output:
anil 0
anil 2
anil 4

example:
for i in range(0,10,2):
    print("anil",i)

output:
anil 0
anil 2
anil 4
anil 6
anil 8

example :
for i in range(1,10,2):
    print("anil",i)

output:
anil 1
anil 3
anil 5
anil 7
anil 9

example:
for i in range(0,10,5):
    print("anil",i)

output:
anil 0
anil 5

example:
for i in range(0,30,5):
    print("loop",i)

output:
loop 0
loop 5
loop 10
loop 15
loop 20
loop 25

example:

for x in range(5):
    for y in range(5):
        if y>=x:
            print("*",end = '')
    print()


output:
*****
****
***
**
*

example 2:
for x in range(5):
    for y in range(5):
        if y<=x:
            print("*",end = '')
    print()

output:
*
**
***
****
*****

similar output:

for x in range(0,5):
    for y in range(0,x):
        print("*",end='')
    print("\n",end='')

output:
*
**
***
****

example 3:
n=int(input("Enter number of rows:"))
for i in range (1,n+1):
    print(" "*(n-i),end="")
    print("*"*i)

output:
    *
   **
  ***
 ****
*****


example 4:
n=int(input("Enter number of rows:"))
m = (2 * n) - 2
for i in range(0, n):
    for j in range(0, m):
        print(end=" ")
    m = m - 1
    for j in range(0, i + 1):
        print("* ", end=' ')
    print(" ")

output:
Enter number of rows:6
          * 
         *  * 
        *  *  * 
       *  *  *  * 
      *  *  *  *  * 
     *  *  *  *  *  * 

example 5:
k = 0
rows = int(input("enter number of rows:"))
for i in range(1, rows+1):
    for space in range(1, (rows-i)+1):
        print(end="  ")
    while k != (2*i-1):
        print("* ", end="")
        k = k + 1
    k = 0
    print()

output:

enter number of rows:10
                  *
                * * *
              * * * * *
            * * * * * * *
          * * * * * * * * *
        * * * * * * * * * * *
      * * * * * * * * * * * * *
    * * * * * * * * * * * * * * *
  * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * 

python class topic video