Home > Software design >  How to print character every time after a loop is completed
How to print character every time after a loop is completed

Time:10-14

I'm having problems printing the below pattern and don't know how to solve it.

Note: Must use for and while loop.

I'm trying to achieve pattern like:

0
1
####
2
3
####
4
5
####

But I'm getting:

0
1
####
1
2
####
2
3
####
3
4
####

Code I'm using is:

n = 0
for z in range(10):
    while n < 2:
        print(z)
        z  = 1
        n  = 1
    print("####")
    n = 0

CodePudding user response:

You only need one loop. You can chose either while or for

Version with while:

n = 0
while n < 6:
    print(n)
    print(n 1)
    print('####')
    n  = 2

Version with for:

for n in range(0, 6, 2):
    print(n)
    print(n 1)
    print('####')

If really you want to use two loops (might be useful if you want to print series of more than 2 numbers in between the ####):

for n in range(0, 6, 2):
    for z in range(2):
        print(n z)
    print('####')

output:

0
1
####
2
3
####
4
5
####

CodePudding user response:

Be careful because z is taking the value in range() every time the with loop finishes. mozway is right, however I think n should start at 1:

n = 1
while n < 6:
    print(n)
    print(n 1)
    print('####')
    n  = 2

CodePudding user response:

The problem is happening because in z = 1 you're assuming that you're changing the value of z in for z in range(10):, but in this for loop the value of z in each iteration is the next sequence in the list of [0,1,2,3,4], so it discards the z = 1 operation you did, so it repeats the number after the #####.

a solution to this problem would be doing something like this, check if n is 2 in an if statement and don't change the value of z:

n = 0
for z in range(10):
    print(z)
    n  = 1
    if (n==2):
        print("####")
        n = 0

this would print:

0
1
####
2
3
####
4
5
####
6
7
####
8
9
####
  • Related