Home > Software engineering >  How to turn it into a while loop?
How to turn it into a while loop?

Time:03-19

What is the form of the for loop code below, if it is converted into a while loop?

This is the code:

    def number(a):
        b = 1
        for c in range(1, a 1):
            b*=c
        return(b)
    
    a = 6
    for d in range(a, 0, -1):
        print(number(d),end=' ')
        for e in range(d, 0, -1):
            print(e, end = ' ')
        print('')
 

This is the output:

    720 6 5 4 3 2 1 
    120 5 4 3 2 1 
    24 4 3 2 1 
    6 3 2 1 
    2 2 1 
    1 1 

CodePudding user response:

a = 6
for d in range(a, 0, -1):

Here it is saying that a=6, and the for loop is running from 6 till 0, and stepping by -1 each time. To turn it into a while loop you can just do:

a = 6
while a > 0:
    a -= 1
    # and so on

Assuming your question is that you wanted to turn the for loop into a while loop, that is how I would do it, but I don't see the point unless there is something very specific you need to do.

CodePudding user response:

How about this line? After the for line:

a = 6
for d in range(a, 0, -1):

I still don't understand changing the for loop for the code below, because this line has a for d in it as a prefix:

    def number(a):
    b = 1
    c = 1
    while c <= a:
        c  = 1
        b*=c
    return(b)

a = 6
while a > 0:
    a -= 1
    print(number(a))
    #for e in range(d, 0, -1):
    #    print(e, end = ' ')
    #print('')

The code that I have hashed, is still my problem, what is the solution in that line of code

The output of the program code has just arrived as below:

720
120
24
6
2
1
  • Related