Home > Blockchain >  I need a better way to implent a condition for this while loop
I need a better way to implent a condition for this while loop

Time:10-18

def factors(x):
    if x >= 0:
            for i in range(1,x): # cannot do mod on 0 
                if (x%i) == 0: # a factor evenly divides with no remainder
                    print(i, end= " " )
    else: print("error message ")
factors(21)
factors(-1)
factors(-3)
 

How can I print factors more organized so you can tell where each factor came from? for example I wanted to print " Factors for 21 are ...... etc. however they are on the same line

My output is : 1 3 7 error message error message

and I want my out put to be

Factors for 21 are : 1 ,3 ,7 error message ( on a new line) error message ( on a new line)

CodePudding user response:

The solution is about finding the right structure. Since you want "Factors for 21 are :" printed first you should start the function printing that. Since you want a new line, you could insert a simple print() after the for-loop.

A solution could be:

def factors(x):
    if x >= 0:
            print(f"Factors for {x} are :", end= " ")
            for i in range(1,x): # cannot do mod on 0 
                if (x%i) == 0: # a factor evenly divides with no remainder
                    print(i, end= " " )
            print()
    else: print("error message ")
factors(21)
factors(-1)
factors(-3)

Always remember that code works in the order you write. So if you want A to happen before B happens, then write the code for A before the code for B.

CodePudding user response:

Try this:

def factors(x):
    if x >= 0:
        print(f"Factors for {x} are:", end=" ")
        for i in range(1,x): # cannot do mod on 0 
            if (x%i) == 0: # a factor evenly divides with no remainder
                print(i, end=", ")
        print()
    else:
        print("error message")
factors(21)
factors(-1)
factors(-3)

We are first printing out the "Factors for..." and putting the end argument so the result happens all on 1 line. Then, in the for loop, we are iterating and place a comma after each iteration. Then, we are using the a regular print statement to create a new line before you print out "error message".

  • Related